Compare commits

..
97 Commits
Author SHA1 Message Date
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
noahandClaude Opus 4.8 be2eab6262 feat(flash): readable network-only stock<->alkane install/restore for a113d (and zynq)
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 0s
a113d (Amlogic AXG, Antminer BHB42XXX) - VALIDATED end-to-end on bench hardware:
- aml_ubi.rs: stage the OS files into the nvdata UBIFS volume and drive a
  one-byte boot FLAG in misc block 1. Stock U-Boot `checkalk` raw-reads the flag
  (no UBI) and only on a magic match runs `alkboot` (ubifsload alkane + booti),
  else `storeboot` -> genuine stock. Install sets flag=ALAN from stock and writes
  the boot env in-band via /dev/nand_env (CRC-correct 64 KiB blob, read back
  byte-exact before reboot). Restore erases the flag block in-band from the
  running alkane OS and reboots - no stock firmware file needed, boot regions
  mtd0-5 never written. The magic is tested byte-by-byte (this vendor U-Boot's
  `itest.l *<mem>` mis-compares; `itest.b` works).
- stock.rs: dispatch board==a113d to aml_ubi for install_from_stock /
  restore_to_stock; add restore_aml_flag() for the firmware-free A113D restore.
- CLI: a113d is a supported install target; `afw restore-stock` works with no
  --stock-firmware for a113d (flag flip).

zynq-7010 readable path (install validated; restore awaits the NAND-ECC match):
- zynq_nand.rs + uimage.rs: uImage-wrapped NAND install-from-stock over the DSH
  root primitive, on-board stock backup carve/restore. Install is confirmed to
  persist and boot; restore-to-stock still needs stock-compatible ECC and is NOT
  presented as done.

stock_method.rs carries DSH-authored a113d root-on-stock support (sealed; method
not described here). 92/92 alkane-flash tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-14 00:43:30 -06:00
DeepSeek Harness 15df9086c1 feat(flash): expose root command and file primitives for stock boards
Add StockMethod::root_exec and StockMethod::root_put, with public wrappers next to the existing stock methods. root_exec runs a /bin/sh command line as root and returns combined output; root_put writes a payload at mode 0644 with parent directories created and supports multi-megabyte data. Existing install and restore paths are unchanged. Test coverage adds compile-level signature checks plus local path, quoting, and streamed-input tests; no test uses the network.
2026-11-13 15:21:44 -06:00
noahandClaude Opus 4.8 d2d4c085ae fix(gui): per-target credentials for install and restore (#46, #51)
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 31m29s
"Install failed due to credentials" was the #46 change pulling one generic
saved SSH login for both directions. Install targets a stock board and restore
targets an alkane board, which need different logins. Add the alkane
control-board login to the shipped defaults ("Alkane" root/alkane) and a
`cred_for(firmware)` helper (saved per-firmware override, else shipped default).

Install now uses the selected stock board's firmware login (e.g. AntMiner
root/root); restore and the on-board-backup probe use the alkane login
(root/alkane). No password field; both overridable per-firmware in Settings.
Confirmed on the bench S17 at 10.255.1.111: its alkane login is root/alkane.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 14:08:28 -06:00
noahandClaude Opus 4.8 6e785275da feat(gui): two-choice restore, dialogs-during-scan, creds-from-settings
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 12m59s
Restore-to-stock dialog overhaul (issues #46, #47, #48, #51): a two-source
restore -- the board's on-board stock backup (checkbox, auto-detected via the
merged alkane-flash onboard_stock_backup_present and greyed out with
set_enabled when absent) or a Bitmain stock firmware file picked with a Browse
button (OTA .tar.gz or SD .zip, any X17-series model). The alkane root login
comes from Settings (no per-dialog password field); on-board restore uses the
new stock_ops::start_restore_onboard over DSH's restore_from_onboard_backup.

Install dialog: password field removed too (#46); the login comes from Settings.

Dialogs during scan (#43): install/uninstall dialogs open and can be prepared
while a scan runs (new flash_busy gate); the scan is stopped only when the
operation actually starts (stop_scan_for_op) so the two never touch a board at
once.

Bug report (#50): the always-present "Open issue" button is gone; filing turns
it into a clickable "View issue #N" link.

wx-rs: add set_enabled (grey out a control); captured as patch 0013. Merges
DSH's alkane-flash on-board backup/restore method (sealed in stock_method.rs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 13:53:28 -06:00
noah 9d49c4b070 Merge commit 'bccfaae2faf60a61c262ee472609cfd9c587b582' into fix/gui-install-and-scan-1113 2026-11-13 13:40:31 -06:00
noahandClaude Opus 4.8 dd3cff19cb ci(verify): drop verify-windows from the PR gate (Windows builds at release)
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 13m56s
The Windows mingw+Wine cross-build roughly doubled PR wall-clock. Move it off
the PR gate: PRs now verify Linux (clippy, build, tests, self-test) fast, and
the Windows build is still produced and shipped by the main release run
(build-test-release / windows-native), so a Windows-only regression surfaces on
the merge to main.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 13:01:37 -06:00
noahandClaude Opus 4.8 25047a603a style(gui): rustfmt + clippy fixes for the review changes
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 44m33s
verify / verify-windows (pull_request) Canceled after 0s
Apply cargo fmt to the edited gui sources and switch a board_status membership
check from iter().any() to contains() so `cargo fmt --check` and
`clippy -D warnings` (the verify CI gates) pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 12:15:41 -06:00
noahandClaude Opus 4.8 69dcedbd9c build(wx-rs): capture the word-wrap text-ctrl edit into the patch queue
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 8m11s
verify / verify-windows (pull_request) Skipped
The #37 wrap fix edited the vendored wx-rs tree (wxbr_text_ctrl_wrap in the C++
bridge + text_ctrl_wrapped in widgets.rs) but not the patch queue, so the
`wx_rs_patches.py check` CI gate failed. Capture the delta as patch 0012 so the
queue reproduces the patched tree again.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 12:02:38 -06:00
DeepSeek Harness bccfaae2fa flash: restore the Zynq from its on-board stock backup
A from-stock install now leaves a complete genuine-stock backup on the
board (stock device tree, kernel and ramdisk) in the reserved NAND region
after the alkane MAC area, clear of the stock configs UBI and all alkane
boot slots.

Add network-only StockMethod calls to check for that backup and restore
the board to genuine stock from it, with public wrappers and interface
tests. BOOT.bin is preserved.

Verified: cargo build -p alkane-flash; cargo test -p alkane-flash
(74 passed, 1 ignored).
2026-11-13 11:45:16 -06:00
noahandClaude Opus 4.8 7cd26aff56 fix(gui): address code-review findings on the install/scan changes
verify / verify (pull_request) Failing after 5m53s
verify / verify-windows (pull_request) Skipped
source / check (pull_request) Skipped
- #1 Update must not rewrite the bootloader: start_install refuses a tier-3
  (bootloader-writing) .afw when the dialog is an in-place Update, enforcing the
  "BOOT.bin is never written" guarantee.
- #2 post-install verify could stick forever when auto-scan is off: tick() now
  re-probes awaiting boards on a fixed 10 s cadence until they answer as alkane
  or the give-up window expires.
- #3 board-health no longer greys a genuinely-mining miner whose backend omits
  per-board active/working_chips: (None,None) reads green when the miner is
  hashing, grey only when idle (the bare S17 case).
- #5 install docs/comments no longer describe the removed typed-FLASH step.
- #6 the flash-plan checklist verifies against the install target board, so a
  file for another board surfaces as an error instead of a misleading plan.
- #7 install board is taken from the selected row's board_family, not a fixed
  default (correct once more boards are supported).
- #4 (verify on the UI thread) accepted: .afw bundles are ~7 MB, so the manifest
  read is a sub-100 ms hash, not a user-visible freeze.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 11:22:00 -06:00
noahandClaude Opus 4.8 4f59233064 feat(gui): live activity-log view toggled from the toolbar
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 7m4s
verify / verify-windows (pull_request) Skipped
A "Log" toolbar button replaces the fleet table with a live view of the
toolkit activity log (what it is currently doing); the button flips to "Table"
to switch back. The view tails the log, appending new lines and staying
scrolled to the newest entry. Verified under a virtual display.

Placed in the toolbar (top-right) rather than the status bar: the native wx
status bar that holds the zoom slider cannot host a wx button, and the content
sizer has no insert, so a true bottom-right button needs extra plumbing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 11:06:56 -06:00
noahandClaude Opus 4.8 7e0174fda1 feat(gui): progress bar in the Health cell during install/restore (#42)
source / check (pull_request) Skipped
verify / verify-windows (pull_request) Canceled after 0s
verify / verify (pull_request) Canceled after 4m10s
While a board installs or restores, its Health cell shows a phase-based ASCII
progress bar ("installing [#######---] 70%") instead of a static "installing".
Phases map to indicative, monotonic percents (acquire < verify < write). Adds
unit tests for the bar and the phase->percent mapping.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 11:01:23 -06:00
noahandClaude Opus 4.8 7d5f250254 feat(gui): install picker reads any repo with board-compat filtering
verify / verify-windows (pull_request) Canceled after 0s
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 1m5s
The install dialog gains a "Release repo (owner/repo)" field (default
blueflare/alkane-os) and a Reload button. Releases are scanned from the chosen
repo via ReleaseSource::for_repo and filtered to those with an .afw compatible
with the target board (ReleaseInfo::is_compatible_with). Verified under a
virtual display: the picker populates with the alkane-os release unauthenticated
now that the repo is public, and the repo field + Reload render.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 10:59:10 -06:00
noahandClaude Opus 4.8 fbf44889ea feat(gui): post-install verify, flash-plan checklist; backend helpers
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 2m0s
verify / verify-windows (pull_request) Canceled after 0s
Stock->alkane re-scan flicker: after a successful install the just-installed
boards are held in a "verifying alkane..." state and a stock re-scan row is
suppressed until the board answers as alkane, with a bounded give-up window.
Fixes the board re-scanning as stock before finally showing alkane.

Flash-plan checklist: picking a local .afw in the install dialog now detects
the flash tier and shows a [x]/[ ] checklist of what it overwrites (U-Boot /
Kernel / Userspace), read from the bundle manifest. Verified end-to-end under
a virtual display: a zynq-7010 .afw shows tier 2, U-Boot preserved, kernel and
userspace written.

Backend helpers (alkane-artifacts, additive, unit-tested):
- AfwManifest::flash_plan() -> FlashPlan { tier, writes_uboot, writes_kernel,
  writes_userspace }.
- ReleaseSource::for_repo(owner, repo) and ReleaseInfo::compatible_boards /
  is_compatible_with, for the upcoming any-repo picker with board-compat
  detection.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 10:56:04 -06:00
noahandClaude Opus 4.8 f9cd12b374 feat(gui): drop typed-FLASH step; raise report-relay rate limit
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 8m16s
verify / verify-windows (pull_request) Skipped
Issue #41: installing alkane OS and restoring to stock no longer require
typing FLASH. The dialog, the board list and the Install/Restore button are
the confirmation; the destructive-action warning stays visible. Removes the
now-unused confirm inputs from the install and uninstall dialogs.

Report relay: raise RATE_PER_IP 5 -> 100 and RATE_GLOBAL 60 -> 300 so bench
testing can file more reports without hitting the hourly cap. Applied live on
the Gitea host and recorded here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 10:18:36 -06:00
noahandClaude Opus 4.8 aab9b63350 fix(gui): install feedback, local .afw picker, scan icons, report wrap
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 10m54s
verify / verify-windows (pull_request) Skipped
Addresses the bench bug reports filed from the toolkit (issues #37, #38, #39)
and the request for a local-file install source.

Install (issue #38): the install never reached the worker in the reported
case and aborts were only a status-bar line, so the operator saw nothing.
Abort reasons (missing FLASH keyword, no release/asset, no target) now raise
the visible error indicator and keep the dialog open; the actual per-board
failure detail is surfaced and logged instead of a bare count; a clear
"installing..." line and log entry mark the start.

Install source (requested): the install dialog gains a "Browse local .afw"
button beside the Gitea release picker, in the same window. A chosen file
takes precedence over the selected release. start_install takes an AfwSource
(Release or Local); a local file is used in place, a release is downloaded as
before. This brings the CLI's local-file install to the GUI.

Scan icons (issue #39): a hashboard the firmware lists with no active flag and
no working-chip count now reads grey (not detected) instead of green, and the
PSU bolt greens only on real delivery evidence (watts, PSU fan, or PSU output)
-- is_mining counts only when the miner is actually hashing. A stock S17
control board with no PSU or hashboards attached asserts a cgminer mining
status at zero watts, which previously showed green board and PSU icons.
Confirmed against the bench S17 at 10.255.1.111 (reports watts=0). Regression
tests added for both.

Bug report (issue #37): the report box word-wraps instead of running off the
edge (new wx text_ctrl_wrapped without wxTE_DONTWRAP). Sub-window movability
is window-manager behaviour (the dialog already has a caption and resize
border) and is not changed here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 09:45:46 -06:00
noah 224b3b37e8 Merge pull request 'main: find Alkane OS boards in the scan; install/update/uninstall only where they apply' (#36) from next into main
build-test-release / release (push) Successful in 21m54s
build-test-release / windows (push) Successful in 32m55s
2026-11-12 15:42:14 -07:00
noah 1fa4aa5532 Merge pull request 'next: find Alkane OS boards in the scan; install/update/uninstall only where they apply' (#35) from feature/alkane-scan into next
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 16m28s
verify / verify-windows (pull_request) Successful in 9m18s
next-build / windows (push) Successful in 4m21s
next-build / candidate (push) Successful in 19m23s
2026-11-12 15:13:17 -07:00
noahandClaude Opus 5.5 315c595714 gui: find boards running Alkane OS in the scan; offer install/update/uninstall only where they apply
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 7m17s
The fleet scan (asic-rs) recognises miners by their cgminer socket or vendor
web UI. A board running Alkane OS exposes neither, so it never appeared and
could not be right-clicked; the periodic refresh also marked it offline.

- alkane_detect: probe addresses asic-rs does not identify over HTTP:
  GET /api/identity (alkane-os 0.1.2+: os, version, board, MAC, hostname),
  falling back to /api/summary's "alkane-os" STATUS for older images. Used by
  the scan and the refresh. Rows show Firmware "Alkane" with the version, MAC,
  hostname and control board (XIL (C49) for zynq-7010).
- Context menu: "Install alkane OS..." only for a supported board (control
  board alkane-os has an image for; a stock Antminer on XIL (C49), or by model
  S17/S17 Pro/T17 when the stock miner software is down and reports no board)
  that is not running Alkane; "Update alkane OS..." for a supported board
  already running it (same dialog, updated in place); "Uninstall alkane OS"
  only for boards running Alkane. Mixed selections get neither install nor
  update.
- Docs updated.

Verified live on the bench S17: running Alkane -> found as Alkane 0.1.2,
XIL (C49), update + uninstall offered; restored to stock -> found as Antminer
S17 Stock, install offered. Unit tests for the probe parsing and the menu
rules; an ignored live scan test (ALKANE_TEST_SCAN_RANGE).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 16:01:40 -06:00
noah 50102800a3 Merge pull request 'main: promote next (alkane-os install/uninstall, genuine-firmware restore, Zynq fixes)' (#32) from next into main
build-test-release / windows (push) Successful in 7m25s
build-test-release / release (push) Successful in 19m26s
2026-11-12 13:11:50 -07:00
noah a998d7a3e3 Merge pull request 'next: ignore the curl-dependent asset-fetch test on Windows' (#34) from feature/afw-os-bundle into next
next-build / windows (push) Successful in 5m12s
next-build / candidate (push) Successful in 5m12s
verify / verify (pull_request) Successful in 11m50s
source / check (pull_request) Skipped
verify / verify-windows (pull_request) Successful in 6m55s
2026-11-12 12:51:54 -07:00
noahandClaude Opus 5.5 cd02ff47a5 test: ignore the curl-dependent asset-fetch test on Windows
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m15s
stock_method's fetch test shells out to curl. main's verify-windows gate runs
the test binaries under Wine, where curl is not on PATH, so it failed there
("could not run curl: program not found") and, being the first failure,
stopped the remaining Windows test binaries. Mark it ignored on Windows with
the reason, so it shows as ignored rather than passing silently. Locally under
Wine all headless crates' Windows tests pass; Windows-target clippy is clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 13:47:20 -06:00
noah 836a531e93 Merge pull request 'next: update the PR change-surface self-test for the GUI's new dependencies' (#33) from feature/afw-os-bundle into next
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 11m22s
verify / verify-windows (pull_request) Failing after 7m5s
next-build / windows (push) Failing after 7s
next-build / candidate (push) Skipped
2026-11-12 12:24:50 -07:00
noahandClaude Opus 5.5 8d72f07cf0 ci: update the PR change-surface self-test for the GUI's new dependencies
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 5m16s
alkane-gui now depends on alkane-flash and alkane-artifacts (right-click
install/uninstall, release picker), so a change in either reaches the GUI
graph and needs the full build. pr-surface.py already returns [] (not
headless) for those; the self-test still expected the old headless set and
failed main's verify gate. Pin the new graph: artifacts -> [], flash -> [],
access + flash -> [], access + cli -> [access, cli].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 13:18:58 -06:00
noah bdea96229b Merge pull request 'next: rustfmt the afw/stock work (no behaviour change)' (#31) from feature/afw-os-bundle into next
next-build / candidate (push) Successful in 4m56s
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 31s
next-build / windows (push) Successful in 4m11s
verify / verify-windows (pull_request) Skipped
2026-11-12 12:13:07 -07:00
noahandClaude Opus 5.5 d318b734fa style: rustfmt the afw/stock work (no behaviour change)
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m17s
main's verify gate runs cargo fmt --check on the first-party crates; next's
gate does not, so the afw/stock feature work reached next unformatted. Pure
cargo fmt output. clippy -D warnings (workspace and GUI) and all tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 13:01:21 -06:00
noah 4305da5e57 Merge pull request 'next: Zynq restore uses the factory device tree; tier-2 in-place update and verify-live for Zynq' (#30) from feature/afw-os-bundle into next
next-build / windows (push) Successful in 3m56s
next-build / candidate (push) Successful in 4m18s
Merge pull request #30: Zynq restore uses the factory device tree; tier-2 in-place update and verify-live for Zynq
2026-11-12 11:04:00 -07:00
noahandClaude Opus 5.5 dc787f1f3b flash: Zynq tier-2 update in place through the verified writer; verify-live for Zynq
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m24s
The Zynq tier-2 install wrote raw images at device-relative offsets on
/dev/mtd0 and /dev/mtd1. On the current alkane image those are stock-cfg and
alkane-cfg, not the boot regions, so it would have erased alkane-cfg first, and
its raw zImage/cpio are not bootable by the stock U-Boot. Its preflight only
checked that mtd0 and mtd1 existed.

- Add StockMethod::update_in_place: refuses a board not running alkane,
  re-registers the boot regions (as restore does), saves every slot locally
  before any erase, writes rootfs/dtb/kernel as the uImages the stock U-Boot
  boots via the shared target builder (BOOT.bin guard, md5 readback), reboots
  and waits for alkane. --dry-run reports the live storage map and the plan.
- boards::zynq keeps the manifest gate; the plan is now in absolute NAND slots
  with ceilings that leave room for the uImage header. The stale writer and
  preflight are removed.
- CLI: Zynq preflight/install use the new path before the generic user
  transport connects.
- verify-live gains a Zynq check (HTTP marker, case-insensitive, plus root SSH
  reporting alkane and the installed kernel; prints the kernel cmdline). It
  previously fell through to the CV1835 check.
- Tests for the protected alkane map, registered and split boot maps, slot
  overrun, and the BOOT.bin guard.

Verified on an S17 (Zynq-7010): dry run, install from a RAM-booted alkane,
NAND boot confirmed on the serial console, verify-live PASS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 11:49:53 -06:00
noahandClaude Opus 4.8 f63127d633 flash: restore uses the correct per-board device tree, not the package's
The kernel device tree is never in Bitmain's distributable firmware: all OTA
packages ship none, and the SD recovery image preserves the factory dtb rather
than writing one. The device tree I was taking from the SD recovery package was
its SD-boot dtb (a different partition layout), which does not match the genuine
rootfs and reboot-loops the board.

Fix: restore now takes only the genuine kernel + rootfs from the vendor package
(RestoreImages drops the dtb field), and the method supplies the correct
per-board device tree itself (fetched + verified from the public assets repo, the
same way the NAND-exposing helper is fetched). This pairs genuine kernel/rootfs
with the factory dtb that matches their partition layout. Any genuine package now
works (an OTA .tar.gz as well as an SD .zip), since the package's own dtb is no
longer needed.

cli/gui: --stock-firmware / the uninstall dialog no longer require a package with
a device tree. docs updated.

NOTE: not yet hardware-verified - the bench S17 is mid-recovery (serial-link
hardware issue) and must be brought back before this can be proven on the board.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 21:07:44 -06:00
noah b02a14bcfc Merge pull request 'next: refresh to main + afw OS bundle (install/uninstall, GUI, genuine-firmware restore)' (#29) from release/next-refresh into next
next-build / windows (push) Successful in 4m25s
next-build / candidate (push) Successful in 6m16s
2026-11-11 17:32:59 -07:00
noahandClaude Opus 4.8 20dff12c05 ci: align next-only bench-pages.yml to the canonical runner image
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m27s
The merge brought next's bench-pages.yml with its stale October runner-image
pin; align it to ci/runner-image.txt so the source gate passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 18:27:57 -06:00
noah ac6bc20c68 Merge branch 'feature/afw-os-bundle' into release-next-stage
source / check (pull_request) Failing after 20s
verify / verify (pull_request) Skipped
2026-11-11 18:21:46 -06:00
noah 8f0accf21d Merge remote-tracking branch 'origin/main' into release-next-stage
# Conflicts:
#	.gitea/workflows/ci-badge.yml
#	.gitea/workflows/next.yml
#	.gitea/workflows/release.yml
#	.gitea/workflows/source.yml
#	.gitea/workflows/verify.yml
#	Cargo.lock
#	README.md
#	ci/bench-badge.py
#	ci/bench_history.py
#	ci/cleanup-generated.py
#	ci/coverage.sh
#	ci/gen-badges.py
#	ci/publish-metrics.py
#	ci/test-bench-badge.py
#	ci/test-bench-history.py
#	crates/alkane-access/src/lib.rs
#	crates/alkane-artifacts/Cargo.toml
#	crates/alkane-artifacts/src/lib.rs
#	crates/alkane-cli/Cargo.toml
#	crates/alkane-cli/src/main.rs
#	crates/alkane-gui/src/model.rs
2026-11-11 18:21:46 -06:00
noahandClaude Opus 4.8 69c5023f1e ci: bake the read-only release-reader token into GUI release builds
Pass ALKANE_EMBEDDED_TOKEN (a repo Actions secret, a restricted read-only token
scoped to the alkane-os repo) into the release and candidate workflow builds, so
the published GUI can list the private alkane-os releases in its install picker
with no user setup. The source tree carries no secret (option_env!); the value
lives only in CI-built binaries.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 18:11:26 -06:00
noahandClaude Opus 4.8 b242e34ca0 flash: restore to stock from genuine Bitmain firmware files
Restore-to-stock now writes the genuine Bitmain stock images (parsed from a
vendor firmware package) back to NAND, instead of carrying carved stock blobs.

- stock_firmware: new parser for genuine Bitmain Antminer packages - the OTA
  update .tar.gz (outer sign wrapper -> inner fw.tar.gz) and the SD recovery
  .zip. Extracts BOOT.bin / devicetree.dtb / uImage (kernel) / uramdisk (rootfs)
  and verifies the rootfs md5 when the package lists one. Shells out to the
  system tar/unzip. Verified against real S17 packages.
- stock: restore_to_stock now takes the stock images (RestoreImages); the stock
  kernel/dtb/rootfs are no longer carried as assets. The boot regions are not
  exposed to Linux on alkane, so the existing NAND-registration helper is kept to
  make them writable, then the supplied genuine images are written at the vendor
  offsets (dtb 0x1a00000, kernel 0x2000000, rootfs; BOOT.bin preserved).
- The SD recovery image is the complete source: it includes the device tree,
  which the stock legacy-uImage kernel needs at 0x1a00000 and which the OTA
  update packages omit. Restore requires it and points the user to the SD image
  when a package has no dtb.
- Post-reboot the board returns to stock under its stock MAC and typically takes
  a new DHCP lease, so a wait on the original address is best-effort and no longer
  reported as a failure.
- cli: afw restore-stock takes --stock-firmware <file>. gui: the uninstall dialog
  takes the firmware file path.

Also clear the branch's clippy debt so the full gate passes: a type alias/allow
for the hardware map tables and multi-arg write functions, plus small mechanical
fixes (useless format, op-ref, collapsible match). wx-rs patch 0011 records the
wxWidgets 3.2 build-compat edits.

Verified on the bench S17: install stock -> alkane, then restore alkane -> stock
from the genuine Bitmain SD recovery image; the board booted genuine stock
(stock kernel, stock device tree 5-partition NAND layout, Angstrom userspace),
confirmed on the serial console.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 18:08:09 -06:00
noahandClaude Opus 4.8 82492231bc gui: right-click install/uninstall of alkane-os via the self-contained engine
Wire the GUI to the toolkit's own compiled-in, network-only stock<->alkane engine
(alkane-flash::stock) and the .afw fetch/verify (alkane-artifacts), so a scanned
control board can be right-clicked to:

  - Install alkane OS (from stock): scans alkane-os releases on Gitea, picks one
    (newest first; pre-releases marked), downloads+verifies the .afw, and installs
    it onto each selected board over the network. Optional board password and an
    allow-unsigned (bench) toggle; typed FLASH confirmation.
  - Uninstall alkane OS (restore to stock): restores each selected board to
    genuine stock over the network, with the board's alkane root credential and a
    typed FLASH confirmation.

Both run on a background thread (stock_ops.rs), streaming progress/results to the
status bar, and share the exclusivity guards so they never race a scan/flash/
restore. These use the same engine the CLI drives; the GUI's older asic-rs
firmware-upload path stays disabled.

alkane-artifacts: add list_releases + fetch_afw_url for the release picker, and an
optional build-time embedded read-only token (option_env!("ALKANE_EMBEDDED_TOKEN"))
so a distributed GUI can scan the private alkane-os releases with no setup; the
env token still wins, and no secret is in the source tree.

wx-rs (vendored, patched): build on system wxWidgets 3.2 - guard the 3.3-only
wxApp::SetAppearance/Appearance behind wxCHECK_VERSION(3,3,0), and emit GTK's own
shared libs (pkg-config --libs gtk+-3.0) at link time since the widget bridge
calls GTK directly. Enables the Linux GUI release build.

docs/install.md: document the GUI actions and that the stock-assets repo is now
public (no token for install/restore; only release scanning needs one).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 14:18:24 -06:00
noahandClaude Opus 4.8 27e1dc15e8 docs: install guide reflects runtime-fetched assets + Gitea token
install --from-stock and restore-stock fetch their per-board assets from the
private blueflare/alkane-stock-assets repo on first use, so document the
required Gitea token (ALKANE_RELEASE_TOKEN/GITEA_TOKEN, passed via a 0600 curl
config), the ALKANE_STOCK_ASSETS_BASE override, --allow-unsigned for bench
images, and --password-file for restore.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-11 11:21:33 -06:00
noah 086c883c4a Merge pull request 'Media icons: 3:1 against the button colour macOS actually paints' (#28) from media-icon-contrast into main
build-test-release / windows (push) Successful in 5m32s
build-test-release / release (push) Successful in 13m30s
2026-11-04 13:31:17 -07:00
noahandClaude Opus 5.5 4324d3046e Media icons: 3:1 against the button colour macOS actually paints
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 7m29s
verify / verify-windows (pull_request) Successful in 5m16s
The play/pause icons on macOS light buttons were about 2.6:1, because
native macOS buttons paint #ebebeb on a white window, not the system
button-face colour the check used. Check the icons against the button
face, the window colour and a shade 20 steps toward the opposite end.
They now measure 3.1:1 on the Mac (light and dark checked in real
system appearance), and stay above 3:1 on Linux and Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
2026-11-04 14:17:52 -06:00
noah de5c1a5a15 Merge pull request 'Keep every coloured text readable in light and dark themes' (#27) from dark-mode-contrast into main
build-test-release / windows (push) Successful in 5m13s
build-test-release / release (push) Successful in 13m38s
2026-11-04 12:52:46 -07:00
noahandClaude Opus 5.5 d22ee79159 Keep every coloured text readable in light and dark themes
verify / verify (pull_request) Successful in 7m18s
verify / verify-windows (pull_request) Successful in 4m48s
source / check (pull_request) Skipped
Checked in real system dark and light mode on macOS (SkyLight theme
switch on the M1, restored afterwards), Windows 11 (the app-mode
setting, run on the VM's desktop) and Linux (Adwaita and Adwaita:dark),
measuring each screenshot's text against its background with the WCAG
contrast formula.

The app's own colours fell short on every platform. The fixed firmware
hues were 2.6 to 3.9:1 (LuxOS gold and ePIC blue on light, Alkane navy,
Braiins purple and Bixbit red on dark). The hashrate greens and
temperature purples were about 4:1, and the play/pause icons about 2:1
on light buttons.

- readable()/readable_at(): nudge a colour toward black (light theme)
  or white (dark theme), keeping its hue, until it reaches 4.5:1 for
  text (3:1 for icons) against every given background.
- palette(): green/amber/red/accent/label are made readable against the
  window, the zebra row and the KPI card; Palette::text() guards every
  computed cell colour (ratio and temperature blends, firmware hues).
- Media button icons: at least 3:1 against the theme's button face.
- macOS snapshot (wx-rs patch 0011): capture the window's frame view.
  The content view alone left unpainted areas transparent, which read
  as a white toolbar strip in dark mode. On screen the area was always
  the dark window colour.

After the change, no app-coloured text is below 4.5:1 in any of the
six theme/platform combinations. What the checker still flags is theme
chrome (grid lines, GTK header labels, button outlines, the zoom
slider) and anti-aliasing on thin fonts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
2026-11-04 13:40:10 -06:00
noah 75b7424a0d Merge pull request 'Avoid duplicate Toolkit feature branch CI' (#14) from ci/drop-duplicate-toolkit-feature-verify into next
next-build / candidate (push) Successful in 11m8s
2026-10-21 06:58:54 -06:00
noah 8d4fe502be Avoid duplicate Toolkit feature branch CI 2026-10-21 06:57:38 -06:00
noah 038c1b1c2b Merge pull request 'Add fast next pull request source gate' (#13) from ci/next-pr-source-check into next 2026-10-21 06:55:56 -06:00
noah 20d7f49c9d Scope Toolkit source checks to changed Rust 2026-10-21 06:54:48 -06:00
noah 74cee50d35 Add fast next pull request source gate 2026-10-21 06:51:32 -06:00
noah 32a75c92ef Merge pull request 'Route toolkit benchmark publication to verifier' (#9) from ci/isolate-fast-runner-next into next 2026-10-21 06:49:08 -06:00
noah f4d9c12bb6 Route toolkit benchmark publication to verifier 2026-10-20 18:45:04 -06:00
noah b610ce3d7f Validate SDK archive contents in Rust before install 2026-10-17 11:13:17 -06:00
noah 1a5dcd17a9 Verify SDK release archives from checksum sidecar 2026-10-17 10:11:15 -06:00
noah 3b1b1fa63e Document running build verification and lock CLI dependency 2026-10-17 10:08:34 -06:00
noah 7880b14e47 Expose running build verification in toolkit CLI 2026-10-17 10:03:34 -06:00
noah 5bbf5b71b7 Verify running board build marker against CI artifact 2026-10-17 10:01:04 -06:00
noah cfec9606a4 Require observed MTD geometry before resolving flash target 2026-10-17 09:02:13 -06:00
noah e8d7cdc77a Parse MTD layouts before board flash planning 2026-10-17 08:02:02 -06:00
noah 8ba585679a Add bounded read-only SSH board probes 2026-10-17 07:02:01 -06:00
noah ea102130ac docs: shorten Toolkit entry guide 2026-10-17 01:42:10 -06:00
noah e656402ec8 Publish Toolkit benchmarks on the standing Alkane runner 2026-10-17 01:21:27 -06:00
noah 80f3c22582 Validate public benchmark page before upload 2026-10-16 08:47:42 -06:00
noah a79ac3e09e Publish Toolkit benchmarks to public Pages site 2026-10-16 07:20:03 -06:00
noah 6580005e77 Bound queued Toolkit CI attempts per branch 2026-10-16 07:08:58 -06:00
noah 2734c8e356 Average benchmark improvements equally in Toolkit badge 2026-10-16 06:02:55 -06:00
noah 0c2897ce37 Require complete Toolkit benchmarks before release 2026-10-16 05:12:21 -06:00
noah fbc903fa6a Benchmark health diagnostics on representative miners 2026-10-15 20:19:36 -06:00
noah fe9617ab56 Guard UTF-8 naming and repair headless screenshots 2026-10-15 20:10:42 -06:00
noah 1e9e4f16b5 Stage verified flash images before device writes 2026-10-15 19:10:45 -06:00
noah 6a6a5e7ded Grade Toolkit code quality from static checks 2026-10-15 19:04:10 -06:00
noah e20b6890d3 Simplify Toolkit docs and update installer status 2026-10-15 14:37:27 -06:00
noah 17bee91248 Clean candidate build after prerelease decision 2026-10-15 12:43:24 -06:00
noah 63d0de8ae3 Clean generated Toolkit builds after CI and local GUI builds 2026-10-15 11:52:21 -06:00
noah 9a8efc807a Parse Rust test harness benchmark output 2026-10-15 04:06:52 -06:00
noah 9879a0eb25 Compare toolkit benchmarks on matching CPU classes 2026-10-15 03:37:30 -06:00
noah 03c19ef7c6 Derive toolkit quality grade from measured coverage 2026-10-15 03:34:41 -06:00
noah 2540801140 Revalidate artifacts and guard complete flash streams 2026-10-14 20:54:42 -06:00
noah dd28fa233c Use Gitea-compatible pinned artifact upload 2026-10-14 20:51:35 -06:00
noah e5ca519df0 Publish measured toolkit badges from main CI 2026-10-14 20:45:03 -06:00
noah 06c8e01eb5 Guard verified artifact writes with recovery checks 2026-10-14 20:40:35 -06:00
noah 990439985d Verify toolkit firmware artifacts before install 2026-10-14 20:31:26 -06:00
noah 54136b71ef Record private toolkit benchmark history 2026-10-14 20:21:38 -06:00
noah 5d18304f0f Standardize toolkit CI badges and scoped release auth 2026-10-14 20:06:48 -06:00
noah 8bbf844bb6 Merge branch 'tooling-standard' into next 2026-10-13 12:10:34 -06:00
noah 97607a0a91 Point next CI badge at next attempts 2026-10-13 11:54:38 -06:00
44 changed files with 9168 additions and 861 deletions
+36
View File
@@ -0,0 +1,36 @@
name: public-benchmark-pages
on:
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:
concurrency:
group: alkane-toolkit-public-benchmark-pages
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
- name: Render measured benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py render
- name: Publish public benchmark page
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
run: python3 ci/publish-bench-pages.py toolkit
- name: Clean generated page
if: always()
run: python3 ci/cleanup-generated.py
+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:
+2
View File
@@ -22,6 +22,7 @@ jobs:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
steps:
- uses: actions/checkout@v4
with:
@@ -94,6 +95,7 @@ jobs:
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
steps:
- uses: actions/checkout@v4
with:
+6
View File
@@ -28,6 +28,9 @@ jobs:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
# Read-only token baked into the GUI so the release picker can list the
# private alkane-os releases with no user setup (option_env!).
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
steps:
- name: Checkout (full history for tags)
uses: actions/checkout@v4
@@ -136,6 +139,9 @@ jobs:
# Set once for the whole job so build/clippy/test/bench steps don't each
# re-export it (round 18 #12).
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
# Read-only token baked into the GUI so the release picker can list the
# private alkane-os releases with no user setup (option_env!).
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
steps:
- name: Checkout (full history for tags)
uses: actions/checkout@v4
+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:
+2 -2
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:
@@ -202,7 +202,7 @@ jobs:
verify-windows:
needs: verify
if: needs.verify.outputs.surface == 'full'
runs-on: alkane-verify
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
Generated
+2
View File
@@ -89,8 +89,10 @@ name = "alkane-gui"
version = "0.1.0"
dependencies = [
"aes",
"alkane-artifacts",
"alkane-core",
"alkane-discovery",
"alkane-flash",
"asic-rs",
"base64 0.21.7",
"ecb",
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish a measured benchmark page to the public, data-only Pages repo."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
import tempfile
from urllib.request import Request, urlopen
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
PAGES_HOST = "gitea.bluefla.re"
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
def run(*args: str, env: dict[str, str] | None = None,
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, env=env, cwd=cwd, text=True,
capture_output=True, check=True)
def current_main_sha() -> str:
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
request = Request(f"{api}/repos/{repo}/branches/main",
headers={"Authorization": f"token {token}"})
with urlopen(request, timeout=20) as response:
branch = json.load(response)
return branch["commit"]["id"]
def publish(site: str) -> None:
if os.environ.get("GITHUB_REF") != "refs/heads/main":
raise ValueError("benchmark Pages publication requires main")
sha = os.environ["GITHUB_SHA"]
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
page = Path("bench-site/index.html").read_bytes()
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
raise ValueError("invalid benchmark page")
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
temporary = Path(directory)
guard_checkout = temporary / "guard"
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
GUARD_REPO, str(guard_checkout))
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
cwd=guard_checkout).stdout
guard_script = temporary / "validate_site.py"
guard_script.write_text(guard_source)
run("python3", str(guard_script), "--page", site,
str(Path("bench-site/index.html").resolve()))
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
raise ValueError("missing benchmark Pages deploy key")
key_path = temporary / "deploy_key"
key_path.write_text(key.rstrip("\n") + "\n")
key_path.chmod(0o600)
known_hosts = temporary / "known_hosts"
known_hosts.write_text(PAGES_HOST_KEY + "\n")
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
if fingerprint != PAGES_HOST_FINGERPRINT:
raise ValueError("benchmark Pages SSH host key changed")
git_env = os.environ.copy()
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
git_env["GIT_SSH_COMMAND"] = ssh_command
git_env["GIT_TERMINAL_PROMPT"] = "0"
checkout = temporary / "site"
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
PAGES_REPO, str(checkout), env=git_env)
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
for attempt in range(3):
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
cwd=checkout)
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
cwd=checkout)
destination = checkout / site / "index.html"
destination.parent.mkdir(exist_ok=True)
destination.write_bytes(page)
run("git", "add", f"{site}/index.html", cwd=checkout)
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
cwd=checkout, check=False)
if changed.returncode == 0:
print(f"{site} benchmark page is already current")
return
if changed.returncode != 1:
raise RuntimeError("cannot compare benchmark page")
run("git", "commit", "-q", "-m",
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
pushed = subprocess.run(("git", "push", "--quiet", "origin",
"HEAD:gh-pages"), env=git_env, cwd=checkout,
text=True, capture_output=True, check=False)
if pushed.returncode == 0:
print(f"Published {site} benchmark page for {sha[:10]}")
return
if attempt == 2:
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
raise RuntimeError("benchmark Pages publication did not complete")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
publish(parser.parse_args().site)
if __name__ == "__main__":
main()
+9 -4
View File
@@ -136,12 +136,17 @@ def main() -> None:
["README.md", "ci/pr-surface.py"]):
assert not pr_surface.documentation_only(paths), paths
assert pr_surface.headless_packages(["crates/alkane-cli/src/main.rs"]) == ["alkane-cli"]
assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == [
"alkane-artifacts", "alkane-cli", "alkane-flash",
]
# alkane-gui depends on alkane-flash and alkane-artifacts (right-click
# install/uninstall and the release picker), so a change in either reaches
# the GUI graph and needs the full build: not a headless-only change.
assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == []
assert pr_surface.headless_packages(["crates/alkane-flash/src/lib.rs"]) == []
assert pr_surface.headless_packages([
"crates/alkane-access/src/lib.rs", "crates/alkane-flash/tests/update.rs",
]) == ["alkane-access", "alkane-flash"]
]) == []
assert pr_surface.headless_packages([
"crates/alkane-access/src/lib.rs", "crates/alkane-cli/src/main.rs",
]) == ["alkane-access", "alkane-cli"]
for paths in ([], ["crates/alkane-core/src/lib.rs"],
["crates/alkane-discovery/src/lib.rs"],
["crates/alkane-gui/src/main.rs"],
+163 -2
View File
@@ -21,6 +21,7 @@ pub const CV1835_P1_SIZE: u64 = 16 * 1024 * 1024;
pub const AM335X_HOLE_OFFSET: u64 = 0x780000;
pub const AM335X_HOLE_SIZE: u64 = 0x80000;
pub const AM335X_CHIP_SIZE: u64 = 0x8000000;
#[allow(clippy::type_complexity)]
const AM335X_MAP: &[(&str, u64, u64, bool, bool, i64, Option<&str>)] = &[
("mtd0", 0x0000000, 0x20000, true, true, 0, None),
("mtd1", 0x0020000, 0x20000, true, true, 0, None),
@@ -42,7 +43,15 @@ const AM335X_CEILINGS: &[(&str, u64, &str)] = &[
];
const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"];
const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "zimage", "fdt", "cpio-gzip", "uimage", "raw"];
const IMAGE_FORMATS: &[&str] = &[
"fit",
"arm64-image",
"zimage",
"fdt",
"cpio-gzip",
"uimage",
"raw",
];
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
@@ -146,6 +155,54 @@ pub struct AfwManifest {
pub notes: Option<String>,
}
/// What an `.afw` bundle overwrites on the target, derived from its manifest.
///
/// Tiers mirror the flash tiers: 1 = update (userspace / HAL only, no kernel or
/// bootloader write), 2 = kernel (kernel, dtb and boot images; bootloader
/// preserved), 3 = bootloader (U-Boot/SPL is rewritten as well).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FlashPlan {
pub tier: u8,
pub writes_uboot: bool,
pub writes_kernel: bool,
pub writes_userspace: bool,
}
impl AfwManifest {
/// Compute the flash tier and the regions this bundle overwrites. Pure
/// computation over the parsed manifest; no device or file access.
///
/// - `writes_uboot`: `bootloader_policy` is [`BootloaderPolicy::Include`]
/// (anything but `Preserve`), or an image with role `bootloader` exists.
/// - `writes_kernel`: an image with role `kernel`, `dtb` or `boot` exists.
/// - `writes_userspace`: an image with role `rootfs` exists.
/// - `tier`: 3 if `writes_uboot`, else 2 if `writes_kernel`, else 1.
pub fn flash_plan(&self) -> FlashPlan {
let has_role = |roles: &[&str]| {
self.images
.iter()
.any(|image| roles.contains(&image.role.as_str()))
};
let writes_uboot =
self.bootloader_policy != BootloaderPolicy::Preserve || has_role(&["bootloader"]);
let writes_kernel = has_role(&["kernel", "dtb", "boot"]);
let writes_userspace = has_role(&["rootfs"]);
let tier = if writes_uboot {
3
} else if writes_kernel {
2
} else {
1
};
FlashPlan {
tier,
writes_uboot,
writes_kernel,
writes_userspace,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AfwMember {
pub name: String,
@@ -606,7 +663,11 @@ fn validate_am335x(manifest: &AfwManifest) -> Result<(), AfwError> {
)));
}
}
let install: Vec<&AfwImage> = manifest.images.iter().filter(|image| image.install).collect();
let install: Vec<&AfwImage> = manifest
.images
.iter()
.filter(|image| image.install)
.collect();
if install.len() != 3 {
return Err(AfwError::Manifest(
"am335x must install exactly kernel, dtb and rootfs".to_owned(),
@@ -1067,6 +1128,106 @@ mod tests {
));
}
/// Build a parsed manifest with the given bootloader policy and one image
/// per listed role (payload bytes are irrelevant to `flash_plan`).
fn plan_manifest(policy: &str, roles: &[&str]) -> AfwManifest {
let mut value = manifest(&[0_u8; 4]);
value["bootloader_policy"] = json!(policy);
value["images"] = json!(roles
.iter()
.enumerate()
.map(|(i, role)| json!({
"name": format!("img{i}"), "file": format!("payload/img{i}"),
"role": role, "format": "raw", "size": 4, "sha256": "0".repeat(64),
"partition": null, "install": false
}))
.collect::<Vec<_>>());
serde_json::from_value(value).unwrap()
}
#[test]
fn flash_plan_tier2_preserve_kernel_and_rootfs() {
let plan = plan_manifest("preserve", &["kernel", "dtb", "rootfs"]).flash_plan();
assert_eq!(plan.tier, 2);
assert!(plan.writes_kernel);
assert!(plan.writes_userspace);
assert!(!plan.writes_uboot);
}
#[test]
fn flash_plan_tier3_include_with_bootloader_image() {
let plan =
plan_manifest("include", &["bootloader", "kernel", "dtb", "rootfs"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot);
assert!(plan.writes_kernel);
assert!(plan.writes_userspace);
}
#[test]
fn flash_plan_tier3_from_bootloader_image_alone() {
// A bootloader image forces tier 3 even if the policy says preserve
// (verification rejects that combination, but the plan stays safe).
let plan = plan_manifest("preserve", &["bootloader"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot);
assert!(!plan.writes_kernel);
assert!(!plan.writes_userspace);
}
#[test]
fn flash_plan_tier3_from_include_policy_alone() {
let plan = plan_manifest("include", &["rootfs"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot);
assert!(!plan.writes_kernel);
assert!(plan.writes_userspace);
}
#[test]
fn flash_plan_tier1_rootfs_only() {
let plan = plan_manifest("preserve", &["rootfs"]).flash_plan();
assert_eq!(plan.tier, 1);
assert!(plan.writes_userspace);
assert!(!plan.writes_kernel);
assert!(!plan.writes_uboot);
}
#[test]
fn flash_plan_boot_role_counts_as_kernel() {
let plan = plan_manifest("preserve", &["boot"]).flash_plan();
assert_eq!(plan.tier, 2);
assert!(plan.writes_kernel);
assert!(!plan.writes_userspace);
assert!(!plan.writes_uboot);
// The shared cv1835 fixture is a single "boot" FIT under preserve.
let fixture: AfwManifest = serde_json::from_value(manifest(&[0_u8; 4])).unwrap();
assert_eq!(fixture.flash_plan().tier, 2);
}
#[test]
fn flash_plan_component_only_is_tier1_with_no_regions() {
let plan = plan_manifest("preserve", &["component"]).flash_plan();
assert_eq!(plan.tier, 1);
assert!(!plan.writes_uboot);
assert!(!plan.writes_kernel);
assert!(!plan.writes_userspace);
}
#[test]
fn flash_plan_empty_images_preserve_is_tier1() {
let plan = plan_manifest("preserve", &[]).flash_plan();
assert_eq!(plan.tier, 1);
assert!(!plan.writes_uboot && !plan.writes_kernel && !plan.writes_userspace);
}
#[test]
fn flash_plan_tier3_dominates_kernel() {
let plan = plan_manifest("include", &["bootloader", "kernel"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot && plan.writes_kernel);
}
#[test]
fn refuses_a_hash_mismatch() {
let p1 = p1_image(P1);
+313 -11
View File
@@ -10,7 +10,15 @@
//!
//! A private repo needs a token; it is read from the environment at run time
//! (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`) and passed to curl through a
//! 0600 config file, never on the command line. No token is embedded or stored.
//! 0600 config file, never on the command line.
//!
//! As a convenience for the GUI, a read-only token can be baked into the binary
//! at build time by compiling with `ALKANE_EMBEDDED_TOKEN=<token>` set (see
//! `EMBEDDED_TOKEN`). The source tree carries no secret - the value lives only in
//! a binary built with that variable set - and the environment variables above
//! always take precedence, so a user can override it. When no such token is baked
//! in and none is in the environment, the token is simply absent (fine for public
//! repos; a private repo then returns 401/404).
use std::fs;
use std::path::{Path, PathBuf};
@@ -19,6 +27,14 @@ use std::process::Command;
use serde_json::Value;
use thiserror::Error;
/// A read-only Gitea token baked in at build time when the crate is compiled
/// with `ALKANE_EMBEDDED_TOKEN` set. `None` in an ordinary build (no secret in
/// the source tree). The environment variables win over this, so it is only a
/// fallback for a distributed binary (the GUI) that ships without asking the user
/// to configure a token. Scope it read-only on the server side; anyone with the
/// binary can extract it.
const EMBEDDED_TOKEN: Option<&str> = option_env!("ALKANE_EMBEDDED_TOKEN");
#[derive(Debug, Error)]
pub enum FetchError {
#[error("curl failed: {0}")]
@@ -44,6 +60,14 @@ impl ReleaseSource {
/// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token
/// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`.
pub fn alkane_os() -> Self {
Self::for_repo("blueflare", "alkane-os")
}
/// A release source for an arbitrary Gitea `owner`/`repo`. The base URL
/// (`ALKANE_RELEASE_BASE`, else the self-hosted Gitea) and the token
/// (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`, else the build-time embedded
/// token) are resolved exactly as for `alkane_os`.
pub fn for_repo(owner: &str, repo: &str) -> Self {
let base_url = std::env::var("ALKANE_RELEASE_BASE")
.ok()
.filter(|s| !s.is_empty())
@@ -51,11 +75,12 @@ impl ReleaseSource {
let token = std::env::var("ALKANE_RELEASE_TOKEN")
.ok()
.or_else(|| std::env::var("GITEA_TOKEN").ok())
.filter(|t| !t.is_empty());
.filter(|t| !t.is_empty())
.or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty()));
Self {
base_url,
owner: "blueflare".to_string(),
repo: "alkane-os".to_string(),
owner: owner.to_string(),
repo: repo.to_string(),
token,
}
}
@@ -104,7 +129,10 @@ impl TokenConfig {
return Ok(Self { path: None });
};
let path = std::env::temp_dir().join(format!("alkane-fetch-{}.cfg", std::process::id()));
write_private(&path, &format!("header = \"Authorization: token {token}\"\n"))?;
write_private(
&path,
&format!("header = \"Authorization: token {token}\"\n"),
)?;
Ok(Self { path: Some(path) })
}
@@ -134,7 +162,8 @@ fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
.mode(0o600)
.open(path)
.map_err(|e| FetchError::Io(e.to_string()))?;
file.write_all(contents.as_bytes()).map_err(|e| FetchError::Io(e.to_string()))
file.write_all(contents.as_bytes())
.map_err(|e| FetchError::Io(e.to_string()))
}
#[cfg(not(unix))]
@@ -162,7 +191,11 @@ fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), FetchError> {
let config = TokenConfig::new(&src.token)?;
let mut cmd = Command::new("curl");
cmd.arg("-fsSL").arg("--max-time").arg("600").arg("-o").arg(dest);
cmd.arg("-fsSL")
.arg("--max-time")
.arg("600")
.arg("-o")
.arg(dest);
config.apply(&mut cmd);
cmd.arg(url);
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
@@ -180,12 +213,17 @@ fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), Fetc
/// Scans the newest-first releases list (so a pre-release counts as latest).
pub fn latest_afw_asset(src: &ReleaseSource, board: &str) -> Result<(String, String), FetchError> {
let body = curl_bytes(src, &src.api_list())?;
let releases: Value = serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
let releases: Value =
serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
pick_asset(&releases, board).ok_or_else(|| FetchError::NoAsset(board.to_string()))
}
/// Download the latest `.afw` for `board` into `dest_dir`; returns its path.
pub fn fetch_latest_afw(src: &ReleaseSource, board: &str, dest_dir: &Path) -> Result<PathBuf, FetchError> {
pub fn fetch_latest_afw(
src: &ReleaseSource,
board: &str,
dest_dir: &Path,
) -> Result<PathBuf, FetchError> {
let (name, url) = latest_afw_asset(src, board)?;
fs::create_dir_all(dest_dir).map_err(|e| FetchError::Io(e.to_string()))?;
let dest = dest_dir.join(&name);
@@ -193,6 +231,151 @@ pub fn fetch_latest_afw(src: &ReleaseSource, board: &str, dest_dir: &Path) -> Re
Ok(dest)
}
/// Board tokens recognised in `.afw` asset names (the `-<board>-` filename
/// segment). Used by `ReleaseInfo::compatible_boards`.
pub const KNOWN_BOARDS: &[&str] = &[
"zynq-7010",
"am335x",
"cv1835",
"a113d",
"allwinner-h3",
"allwinner-h6",
"allwinner-h616",
];
/// One `.afw` asset in a release.
#[derive(Debug, Clone)]
pub struct AfwAsset {
pub name: String,
pub url: String,
}
/// A release as listed for the GUI's release picker: its tag/name, whether it is
/// a pre-release or draft, when it was published, and the `.afw` assets it holds.
#[derive(Debug, Clone)]
pub struct ReleaseInfo {
pub tag: String,
pub name: String,
pub prerelease: bool,
pub draft: bool,
pub published_at: String,
pub afw_assets: Vec<AfwAsset>,
}
impl ReleaseInfo {
/// The `.afw` asset for `board` in this release, if any (matched by the
/// `-<board>-` segment of the filename, as `pick_asset` does).
pub fn asset_for_board(&self, board: &str) -> Option<&AfwAsset> {
let needle = format!("-{board}-");
self.afw_assets.iter().find(|a| a.name.contains(&needle))
}
/// The distinct board tokens (from `KNOWN_BOARDS`) this release carries an
/// `.afw` for, detected from the asset filenames (`-<board>-` segment, e.g.
/// `alkane-os-0.1.2-zynq-7010-armv7.afw` -> `zynq-7010`). Ordered by first
/// appearance across the assets; a release with no recognised board yields an
/// empty list.
pub fn compatible_boards(&self) -> Vec<String> {
let mut boards: Vec<String> = Vec::new();
for asset in &self.afw_assets {
for board in KNOWN_BOARDS {
let needle = format!("-{board}-");
if asset.name.contains(&needle) && !boards.iter().any(|b| b == board) {
boards.push((*board).to_string());
}
}
}
boards
}
/// Whether this release has an `.afw` for `board` (same match as
/// `asset_for_board`).
pub fn is_compatible_with(&self, board: &str) -> bool {
self.asset_for_board(board).is_some()
}
}
/// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only
/// the `.afw` assets of each. Drafts are included so the caller can decide.
fn parse_releases(releases: &Value) -> Vec<ReleaseInfo> {
let mut out = Vec::new();
let Some(arr) = releases.as_array() else {
return out;
};
for release in arr {
let tag = release
.get("tag_name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let name = release
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let prerelease = release
.get("prerelease")
.and_then(Value::as_bool)
.unwrap_or(false);
let draft = release
.get("draft")
.and_then(Value::as_bool)
.unwrap_or(false);
let published_at = release
.get("published_at")
.or_else(|| release.get("created_at"))
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let mut afw_assets = Vec::new();
if let Some(assets) = release.get("assets").and_then(Value::as_array) {
for asset in assets {
let aname = asset.get("name").and_then(Value::as_str).unwrap_or("");
if aname.ends_with(".afw") {
if let Some(url) = asset.get("browser_download_url").and_then(Value::as_str) {
afw_assets.push(AfwAsset {
name: aname.to_string(),
url: url.to_string(),
});
}
}
}
}
out.push(ReleaseInfo {
tag,
name,
prerelease,
draft,
published_at,
afw_assets,
});
}
out
}
/// List the releases (newest first) of the source repo, each with its `.afw`
/// assets. Used by the GUI to scan alkane-os releases and pick one to install.
pub fn list_releases(src: &ReleaseSource) -> Result<Vec<ReleaseInfo>, FetchError> {
let body = curl_bytes(src, &src.api_list())?;
let releases: Value =
serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
Ok(parse_releases(&releases))
}
/// Download a specific release asset (by its `browser_download_url`) into
/// `dest_dir`, saving it under `name`; returns the written path.
pub fn fetch_afw_url(
src: &ReleaseSource,
name: &str,
url: &str,
dest_dir: &Path,
) -> Result<PathBuf, FetchError> {
fs::create_dir_all(dest_dir).map_err(|e| FetchError::Io(e.to_string()))?;
let dest = dest_dir.join(name);
curl_download(src, url, &dest)?;
Ok(dest)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -203,7 +386,9 @@ mod tests {
let src = ReleaseSource::alkane_os();
assert_eq!(src.owner, "blueflare");
assert_eq!(src.repo, "alkane-os");
assert!(src.api_list().contains("/api/v1/repos/blueflare/alkane-os/releases"));
assert!(src
.api_list()
.contains("/api/v1/repos/blueflare/alkane-os/releases"));
assert!(src.api_list().starts_with("https://gitea.bluefla.re"));
}
@@ -220,7 +405,124 @@ mod tests {
{"name": "alkane-os-0.0.9-zynq-7010-armv7.afw", "browser_download_url": "old"},
]},
]);
assert_eq!(pick_asset(&releases, "zynq-7010"), Some(("alkane-os-0.1.0-zynq-7010-armv7.afw".into(), "u2".into())));
assert_eq!(
pick_asset(&releases, "zynq-7010"),
Some(("alkane-os-0.1.0-zynq-7010-armv7.afw".into(), "u2".into()))
);
assert_eq!(pick_asset(&releases, "cv1835"), None);
}
#[test]
fn list_parses_releases_and_filters_afw_assets() {
let releases = serde_json::json!([
{"tag_name": "v0.2.0-bench1", "name": "bench", "prerelease": true, "draft": false,
"published_at": "2026-11-11T10:00:00Z", "assets": [
{"name": "SHA256SUMS", "browser_download_url": "s"},
{"name": "alkane-os-0.2.0-zynq-7010-armv7.afw", "browser_download_url": "z"},
]},
{"tag_name": "v0.1.0", "name": "", "prerelease": false, "draft": false,
"published_at": "2026-10-01T00:00:00Z", "assets": [
{"name": "alkane-os-0.1.0-am335x-arm.afw", "browser_download_url": "a"},
]},
]);
let parsed = parse_releases(&releases);
assert_eq!(parsed.len(), 2);
// Newest first; only .afw assets kept; SHA256SUMS dropped.
assert_eq!(parsed[0].tag, "v0.2.0-bench1");
assert!(parsed[0].prerelease);
assert_eq!(parsed[0].afw_assets.len(), 1);
// The board filter matches the -<board>- segment.
assert_eq!(
parsed[0]
.asset_for_board("zynq-7010")
.map(|a| a.url.as_str()),
Some("z")
);
assert!(parsed[0].asset_for_board("am335x").is_none());
assert_eq!(
parsed[1].asset_for_board("am335x").map(|a| a.name.as_str()),
Some("alkane-os-0.1.0-am335x-arm.afw")
);
assert!(parsed[1].asset_for_board("zynq-7010").is_none());
}
#[test]
fn for_repo_builds_the_api_url_for_a_custom_repo() {
std::env::remove_var("ALKANE_RELEASE_BASE");
let src = ReleaseSource::for_repo("someorg", "some-firmware");
assert_eq!(src.owner, "someorg");
assert_eq!(src.repo, "some-firmware");
assert_eq!(
src.api_list(),
"https://gitea.bluefla.re/api/v1/repos/someorg/some-firmware/releases?limit=50"
);
// alkane_os() is for_repo("blueflare", "alkane-os").
let os = ReleaseSource::alkane_os();
assert_eq!(
(os.owner.as_str(), os.repo.as_str()),
("blueflare", "alkane-os")
);
}
fn release_with(names: &[&str]) -> ReleaseInfo {
ReleaseInfo {
tag: "v0.1.2".into(),
name: String::new(),
prerelease: false,
draft: false,
published_at: String::new(),
afw_assets: names
.iter()
.map(|n| AfwAsset {
name: (*n).to_string(),
url: format!("https://example.invalid/{n}"),
})
.collect(),
}
}
#[test]
fn compatible_boards_extracts_board_tokens_from_asset_names() {
let single = release_with(&["alkane-os-0.1.2-zynq-7010-armv7.afw"]);
assert_eq!(single.compatible_boards(), vec!["zynq-7010"]);
// Multi-board release: distinct boards in first-appearance order,
// duplicates (a second arch build of one board) collapse.
let multi = release_with(&[
"alkane-os-0.1.2-am335x-armv7.afw",
"alkane-os-0.1.2-zynq-7010-armv7.afw",
"alkane-os-0.1.2-allwinner-h616-aarch64.afw",
"alkane-os-0.1.2-am335x-arm.afw",
"alkane-os-0.1.2-cv1835-riscv64.afw",
]);
assert_eq!(
multi.compatible_boards(),
vec!["am335x", "zynq-7010", "allwinner-h616", "cv1835"]
);
// allwinner-h6 must not match an allwinner-h616 asset (and vice versa).
let h616 = release_with(&["alkane-os-0.1.2-allwinner-h616-aarch64.afw"]);
assert_eq!(h616.compatible_boards(), vec!["allwinner-h616"]);
let h6 = release_with(&["alkane-os-0.1.2-allwinner-h6-aarch64.afw"]);
assert_eq!(h6.compatible_boards(), vec!["allwinner-h6"]);
// No .afw assets, or an unrecognised board, yields nothing.
assert!(release_with(&[]).compatible_boards().is_empty());
assert!(release_with(&["alkane-os-0.1.2-mystery-board-arm.afw"])
.compatible_boards()
.is_empty());
}
#[test]
fn is_compatible_with_matches_asset_for_board() {
let rel = release_with(&[
"alkane-os-0.1.2-zynq-7010-armv7.afw",
"alkane-os-0.1.2-a113d-aarch64.afw",
]);
assert!(rel.is_compatible_with("zynq-7010"));
assert!(rel.is_compatible_with("a113d"));
assert!(!rel.is_compatible_with("am335x"));
assert!(!rel.is_compatible_with("allwinner-h6"));
assert!(!release_with(&[]).is_compatible_with("zynq-7010"));
}
}
+491 -93
View File
@@ -7,20 +7,23 @@
use alkane_artifacts::afw::{verify_afw, VerifiedAfw, VerifyOptions};
use alkane_artifacts::fetch::{self, ReleaseSource};
use alkane_flash::stock;
use alkane_artifacts::{seed_manifest, verify_file};
use alkane_core::platform;
use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan};
use alkane_flash::boards::am335x::{
self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions,
};
use alkane_flash::boards::cv1835::Cv1835Plan;
use alkane_flash::boards::zynq::{self, ZynqInstallOptions, ZynqOutcome, ZynqPlan};
use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan};
use alkane_flash::boards::zynq::{self, ZynqPlan};
use alkane_flash::install::{
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
};
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::transport::{Remote, RootMethod, SshOptions, SshTransport};
use alkane_flash::zynq_nand;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -146,8 +149,8 @@ fn read_board_password(opts: &Opts) -> Result<Option<String>, Box<dyn std::error
let secret = resolve_password(opts)?;
match &secret.path {
Some(path) => {
let raw = fs::read_to_string(path)
.map_err(|e| format!("reading board password: {e}"))?;
let raw =
fs::read_to_string(path).map_err(|e| format!("reading board password: {e}"))?;
Ok(Some(raw.trim_end_matches(['\n', '\r']).to_string()))
}
None => Ok(None),
@@ -348,10 +351,9 @@ fn run_plan(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
String::from_utf8_lossy(&transport.root_command("id -u", Duration::from_secs(15))?)
.trim()
.to_owned();
let mtd = String::from_utf8_lossy(&transport.user_command(
"cat /proc/mtd 2>/dev/null",
Duration::from_secs(15),
)?)
let mtd = String::from_utf8_lossy(
&transport.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(15))?,
)
.into_owned();
println!("{}", plan.render());
println!("current kernel {kernel} uid {uid}");
@@ -420,6 +422,28 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.first()
.ok_or("usage: alkane-cli afw preflight <file> --host <ip>")?;
let verified = load_afw(path, &opts)?;
// Zynq is reached through the compiled-in method (root SSH, boot regions
// re-registered), not the generic user transport below.
if zynq::owns_board(&verified.manifest.board) {
let host = opts.value("host").ok_or("--host is required")?;
let plan = ZynqPlan::from_afw(&verified)?;
println!("{}", plan.render());
let password = read_board_password(&opts)?;
let options = InPlaceOptions {
dry_run: true,
reboot: false,
backup_dir: None,
};
match stock::update_in_place(host, &verified, password.as_deref(), &options) {
Ok(InPlaceOutcome::DryRun(report)) => print!("{report}"),
Ok(InPlaceOutcome::Updated(_)) => {
return Err("internal error: preflight reported a write".into())
}
Err(e) => return Err(format!("preflight failed; do not write: {e}").into()),
}
println!("preflight is read-only; no write performed");
return Ok(());
}
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
if am335x::owns_board(&verified.manifest.board) {
@@ -431,15 +455,6 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
let report = zynq::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
print!("{}", report.render());
if !report.ok() {
return Err("preflight failed; do not write".into());
}
return Ok(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
let report = a113d::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
@@ -468,7 +483,64 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
/// Install onto a board currently on stock via the sealed from-stock method.
/// Update a Zynq board that already runs alkane, in place, through the
/// compiled-in method: it re-registers the boot regions (not exposed to Linux on
/// alkane), keeps a copy of every slot before any erase, writes the kernel and
/// rootfs as the uImages the stock U-Boot boots, reads each back, and never
/// writes BOOT.bin. A board on stock is refused (use --from-stock).
fn install_zynq_in_place(
verified: &VerifiedAfw,
opts: &Opts,
) -> Result<(), Box<dyn std::error::Error>> {
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let plan = ZynqPlan::from_afw(verified)?;
println!("{}", plan.render());
let dry_run = opts.flag("dry-run");
if !dry_run && opts.value("confirm") != Some("FLASH") {
return Err("refusing to write without --confirm FLASH (use --dry-run to inspect)".into());
}
let backup_dir = opts
.value("backup-dir")
.map(PathBuf::from)
.unwrap_or_else(|| platform::config_path("backups"));
let password = read_board_password(opts)?;
let options = InPlaceOptions {
dry_run,
reboot: !opts.flag("no-reboot"),
backup_dir: Some(backup_dir),
};
match stock::update_in_place(&host, verified, password.as_deref(), &options)? {
InPlaceOutcome::DryRun(report) => {
print!("{report}");
println!("DRY RUN: no board erase or write was performed.");
println!(
"Re-run with --confirm FLASH to write rootfs, dtb and kernel (BOOT.bin preserved)."
);
}
InPlaceOutcome::Updated(receipt) => {
for held in &receipt.backups {
println!(
"held {} abs 0x{:x} ({} B) {} md5 {}",
held.name,
held.absolute,
held.size,
held.path.display(),
held.md5
);
}
println!("all read-backs matched before reboot; BOOT.bin never touched");
if receipt.rebooted {
println!("board rebooted and answered as alkane again (SSH banner)");
print!("{}", zynq_verify_hint(&host));
} else {
println!("reboot skipped (--no-reboot); the new images run after the next reboot");
}
}
}
Ok(())
}
/// Install onto a board currently on stock via the from-stock install method.
fn install_from_stock_flow(
verified: &VerifiedAfw,
host: &str,
@@ -477,7 +549,7 @@ fn install_from_stock_flow(
) -> Result<(), Box<dyn std::error::Error>> {
if opts.flag("dry-run") {
println!(
"DRY RUN: would install {} onto stock board {host} via the sealed from-stock method ({})",
"DRY RUN: would install {} onto stock board {host} via the from-stock install method ({})",
verified.manifest.board,
afw.display()
);
@@ -496,17 +568,35 @@ fn install_from_stock_flow(
);
stock::install_from_stock(host, afw, verified, password.as_deref())?;
println!("from-stock install reported success.");
println!("verify the board is now reachable as alkane:");
println!(" alkane-cli afw verify-live --host {host} --timeout 300");
if zynq::owns_board(&verified.manifest.board) {
print!("{}", zynq_verify_hint(host));
} else {
println!("verify the board is now reachable as alkane:");
println!(" alkane-cli afw verify-live --host {host} --timeout 300");
}
Ok(())
}
/// How to confirm a Zynq board came up on alkane.
fn zynq_verify_hint(host: &str) -> String {
format!(
"verify independently:\n\
\x20 alkane-cli afw verify-live <the .afw> --host {host} --password-file <alkane root pw> --timeout 300\n"
)
}
fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[
ssh_values(),
&["held-backup", "backup-dir", "confirm", "expect-board", "board"],
&[
"held-backup",
"backup-dir",
"confirm",
"expect-board",
"board",
],
]
.concat(),
&[
@@ -528,13 +618,16 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
)
.into());
}
// A board on stock: the first install goes through the sealed from-stock
// A board on stock: the first install goes through the from-stock install
// method; the tier-2 partition-write path below is for a board already on
// alkane.
if opts.flag("from-stock") {
let host = opts.value("host").ok_or("--host is required")?.to_owned();
return install_from_stock_flow(&verified, &host, &path, &opts);
}
if zynq::owns_board(&verified.manifest.board) {
return install_zynq_in_place(&verified, &opts);
}
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let backup_dir = opts
@@ -591,39 +684,6 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
println!("{}", plan.render());
let install_options = ZynqInstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
match zynq::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
ZynqOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no board erase or write was performed.");
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
println!("Re-run with --confirm FLASH to write {targets} (BOOT.bin preserved).");
}
ZynqOutcome::Installed(receipt) => {
for backup in &receipt.backups {
println!(
"held {} {} offset 0x{:x} md5 {}",
backup.image_name, backup.path.display(), backup.offset, backup.md5
);
}
println!("all read-backs matched before reboot; BOOT.bin never touched");
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
} else {
println!("reboot skipped (--no-reboot)");
}
}
}
return Ok(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
println!("{}", plan.render());
@@ -633,25 +693,39 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
match a113d::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
match a113d::install(
&plan,
&mut transport,
&install_options,
opts.value("host").unwrap_or(""),
)? {
A113dOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no file was written into the nvdata UBI.");
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
let targets = plan
.targets
.iter()
.map(|t| t.image_name.as_str())
.collect::<Vec<_>>()
.join(", ");
println!("Re-run with --confirm FLASH to write {targets} into the alkane/ dir on nvdata (FIP + mtd0-5 are not MTD devices).");
}
A113dOutcome::Installed(receipt) => {
println!("wrote OS files into the alkane/ dir on nvdata volume {}", receipt.volume);
println!(
"wrote OS files into the alkane/ dir on nvdata volume {}",
receipt.volume
);
for backup in &receipt.backups {
match (&backup.path, &backup.md5) {
(Some(path), Some(md5)) => println!(
"held {} {} md5 {}",
backup.image_name, path.display(), md5
),
(Some(path), Some(md5)) => {
println!("held {} {} md5 {}", backup.image_name, path.display(), md5)
}
_ => println!("held {} (no prior file on board)", backup.image_name),
}
}
println!("all read-backs matched before reboot; no raw NAND write, FIP never touched");
println!(
"all read-backs matched before reboot; no raw NAND write, FIP never touched"
);
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
} else {
@@ -711,7 +785,13 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
args,
&[
ssh_values(),
&["marker", "kernel-version", "timeout", "expect-board", "board"],
&[
"marker",
"kernel-version",
"timeout",
"expect-board",
"board",
],
]
.concat(),
&["allow-unsigned"],
@@ -720,7 +800,16 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let (board, marker, kernel_version) = if let Some(path) = opts.positionals.first() {
let verified = load_afw(path, &opts)?;
let board = verified.manifest.board.clone();
if board == "am335x" {
if zynq::owns_board(&board) {
let plan = ZynqPlan::from_afw(&verified)?;
(
board,
opts.value("marker").unwrap_or(&plan.marker).to_owned(),
opts.value("kernel-version")
.unwrap_or(&plan.kernel_version)
.to_owned(),
)
} else if board == "am335x" {
let plan = Am335xPlan::from_afw(&verified)?;
(
board,
@@ -740,9 +829,13 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
)
}
} else {
let board = requested_board.clone().unwrap_or_else(|| "cv1835".to_owned());
let board = requested_board
.clone()
.unwrap_or_else(|| "cv1835".to_owned());
let (marker, kernel) = if board == "am335x" {
("Alkane".to_owned(), "6.18.48".to_owned())
} else if zynq::owns_board(&board) {
("Alkane".to_owned(), String::new())
} else {
("CVBOOT".to_owned(), String::new())
};
@@ -758,12 +851,31 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
}
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let timeout = opts
.value("timeout")
.map(str::parse::<u64>)
.transpose()?
.unwrap_or(DEFAULT_TIMEOUT);
if zynq::owns_board(&board) {
// Zynq is checked through the compiled-in method's root SSH (the host
// key changes on every reflash, so it is not pinned) plus the web page.
let password = read_board_password(&opts)?;
let report = stock::verify_zynq_live(
&host,
password.as_deref(),
&marker,
&kernel_version,
Duration::from_secs(timeout),
)?;
print!("{}", report.render());
if !report.ok() {
return Err(
"live verification failed: HTTP marker and SSH did not both confirm alkane".into(),
);
}
return Ok(());
}
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
if board == "am335x" {
let report = am335x::verify_live(
&host,
@@ -799,8 +911,13 @@ fn run_restore(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
&[
ssh_values(),
&[
"held-backup", "backup-dir", "confirm", "board", "held-kernel",
"held-dtb", "held-uboot",
"held-backup",
"backup-dir",
"confirm",
"board",
"held-kernel",
"held-dtb",
"held-uboot",
],
]
.concat(),
@@ -923,7 +1040,13 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
/// Boards this toolkit can install alkane onto, with the miner each is the
/// control board for. The install/restore gate is the .afw's board matching one
/// 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)")];
const SUPPORTED: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
(
"a113d",
"Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)",
),
];
fn is_supported(board: &str) -> bool {
SUPPORTED.iter().any(|(b, _)| *b == board)
@@ -934,7 +1057,9 @@ fn run_compat(_args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
for (board, miner) in SUPPORTED {
println!(" {board:<12} {miner}");
}
println!("\nInstall a local bundle: alkane-cli afw install <file.afw> --host <ip> --confirm FLASH");
println!(
"\nInstall a local bundle: alkane-cli afw install <file.afw> --host <ip> --confirm FLASH"
);
println!("Install the latest build: alkane-cli afw install --latest --board zynq-7010 --host <ip> --confirm FLASH");
println!("Remove (back to stock): alkane-cli afw restore-stock --host <ip> --confirm FLASH");
Ok(())
@@ -949,9 +1074,15 @@ fn run_fetch_latest(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &["board", "output"], &[])?;
let board = opts.value("board").unwrap_or("zynq-7010");
if !is_supported(board) {
return Err(format!("{board} is not a supported install target (see: alkane-cli afw compat)").into());
return Err(format!(
"{board} is not a supported install target (see: alkane-cli afw compat)"
)
.into());
}
let dest = opts.value("output").map(PathBuf::from).unwrap_or_else(download_dir);
let dest = opts
.value("output")
.map(PathBuf::from)
.unwrap_or_else(download_dir);
let path = fetch::fetch_latest_afw(&ReleaseSource::alkane_os(), board, &dest)?;
println!("fetched {}", path.display());
Ok(())
@@ -963,45 +1094,303 @@ fn resolve_afw_source(opts: &Opts) -> Result<PathBuf, Box<dyn std::error::Error>
if opts.flag("latest") {
let board = opts.value("board").unwrap_or("zynq-7010");
if !is_supported(board) {
return Err(format!("{board} is not a supported install target (see: alkane-cli afw compat)").into());
return Err(format!(
"{board} is not a supported install target (see: alkane-cli afw compat)"
)
.into());
}
println!("fetching the latest {board} release from Gitea...");
let path = fetch::fetch_latest_afw(&ReleaseSource::alkane_os(), board, &download_dir())?;
println!("using {}", path.display());
return Ok(path);
}
opts.positionals
.first()
.map(PathBuf::from)
.ok_or_else(|| "usage: alkane-cli afw install <file>|--latest --host <ip> --confirm FLASH".into())
opts.positionals.first().map(PathBuf::from).ok_or_else(|| {
"usage: alkane-cli afw install <file>|--latest --host <ip> --confirm FLASH".into()
})
}
/// Return an alkane board to genuine stock via the sealed stock-restore method,
/// then leave the independent verification to the operator/bench.
/// Return an alkane board to genuine Bitmain stock by writing the stock images
/// from a genuine vendor firmware package back to NAND, over the network.
fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["dry-run"])?;
let host = opts.value("host").ok_or("--host is required")?;
// Restore runs over the network against the alkane board, so it needs the
// board's root credential; it is passed to the compiled-in method in-process.
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();
// Restore reaches the alkane board over SSH as root; the board credential is
// supplied via --password-file / ALKANE_BOARD_PASSWORD(_FILE).
let password = read_board_password(&opts)?;
// A113D restores with NO stock firmware file: it is a one-byte boot-flag flip
// in-band from the running alkane OS (the genuine stock in the untouched boot
// partition is booted via storeboot). Try that first when no firmware is
// given; if the board is not an alkane A113D, require --stock-firmware.
let firmware = match opts.value("stock-firmware") {
Some(f) => f,
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!("Re-run with --confirm FLASH.");
return Ok(());
}
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to restore without --confirm FLASH".into());
}
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!("verify independently: the board should present genuine stock");
println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x).");
return Ok(());
}
Err(alkane_flash::stock::StockError::NotApplicable) => {
return Err("this board is not an alkane A113D; pass --stock-firmware \
<genuine Bitmain OTA .tar.gz or SD .zip> to restore it"
.into());
}
Err(e) => return Err(e.into()),
}
}
};
// Parse the genuine vendor package for the stock kernel + rootfs. The kernel
// device tree is not in distributable Bitmain firmware; the toolkit supplies
// the correct per-board dtb, so any genuine package (OTA or SD) works here.
let fw = stock_firmware::parse(Path::new(firmware))?;
println!("stock firmware: {}", fw.summary());
if opts.flag("dry-run") {
println!("DRY RUN: would restore {host} to stock via the network-only restore-to-stock method");
println!("DRY RUN: would restore {host} to stock by writing the genuine stock kernel");
println!("and rootfs plus the per-board device tree back to NAND (BOOT.bin preserved).");
println!("Re-run with --confirm FLASH.");
return Ok(());
}
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to restore without --confirm FLASH".into());
}
println!("restoring {host} to stock (network-only method)...");
stock::restore_to_stock(host, password.as_deref())?;
println!("restore-to-stock reported success.");
println!("verify independently: the board should no longer answer as alkane (no alkane console/API),");
println!("and should present its genuine stock OS. Confirm over the network or serial before reuse.");
println!("restoring {host} to genuine stock from {firmware} (network-only)...");
let images = RestoreImages {
kernel: &fw.kernel,
rootfs: &fw.rootfs,
dtb: fw.dtb.as_deref(),
};
stock::restore_to_stock(&host, &images, password.as_deref())?;
println!("restore-to-stock reported success (stock images written, BOOT.bin preserved).");
println!("verify independently: the board should no longer answer as alkane and should");
println!("present genuine stock (lighttpd 401 on :80, TCP 22 closed).");
Ok(())
}
/// Run a command as root on a stock board and print its output (drives the DSH
/// root-on-stock primitive; used to build and debug the flash operations).
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(" ");
if cmd.trim().is_empty() {
return Err("usage: alkane-cli afw root-run --host <ip> <command...>".into());
}
let password = read_board_password(&opts)?;
let out = stock::root_exec(&host, password.as_deref(), &cmd)?;
print!("{out}");
Ok(())
}
/// Readable zynq NAND install-from-stock: wrap the afw's zImage/rootfs as the
/// legacy uImages the stock U-Boot boots, carve the on-board genuine-stock
/// 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 host = opts.value("host").ok_or("--host is required")?.to_owned();
let afw_path = opts
.positionals
.first()
.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());
}
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 dtb = verified.image("dtb").ok_or("afw missing dtb 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
);
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)."
);
print!("{}", zynq_verify_hint(&host));
Ok(())
}
/// Readable zynq restore-to-stock: write the vendor stock kernel/dtb/rootfs
/// 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 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 fw = stock_firmware::parse(Path::new(firmware))?;
println!("stock firmware: {}", fw.summary());
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to restore without --confirm FLASH".into());
}
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)."
);
Ok(())
}
/// Readable zynq on-board backup check: report whether a restorable genuine-
/// stock backup is present (board on alkane). Read-only.
fn run_nand_backup_check(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 password = read_board_password(&opts)?;
if zynq_nand::onboard_backup_present(&host, password.as_deref())? {
println!("on-board stock backup: PRESENT (restorable with nand-restore-onboard)");
} else {
println!("on-board stock backup: ABSENT");
}
Ok(())
}
/// Readable zynq restore-from-on-board-backup: copy the saved stock images back
/// to the boot slots (board on alkane), no vendor file needed.
fn run_nand_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &[])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to restore without --confirm FLASH".into());
}
let password = read_board_password(&opts)?;
println!("restoring {host} to stock from its on-board backup (readable NAND path)...");
zynq_nand::restore_from_onboard(&host, password.as_deref())?;
println!("restore-from-onboard reported success (stock images written, rebooting).");
Ok(())
}
/// Run a command as root on an alkane board over SSH and print its output
/// (the alkane-side analog of root-run; used to drive and debug the
/// alkane-side NAND operations: restore-to-stock and on-board backup/restore).
fn run_ssh_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, ssh_values(), &[])?;
let cmd = opts.positionals.join(" ");
if cmd.trim().is_empty() {
return Err("usage: alkane-cli afw ssh-run --host <ip> <command...>".into());
}
let (ssh, _secret) = ssh_options(&opts, "root")?;
let mut transport = SshTransport::connect(ssh, true)?;
let out = transport.root_command(&cmd, std::time::Duration::from_secs(120))?;
print!("{}", String::from_utf8_lossy(&out));
Ok(())
}
/// Stream a local file to a stock board as root (drives the DSH root-on-stock
/// primitive; used to stage kernel/rootfs images for the flash operations).
fn run_root_put(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &[ssh_values(), &["remote"]].concat(), &[])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let remote = opts
.value("remote")
.ok_or("--remote <path> is required")?
.to_owned();
let local = opts
.positionals
.first()
.ok_or("usage: alkane-cli afw root-put --host <ip> --remote <path> <local-file>")?;
let data = std::fs::read(local)?;
let password = read_board_password(&opts)?;
stock::root_put(&host, password.as_deref(), &data, &remote)?;
println!("put {} bytes -> {remote}", data.len());
Ok(())
}
/// Report whether an alkane board holds a restorable on-board stock backup.
/// Read-only (no FLASH confirmation).
fn run_backup_check(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 password = read_board_password(&opts)?;
let present = stock::onboard_stock_backup_present(&host, password.as_deref())?;
println!("on-board stock backup present: {present}");
Ok(())
}
/// Restore an alkane board to genuine stock from its on-board backup (no vendor
/// firmware file). Destructive; gated by --confirm FLASH.
fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["dry-run"])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let password = read_board_password(&opts)?;
if opts.flag("dry-run") {
println!(
"DRY RUN: would restore {host} to stock from its on-board backup \
(BOOT.bin preserved). Re-run with --confirm FLASH."
);
return Ok(());
}
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to restore without --confirm FLASH".into());
}
println!("restoring {host} to stock from its on-board backup (network-only)...");
stock::restore_from_onboard_backup(
&host,
password.as_deref(),
std::time::Duration::from_secs(300),
)?;
println!(
"restore-from-onboard reported success. Verify independently the board answers as stock."
);
Ok(())
}
fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let subcommand = args.first().ok_or(
"usage: alkane-cli afw <compat|fetch-latest|verify|inspect|plan|preflight|install|verify-live|restore|restore-stock>",
"usage: alkane-cli afw <compat|fetch-latest|verify|inspect|plan|preflight|install|verify-live|restore|restore-stock|backup-check|restore-onboard>",
)?;
let rest = &args[1..];
match subcommand.as_str() {
@@ -1015,6 +1404,15 @@ fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
"verify-live" => run_verify_live(rest),
"restore" => run_restore(rest),
"restore-stock" => run_restore_stock(rest),
"backup-check" => run_backup_check(rest),
"restore-onboard" => run_restore_onboard(rest),
"root-run" => run_root_run(rest),
"root-put" => run_root_put(rest),
"ssh-run" => run_ssh_run(rest),
"nand-install" => run_nand_install(rest),
"nand-restore-stock" => run_nand_restore_stock(rest),
"nand-backup-check" => run_nand_backup_check(rest),
"nand-restore-onboard" => run_nand_restore_onboard(rest),
other => Err(format!("unknown afw subcommand {other}").into()),
}
}
+660
View File
@@ -0,0 +1,660 @@
// SPDX-License-Identifier: MIT
//! Readable Amlogic A113D (Amlogic AXG, Antminer BHB42XXX) install/restore over
//! the FLAG-BASED boot chain. This is the Claude-domain counterpart of
//! `zynq_nand`: it drives the DSH root-on-stock primitive (`stock::root_exec` /
//! `stock::root_put`) for the from-stock install, and the alkane SSH transport
//! for the in-band restore, with the stock-access method never read here.
//!
//! Mechanism (CONFIRMED live 2026-11-13, see alkane-sdk-construction
//! alkane-a113d-image-bringup):
//!
//! - The OS files `alkane/{vmlinux.bin,devicetree.dtb,uramdisk.image.gz}` are
//! staged into the nvdata UBI volume (UBIFS), exactly as the alkane boot chain
//! reads them (`ubifsload`). Zero raw writes to the brick-sensitive regions.
//! - A one-byte-magic FLAG lives in the `misc` partition (the Android BCB block,
//! abs NAND 0x1000000) at erase-block 1 (offset 0x20000, abs 0x1020000). Block
//! 0 (the BCB) is never touched. The flag is the four bytes "ALAN".
//! - Stock U-Boot's `bootcmd` is set (once, in-band via /dev/nand_env from stock)
//! to `run checkalk; run storeboot`, where `checkalk` RAW-reads the flag page
//! (`nand read`, NO UBI) and, only if the magic matches, runs `alkboot` (which
//! mounts the nvdata UBIFS and boots alkane). When the flag is absent the stock
//! path is a pure raw read + `storeboot`, which boots genuine stock STABLY (a
//! ubi/ubifs op in the stock boot path instead makes stock's firstboot
//! supervisor reboot-loop - that is why the flag read must be raw).
//! - INSTALL (stock -> alkane): stage the files, write the env, set flag=ALAN.
//! - RESTORE (alkane -> stock): erase the flag block in-band from the running
//! alkane OS (which exposes `misc` as an MTD). One raw NAND erase, `reboot -f`,
//! and stock boots via `storeboot`. Fully network-only; the alkane payload and
//! the env are left in place, so re-install is just re-writing the flag.
//!
//! itest note: this vendor U-Boot's `itest.l *<mem>` does NOT compare correctly,
//! but `itest.b *<mem>` does, so `checkalk` tests the four magic bytes with
//! nested `itest.b`. CONFIRMED live 2026-11-13.
use crate::stock::StockError;
use crate::transport::{Remote, SshOptions, SshTransport};
use crate::uimage::crc32;
use std::path::{Path, PathBuf};
use std::time::Duration;
pub const BOARD: &str = "a113d";
/// U-Boot env blob size on this board (CONFIRMED: `/dev/nand_env` is 64 KiB, a
/// standard U-Boot env = 4-byte little-endian CRC32 + NUL-separated key=value,
/// double-NUL terminated, 0x00-padded).
const ENV_SIZE: usize = 65536;
/// Flag: four magic bytes "ALAN" at misc (abs 0x1000000) erase-block 1.
const FLAG_ABS_OFFSET: u64 = 0x1020000; // misc base 0x1000000 + block 1 (0x20000)
const FLAG_BLOCK_IN_MISC: u64 = 0x20000; // offset of the flag block within the misc MTD
const FLAG_MAGIC: [u8; 4] = *b"ALAN";
/// Boot load addresses (CONFIRMED live) and the alkane console bootargs.
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";
/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory.
const ALKANE_DIR: &str = "alkane";
// ---------------------------------------------------------------------------
// Shell abstraction: StockShell drives the DSH root primitive; AlkaneShell the
// alkane SSH transport. (Mirrors zynq_nand.)
// ---------------------------------------------------------------------------
trait Shell {
fn exec(&mut self, cmd: &str) -> Result<String, StockError>;
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError>;
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>;
}
struct StockShell {
host: String,
password: Option<String>,
}
impl Shell for StockShell {
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
}
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
// root_exec already carries a generous timeout in the method.
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
}
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path)
}
}
struct AlkaneShell {
transport: SshTransport,
_secret: TempFile,
}
impl AlkaneShell {
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
// Password in a 0600 temp file; a throwaway empty known_hosts (the host
// key legitimately changes across stock<->alkane). Same stance as zynq.
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
let known = temp_path("kh");
let _ = std::fs::File::create(&known);
let options = SshOptions {
host: host.to_owned(),
port: 22,
user: "root".to_owned(),
identity_file: None,
password_file: Some(secret.0.clone()),
known_hosts: Some(known),
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
})
}
}
impl Shell for AlkaneShell {
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
self.transport
.root_command(cmd, Duration::from_secs(120))
.map(|o| String::from_utf8_lossy(&o).into_owned())
.map_err(|e| StockError::Method(e.to_string()))
}
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
self.transport
.root_command(cmd, Duration::from_secs(900))
.map(|o| String::from_utf8_lossy(&o).into_owned())
.map_err(|e| StockError::Method(e.to_string()))
}
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
let tmp = TempFile::with(data, "put")?;
self.transport
.push(&tmp.0, remote_path, Duration::from_secs(900))
.map_err(|e| StockError::Method(e.to_string()))
}
}
static TEMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn temp_path(tag: &str) -> PathBuf {
let n = TEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::env::temp_dir().join(format!("alkane-aml-{}-{}-{}", std::process::id(), tag, n))
}
/// A 0600 temp file removed on drop.
struct TempFile(PathBuf);
impl TempFile {
fn with(contents: &[u8], tag: &str) -> Result<Self, StockError> {
let path = temp_path(tag);
write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?;
Ok(TempFile(path))
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[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)
.truncate(true)
.write(true)
.mode(0o600)
.open(path)?;
f.write_all(contents)?;
f.flush()
}
#[cfg(not(unix))]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
std::fs::write(path, contents)
}
// ---------------------------------------------------------------------------
// base64 (busybox-safe: decode a possibly line-wrapped stream).
// ---------------------------------------------------------------------------
fn b64_decode(s: &str) -> Option<Vec<u8>> {
const INV: u8 = 0xFF;
fn val(c: u8) -> u8 {
match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
_ => INV,
}
}
let mut out = Vec::new();
let mut acc = 0u32;
let mut bits = 0u32;
for &c in s.as_bytes() {
if c == b'=' {
break;
}
let v = val(c);
if v == INV {
continue; // skip whitespace / newlines
}
acc = (acc << 6) | v as u32;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
}
}
Some(out)
}
fn b64_encode(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
out.push(T[((n >> 18) & 63) as usize] as char);
out.push(T[((n >> 12) & 63) as usize] as char);
out.push(if chunk.len() > 1 {
T[((n >> 6) & 63) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
T[(n & 63) as usize] as char
} else {
'='
});
}
out
}
// ---------------------------------------------------------------------------
// U-Boot environment (standard format) read / parse / build / write.
// ---------------------------------------------------------------------------
/// Read the 64 KiB U-Boot env blob from /dev/nand_env (stock only).
fn read_env(sh: &mut dyn Shell) -> Result<Vec<u8>, StockError> {
let out = sh.exec(
"echo B64START; dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | base64; echo B64END",
)?;
let start = out
.find("B64START")
.ok_or_else(|| StockError::Method("env read: no marker".into()))?;
let end = out
.find("B64END")
.ok_or_else(|| StockError::Method("env read: no end marker".into()))?;
let b64 = &out[start + "B64START".len()..end];
let blob = b64_decode(b64).ok_or_else(|| StockError::Method("env read: bad base64".into()))?;
if blob.len() != ENV_SIZE {
return Err(StockError::Method(format!(
"env read: {} bytes (expected {ENV_SIZE})",
blob.len()
)));
}
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
if crc32(&blob[4..]) != stored {
return Err(StockError::Method("env read: CRC mismatch".into()));
}
Ok(blob)
}
/// Parse the env body into ordered (key, value) pairs (up to the double-NUL).
fn parse_env(blob: &[u8]) -> Vec<(String, String)> {
let body = &blob[4..];
let end = body
.windows(2)
.position(|w| w == [0, 0])
.unwrap_or(body.len());
let mut vars = Vec::new();
for kv in body[..end].split(|&b| b == 0) {
if kv.is_empty() {
continue;
}
if let Some(eq) = kv.iter().position(|&b| b == b'=') {
let k = String::from_utf8_lossy(&kv[..eq]).into_owned();
let v = String::from_utf8_lossy(&kv[eq + 1..]).into_owned();
vars.push((k, v));
}
}
vars
}
/// Build a 64 KiB env blob from ordered (key,value) pairs: CRC32 + body +
/// double-NUL + 0x00 padding (what a clean `saveenv` produces).
fn build_env(vars: &[(String, String)]) -> Result<Vec<u8>, StockError> {
let mut body = Vec::with_capacity(ENV_SIZE);
for (k, v) in vars {
body.extend_from_slice(k.as_bytes());
body.push(b'=');
body.extend_from_slice(v.as_bytes());
body.push(0);
}
body.push(0); // terminating double-NUL (last var's NUL + this one)
if body.len() > ENV_SIZE - 4 {
return Err(StockError::Method("env too large".into()));
}
body.resize(ENV_SIZE - 4, 0);
let crc = crc32(&body);
let mut blob = Vec::with_capacity(ENV_SIZE);
blob.extend_from_slice(&crc.to_le_bytes());
blob.extend_from_slice(&body);
Ok(blob)
}
/// Set (or insert, preserving order) a variable.
fn set_var(vars: &mut Vec<(String, String)>, key: &str, value: &str) {
if let Some(slot) = vars.iter_mut().find(|(k, _)| k == key) {
slot.1 = value.to_owned();
} else {
vars.push((key.to_owned(), value.to_owned()));
}
}
/// Write the env blob to /dev/nand_env and read it back byte-exact BEFORE any
/// reboot (the env is only consumed at next boot, so a verified read-back cannot
/// brick). On a read-back mismatch the caller must restore the previous env.
fn write_env(sh: &mut dyn Shell, blob: &[u8]) -> Result<(), StockError> {
let b64 = b64_encode(blob);
// Stream the blob to a temp file, then dd it to /dev/nand_env in one write.
sh.put(b64.as_bytes(), "/tmp/.alkenv.b64")?;
let out = sh.exec(
"base64 -d /tmp/.alkenv.b64 > /tmp/.alkenv.bin 2>/dev/null; \
dd if=/tmp/.alkenv.bin of=/dev/nand_env bs=65536 count=1 2>/dev/null; sync; \
echo RB=$(dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | md5sum | cut -d' ' -f1); \
rm -f /tmp/.alkenv.b64 /tmp/.alkenv.bin",
)?;
let want = md5_hex(blob);
let got = out
.split("RB=")
.nth(1)
.map(|s| s.trim().to_owned())
.unwrap_or_default();
if got != want {
return Err(StockError::Method(format!(
"env write read-back mismatch: wrote {want}, read {got}"
)));
}
Ok(())
}
fn md5_hex(data: &[u8]) -> String {
crate::md5::md5_hex(data)
}
// ---------------------------------------------------------------------------
// MTD / flag helpers.
// ---------------------------------------------------------------------------
/// Find the /dev/mtdN whose /proc/mtd label matches `name`.
fn find_mtd(sh: &mut dyn Shell, name: &str) -> Result<String, StockError> {
let out = sh.exec("cat /proc/mtd")?;
for line in out.lines() {
if line.contains(&format!("\"{name}\"")) {
if let Some((dev, _)) = line.split_once(':') {
return Ok(format!("/dev/{}", dev.trim()));
}
}
}
Err(StockError::Method(format!("no '{name}' MTD on this board")))
}
/// Discover the nvdata UBI volume's name (never assumed: vendor histories leave
/// different names). Looks for an already-attached ubi volume on the nvdata MTD.
fn discover_nvdata_volume(sh: &mut dyn Shell) -> Result<(String, String), StockError> {
// Returns (mountpoint, volume_name). On stock the vendor mounts nvdata (e.g.
// at /tmp/miner); find the ubifs mount whose volume sits on the nvdata MTD.
let mounts = sh.exec("cat /proc/mounts")?;
for line in mounts.lines() {
// e.g. "/dev/ubi2_0 /tmp/miner ubifs rw,..."
let mut it = line.split_whitespace();
let dev = it.next().unwrap_or("");
let mnt = it.next().unwrap_or("");
let fs = it.next().unwrap_or("");
if fs == "ubifs" && dev.contains("ubi") {
// read the volume name from sysfs: /sys/class/ubi/<ubiX_0>/name
let base = dev.trim_start_matches("/dev/");
let name = sh
.exec(&format!("cat /sys/class/ubi/{base}/name 2>/dev/null"))?
.trim()
.to_owned();
// Only accept the nvdata volume (skip the small config_data volume).
// nvdata is the large one; confirm by its mount not being /config.
if !name.is_empty() && mnt != "/config" {
return Ok((mnt.to_owned(), name));
}
}
}
Err(StockError::Method(
"could not find the mounted nvdata UBI volume".into(),
))
}
/// Write the ALAN flag into misc block 1 (flag=alkane). `misc_dev` is the misc
/// MTD device on the running OS (stock: /dev/mtd2; alkane: whatever /proc/mtd
/// shows for "misc").
fn set_flag_alkane(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> {
// one page: magic + 0xFF pad
let mut page = FLAG_MAGIC.to_vec();
page.resize(2048, 0xFF);
sh.put(&page, "/tmp/.alkflag")?;
let out = sh.exec(&format!(
"flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; \
nandwrite -s 0x{FLAG_BLOCK_IN_MISC:x} -p {misc_dev} /tmp/.alkflag >/dev/null 2>&1; sync; \
echo RB=$(dd if={misc_dev} bs=2048 skip={blk} count=1 2>/dev/null | md5sum | cut -d' ' -f1); \
rm -f /tmp/.alkflag",
blk = FLAG_BLOCK_IN_MISC / 2048
))?;
let want = md5_hex(&page);
let got = out
.split("RB=")
.nth(1)
.map(|s| s.trim().to_owned())
.unwrap_or_default();
if got != want {
return Err(StockError::Method("flag write read-back mismatch".into()));
}
Ok(())
}
/// Erase the flag block (flag=stock).
fn clear_flag(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> {
sh.exec(&format!(
"flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; sync; echo CLEARED"
))?;
Ok(())
}
// ---------------------------------------------------------------------------
// The flag-based boot-chain env vars.
// ---------------------------------------------------------------------------
/// checkalk raw-reads the flag page and tests the four magic bytes with nested
/// `itest.b` (this vendor U-Boot mis-compares `itest.l *<mem>`); only on a match
/// does it run alkboot. No ubi/ubifs here - that keeps the stock path raw.
fn checkalk_value() -> String {
format!(
"nand read 0x08000000 0x{FLAG_ABS_OFFSET:x} 0x800; \
if itest.b *0x08000000 == 0x{a:02x}; then \
if itest.b *0x08000001 == 0x{l:02x}; then \
if itest.b *0x08000002 == 0x{a2:02x}; then \
if itest.b *0x08000003 == 0x{n:02x}; then run alkboot; fi; fi; fi; fi",
a = FLAG_MAGIC[0],
l = FLAG_MAGIC[1],
a2 = FLAG_MAGIC[2],
n = FLAG_MAGIC[3],
)
}
/// alkboot mounts the nvdata UBIFS and boots alkane from `alkane/`.
fn alkboot_value(volume: &str) -> String {
format!(
"setenv bootargs ${{alkbootargs}}; ubi part nvdata; ubifsmount ubi0:{volume}; \
ubifsload ${{krnaddr}} {ALKANE_DIR}/vmlinux.bin; \
ubifsload ${{fdtaddr}} {ALKANE_DIR}/devicetree.dtb; \
ubifsload ${{rdaddr}} {ALKANE_DIR}/uramdisk.image.gz; \
booti ${{krnaddr}} ${{rdaddr}} ${{fdtaddr}}"
)
}
/// Install the flag-based boot env (preserving all existing stock vars). Leaves
/// bootcmd = "run checkalk; run storeboot".
fn install_boot_env(sh: &mut dyn Shell, volume: &str) -> Result<(), StockError> {
let blob = read_env(sh)?;
let mut vars = parse_env(&blob);
set_var(&mut vars, "krnaddr", KRNADDR);
set_var(&mut vars, "fdtaddr", FDTADDR);
set_var(&mut vars, "rdaddr", RDADDR);
set_var(&mut vars, "alkbootargs", ALK_BOOTARGS);
set_var(&mut vars, "alkboot", &alkboot_value(volume));
set_var(&mut vars, "checkalk", &checkalk_value());
set_var(&mut vars, "bootcmd", "run checkalk; run storeboot");
let new_blob = build_env(&vars)?;
write_env(sh, &new_blob)
}
fn reboot_stock(sh: &mut dyn Shell) {
let _ = sh.exec("sync; reboot");
}
fn reboot_alkane(sh: &mut dyn Shell) {
// plain `reboot` no-ops on the minimal init; `reboot -f` triggers PSCI reset.
let _ = sh.exec("sync; reboot -f");
}
// ---------------------------------------------------------------------------
// Public API (dispatched from stock.rs for board == a113d).
// ---------------------------------------------------------------------------
/// Install alkane onto an A113D running genuine stock, network-only, over the
/// DSH root-on-stock primitive. Stages the OS files into the nvdata UBI volume,
/// installs the flag-based boot env, and sets flag=alkane; the next boot runs
/// alkane. Zero raw writes outside the flag block in `misc`.
pub fn install_from_stock(
host: &str,
kernel_image: &[u8],
dtb: &[u8],
uramdisk: &[u8],
password: Option<&str>,
) -> Result<(), StockError> {
let mut sh = StockShell {
host: host.to_owned(),
password: password.map(|s| s.to_owned()),
};
// Guard: this board must be A113D stock (has a 'misc' MTD and a mounted
// nvdata UBI). If not, defer to the compiled-in method.
let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default();
if !proc_mtd.contains("\"nvdata\"") || !proc_mtd.contains("\"misc\"") {
return Err(StockError::NotApplicable);
}
let misc = find_mtd(&mut sh, "misc")?;
let (mount, volume) = discover_nvdata_volume(&mut sh)?;
// Stage the three files into <mount>/alkane/ and read-back verify.
let dir = format!("{mount}/{ALKANE_DIR}");
sh.exec(&format!("mkdir -p {dir}"))?;
// rootfs -> dtb -> kernel (kernel lands last).
stage_file(&mut sh, uramdisk, &format!("{dir}/uramdisk.image.gz"))?;
stage_file(&mut sh, dtb, &format!("{dir}/devicetree.dtb"))?;
stage_file(&mut sh, kernel_image, &format!("{dir}/vmlinux.bin"))?;
sh.exec("sync")?;
// Install the flag-based boot env (read-back verified before reboot).
install_boot_env(&mut sh, &volume)?;
// Set flag=alkane, then reboot into alkane.
set_flag_alkane(&mut sh, &misc)?;
reboot_stock(&mut sh);
Ok(())
}
/// Stage one file to a UBIFS path and prove its read-back md5 before continuing.
fn stage_file(sh: &mut dyn Shell, data: &[u8], dest: &str) -> Result<(), StockError> {
let tmp = "/tmp/.alkstage";
sh.put(data, tmp)?;
let out = sh.exec_long(&format!(
"cp -f {tmp} {dest} && sync; echo RB=$(md5sum {dest} | cut -d' ' -f1); rm -f {tmp}"
))?;
let want = md5_hex(data);
let got = out
.split("RB=")
.nth(1)
.map(|s| s.trim().to_owned())
.unwrap_or_default();
if got != want {
return Err(StockError::Method(format!(
"staged {dest} md5 mismatch: want {want}, got {got}"
)));
}
Ok(())
}
/// Restore an A113D running alkane back to genuine stock, network-only, in-band
/// from the running alkane OS: erase the flag block (flag=stock) and reboot.
/// Stock boots via `storeboot` from the untouched `boot` MTD; the alkane payload
/// and env are left in place, so a re-install is just re-writing the flag.
pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> {
let mut sh = AlkaneShell::connect(host, password)?;
// Guard: must be the alkane a113d image (exposes 'misc' and 'nvdata' MTDs,
// mainline 6.18.48). If 'misc' is absent this is not applicable.
let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default();
if !proc_mtd.contains("\"misc\"") {
return Err(StockError::NotApplicable);
}
let misc = find_mtd(&mut sh, "misc")?;
clear_flag(&mut sh, &misc)?;
reboot_alkane(&mut sh);
Ok(())
}
/// The on-board stock backup is structural on this board: `storeboot` always
/// boots genuine stock from the `boot` MTD (mtd4), which this install never
/// writes. So a complete backup is present whenever the board is an A113D.
pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result<bool, StockError> {
// Best-effort confirm over alkane that the flag chain is in place; if we
// cannot reach alkane, report not-applicable so the caller falls through.
let mut sh = AlkaneShell::connect(host, password)?;
let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default();
if proc_mtd.contains("\"misc\"") {
Ok(true)
} else {
Err(StockError::NotApplicable)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn env_roundtrips_with_crc() {
let vars = vec![
(
"bootcmd".to_owned(),
"run checkalk; run storeboot".to_owned(),
),
("bootdelay".to_owned(), "1".to_owned()),
("checkalk".to_owned(), checkalk_value()),
];
let blob = build_env(&vars).unwrap();
assert_eq!(blob.len(), ENV_SIZE);
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!(parsed.iter().any(|(k, _)| k == "checkalk"));
}
#[test]
fn b64_roundtrip() {
for n in [0usize, 1, 2, 3, 64, 2048, 65536] {
let data: Vec<u8> = (0..n).map(|i| (i * 7 + 3) as u8).collect();
let enc = b64_encode(&data);
let dec = b64_decode(&enc).unwrap();
assert_eq!(dec, data, "n={n}");
}
// wrapped base64 decodes the same
let data: Vec<u8> = (0..100).map(|i| i as u8).collect();
let mut wrapped = b64_encode(&data);
wrapped.insert(20, '\n');
wrapped.insert(50, '\n');
assert_eq!(b64_decode(&wrapped).unwrap(), data);
}
#[test]
fn checkalk_is_raw_and_byte_tested() {
let c = checkalk_value();
assert!(c.starts_with("nand read 0x08000000"));
assert!(c.contains("itest.b *0x08000000 == 0x41"));
assert!(!c.contains("ubi")); // the stock path must never touch UBI
assert!(c.contains("run alkboot"));
}
#[test]
fn alkboot_loads_from_alkane_dir() {
let a = alkboot_value("nvdata_log");
assert!(a.contains("ubifsmount ubi0:nvdata_log"));
assert!(a.contains("alkane/vmlinux.bin"));
assert!(a.contains("booti ${krnaddr} ${rdaddr} ${fdtaddr}"));
}
}
+118 -35
View File
@@ -14,9 +14,9 @@
//! never changes the bootloader: the brick-sensitive regions are physically
//! unreachable.
//!
//! The first from-stock install (via the vendor toolkit, past the signed
//! bootloader) is the dsh-owned path and is NOT this module. This is the
//! repeatable alkane-to-alkane update.
//! The first from-stock install (past the signed bootloader) is handled
//! elsewhere and is NOT this module. This is the repeatable alkane-to-alkane
//! update.
use crate::md5::md5_hex;
use crate::preflight::{classify, parse_digest};
@@ -67,9 +67,17 @@ pub enum A113dPlanError {
#[error("a113d is missing the {0} image")]
MissingImage(String),
#[error("a113d {image} format is {actual}, expected {expected}")]
ImageFormat { image: String, actual: String, expected: &'static str },
ImageFormat {
image: String,
actual: String,
expected: &'static str,
},
#[error("a113d {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
ImageTooLarge { image: String, size: u64, ceiling: u64 },
ImageTooLarge {
image: String,
size: u64,
ceiling: u64,
},
#[error("a113d images total {total} bytes, over the nvdata UBI (0x{usable:x})")]
OverNvdata { total: u64, usable: u64 },
#[error("a113d {image} is not an arm64 Image")]
@@ -152,7 +160,9 @@ impl A113dPlan {
// Defense in depth: only nvdata (mtd6) may carry an image; mtd0-5 preserved.
for partition in &manifest.partitions {
if partition.name != "nvdata" && partition.image.is_some() {
return Err(A113dPlanError::PreservedCarriesImage(partition.name.clone()));
return Err(A113dPlanError::PreservedCarriesImage(
partition.name.clone(),
));
}
}
@@ -193,20 +203,29 @@ impl A113dPlan {
.image(image_name)
.map(|(_, data)| data)
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
// Each arm validates a different magic; keeping them as explicit
// arms (not match guards) reads more clearly than collapsing.
#[allow(clippy::collapsible_match)]
match expected_format {
"arm64-image" => {
if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") {
return Err(A113dPlanError::NotArm64 { image: image_name.to_owned() });
return Err(A113dPlanError::NotArm64 {
image: image_name.to_owned(),
});
}
}
"fdt" => {
if !(data.len() >= 4 && data[0..4] == [0xd0, 0x0d, 0xfe, 0xed]) {
return Err(A113dPlanError::NotFdt { image: image_name.to_owned() });
return Err(A113dPlanError::NotFdt {
image: image_name.to_owned(),
});
}
}
"uimage" => {
if !(data.len() >= 4 && data[0..4] == [0x27, 0x05, 0x19, 0x56]) {
return Err(A113dPlanError::NotUimage { image: image_name.to_owned() });
return Err(A113dPlanError::NotUimage {
image: image_name.to_owned(),
});
}
}
_ => {}
@@ -221,7 +240,10 @@ impl A113dPlan {
});
}
if total > NVDATA_USABLE {
return Err(A113dPlanError::OverNvdata { total, usable: NVDATA_USABLE });
return Err(A113dPlanError::OverNvdata {
total,
usable: NVDATA_USABLE,
});
}
Ok(Self {
@@ -324,7 +346,11 @@ impl A113dPreflight {
}
out.push_str(&format!(
"result {}",
if self.ok() { "PASS" } else { "FAIL (do not write)" }
if self.ok() {
"PASS"
} else {
"FAIL (do not write)"
}
));
out
}
@@ -376,7 +402,11 @@ pub fn preflight(
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(A113dCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
checks.push(A113dCheck {
name: "root".to_owned(),
ok: uid == "0",
detail: format!("uid {uid}"),
});
let tools = remote.user_command(
"for c in ubiattach ubidetach mount umount cp md5sum sync; do \
@@ -423,7 +453,11 @@ pub fn preflight(
detail: format!("all writes are files under {ALKANE_DIR}/ on the nvdata UBI"),
});
Ok(A113dPreflight { host: host.to_owned(), checks, nvdata_mtd })
Ok(A113dPreflight {
host: host.to_owned(),
checks,
nvdata_mtd,
})
}
#[derive(Clone, Debug)]
@@ -461,10 +495,7 @@ const MNT: &str = "/tmp/.alkane-nvdata";
/// Returns (ubi device number, volume name). The volume name is DISCOVERED, never
/// assumed (vendor histories leave different names: umc_os_rootfs, nvdada_log,
/// overlay, ...).
fn attach_and_mount(
remote: &mut dyn Remote,
nvdata_mtd: u32,
) -> Result<String, A113dError> {
fn attach_and_mount(remote: &mut dyn Remote, nvdata_mtd: u32) -> Result<String, A113dError> {
// Attach (idempotent: if ubi0 already exists, reuse it).
let _ = remote.root_command(
&format!(
@@ -488,8 +519,10 @@ fn attach_and_mount(
Duration::from_secs(60),
)?;
// Confirm the mount actually took.
let mounted =
remote.user_command(&format!("mount | grep -c ' {MNT} '"), Duration::from_secs(20))?;
let mounted = remote.user_command(
&format!("mount | grep -c ' {MNT} '"),
Duration::from_secs(20),
)?;
if String::from_utf8_lossy(&mounted).trim() == "0" {
return Err(A113dError::Mount);
}
@@ -498,7 +531,9 @@ fn attach_and_mount(
fn unmount(remote: &mut dyn Remote) {
let _ = remote.root_command(
&format!("sync; umount {MNT} 2>/dev/null; ubidetach -d 0 2>/dev/null; rmdir {MNT} 2>/dev/null"),
&format!(
"sync; umount {MNT} 2>/dev/null; ubidetach -d 0 2>/dev/null; rmdir {MNT} 2>/dev/null"
),
Duration::from_secs(60),
);
}
@@ -524,7 +559,10 @@ pub fn install(
.ok_or_else(|| A113dError::NoNvdataMtd(NVDATA_LABEL.to_owned()))?;
fs::create_dir_all(&options.backup_dir)?;
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
let epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let volume = attach_and_mount(remote, nvdata_mtd)?;
let alkane_dir = format!("{MNT}/{ALKANE_DIR}");
@@ -546,7 +584,9 @@ pub fn install(
Duration::from_secs(15),
)?;
if String::from_utf8_lossy(&have).contains("__YES__") {
let local = options.backup_dir.join(format!("{}-{epoch}.bak", target.dest));
let local = options
.backup_dir
.join(format!("{}-{epoch}.bak", target.dest));
remote.pull(&dest_path, &local, Duration::from_secs(300))?;
let data = fs::read(&local)?;
backups.push(A113dBackup {
@@ -613,7 +653,11 @@ pub fn install(
remote.reboot()?;
true
};
Ok(A113dOutcome::Installed(A113dReceipt { volume, backups, rebooted }))
Ok(A113dOutcome::Installed(A113dReceipt {
volume,
backups,
rebooted,
}))
}
pub fn owns_board(board: &str) -> bool {
@@ -661,7 +705,10 @@ mod tests {
partitions: serde_json::Value,
) -> VerifiedAfw {
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
let sha: String = Sha256::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "nvdata", "install": true})
};
@@ -684,9 +731,18 @@ mod tests {
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/vmlinux.bin".to_owned(), data: kernel },
AfwMember { name: "payload/devicetree.dtb".to_owned(), data: dtb },
AfwMember { name: "payload/uramdisk.image.gz".to_owned(), data: rootfs },
AfwMember {
name: "payload/vmlinux.bin".to_owned(),
data: kernel,
},
AfwMember {
name: "payload/devicetree.dtb".to_owned(),
data: dtb,
},
AfwMember {
name: "payload/uramdisk.image.gz".to_owned(),
data: rootfs,
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
@@ -715,7 +771,11 @@ mod tests {
assert_eq!(plan.targets[2].image_name, "kernel");
assert!(no_raw_device_targets(&plan));
for t in &plan.targets {
assert!(!t.dest.contains('/'), "{} has a path, not a basename", t.image_name);
assert!(
!t.dest.contains('/'),
"{} has a path, not a basename",
t.image_name
);
}
assert!(plan.render().contains("alkane/"));
assert!(plan.render().contains("no raw NAND write is possible"));
@@ -723,7 +783,12 @@ mod tests {
#[test]
fn refuses_a_non_arm64_kernel() {
let r = A113dPlan::from_afw(&afw_with(vec![0u8; 64], dtb(), uramdisk(), preserved_partitions()));
let r = A113dPlan::from_afw(&afw_with(
vec![0u8; 64],
dtb(),
uramdisk(),
preserved_partitions(),
));
assert!(matches!(r, Err(A113dPlanError::NotArm64 { .. })));
}
@@ -738,10 +803,16 @@ mod tests {
fn refuses_a_fip_member() {
let mut v = good();
v.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::BootloaderMember(_))
));
let mut v = good();
v.manifest.images[1].file = "payload/fip.bin".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::BootloaderMember(_))
));
}
#[test]
@@ -763,16 +834,25 @@ mod tests {
fn wrong_board_and_arch_are_refused() {
let mut v = good();
v.manifest.board = "zynq-7010".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongBoard(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::WrongBoard(_))
));
let mut v = good();
v.manifest.arch = "armv7".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongArch(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::WrongArch(_))
));
}
#[test]
fn every_target_is_a_basename_never_a_device() {
for (image, dest, _ceiling, _fmt) in TARGETS {
assert!(is_safe_dest(dest), "{image} dest {dest} is not a safe basename");
assert!(
is_safe_dest(dest),
"{image} dest {dest} is not a safe basename"
);
}
}
@@ -792,6 +872,9 @@ mod tests {
// No nvdata line -> None (the no-NAND running image).
assert_eq!(parse_nvdata_mtd("dev: size erasesize name\n"), None);
// Different index is honored.
assert_eq!(parse_nvdata_mtd("mtd3: 0b900000 00020000 \"nvdata\"\n"), Some(3));
assert_eq!(
parse_nvdata_mtd("mtd3: 0b900000 00020000 \"nvdata\"\n"),
Some(3)
);
}
}
+176 -99
View File
@@ -10,9 +10,7 @@ use crate::install::{api_version, http_get};
use crate::md5::md5_hex;
use crate::preflight::{classify, parse_digest};
use crate::transport::{Remote, RemoteError, SshOptions, SshTransport};
use alkane_artifacts::afw::{
AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw,
};
use alkane_artifacts::afw::{AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::fs;
@@ -88,7 +86,15 @@ const TARGET_IMAGES_STOCK: [(&str, &str, u64); 4] = [
pub struct Profile {
pub board: &'static str,
pub policy: BootloaderPolicy,
pub mtd_map: &'static [(&'static str, u64, u64, bool, bool, i64, Option<&'static str>)],
pub mtd_map: &'static [(
&'static str,
u64,
u64,
bool,
bool,
i64,
Option<&'static str>,
)],
pub preserve: &'static [&'static str],
pub targets: &'static [(&'static str, &'static str, u64)],
/// Tier 3 ships our U-Boot as a `bootloader` member; tier 2 never does.
@@ -319,7 +325,11 @@ impl Am335xPlan {
Ok(Self {
board: profile.board.to_owned(),
preserve: profile.preserve.iter().map(|name| (*name).to_owned()).collect(),
preserve: profile
.preserve
.iter()
.map(|name| (*name).to_owned())
.collect(),
targets,
partitions: manifest.partitions.clone(),
marker: manifest.marker.clone(),
@@ -351,9 +361,7 @@ impl Am335xPlan {
);
} else {
out.push_str("bootloader preserve (mtd0-5 SPL/U-Boot/bootenv kept, never written)\n");
out.push_str(
"image format legacy-uimage (kernel type 2, ramdisk type 3), never FIT\n",
);
out.push_str("image format legacy-uimage (kernel type 2, ramdisk type 3), never FIT\n");
}
out.push_str(&format!(
"nand hole 0x{:x}-0x{:x} (never written)\n",
@@ -523,7 +531,9 @@ impl AmPreflightReport {
"free tmp {} MiB\n",
self.free_bytes / (1024 * 1024)
));
out.push_str("preserved partitions (see preserve-spl check): never erased and never written\n");
out.push_str(
"preserved partitions (see preserve-spl check): never erased and never written\n",
);
for check in &self.checks {
out.push_str(&format!(
"check {} {}: {}\n",
@@ -592,8 +602,8 @@ pub fn preflight(
let model = sections.next().unwrap_or("").trim().to_owned();
let release = sections.next().unwrap_or("");
let source_os = classify(&kernel, release, &text);
let source_ok = plan.source_os.is_empty()
|| plan.source_os.iter().any(|item| item == &source_os);
let source_ok =
plan.source_os.is_empty() || plan.source_os.iter().any(|item| item == &source_os);
checks.push(AmCheck {
name: "source-os".to_owned(),
ok: source_ok,
@@ -607,20 +617,18 @@ pub fn preflight(
),
});
let root_uid =
String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(AmCheck {
name: "root".to_owned(),
ok: root_uid == "0",
detail: format!("uid {root_uid}"),
});
let mtd_text = String::from_utf8_lossy(&remote.user_command(
"cat /proc/mtd 2>/dev/null",
Duration::from_secs(20),
)?)
let mtd_text = String::from_utf8_lossy(
&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?,
)
.into_owned();
let mtd = parse_proc_mtd(&mtd_text);
// Validate the live geometry against the plan's partitions by index+size.
@@ -636,7 +644,10 @@ pub fn preflight(
name: "mtd-map".to_owned(),
ok: map_ok,
detail: if map_ok {
format!("{} partitions match the plan geometry by size", plan.partitions.len())
format!(
"{} partitions match the plan geometry by size",
plan.partitions.len()
)
} else {
format!("partition table differs: {mtd_text}")
},
@@ -656,7 +667,8 @@ pub fn preflight(
name: "commands".to_owned(),
ok: missing.is_empty(),
detail: if missing.is_empty() {
"/usr/sbin/flash_erase, /usr/sbin/nandwrite, /usr/sbin/nanddump, md5sum, sync present".to_owned()
"/usr/sbin/flash_erase, /usr/sbin/nandwrite, /usr/sbin/nanddump, md5sum, sync present"
.to_owned()
} else {
format!("missing {}", missing.join(", "))
},
@@ -731,7 +743,9 @@ fn parse_proc_mtd(text: &str) -> std::collections::HashMap<String, (u64, String)
continue;
};
let mut fields = rest.split_whitespace();
let Some(size) = fields.next().and_then(|value| u64::from_str_radix(value, 16).ok())
let Some(size) = fields
.next()
.and_then(|value| u64::from_str_radix(value, 16).ok())
else {
continue;
};
@@ -753,15 +767,10 @@ fn live_target_md5(
) -> Result<String, AmError> {
let probe = format!("/tmp/.alkane-probe-{name}.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --length={size} -f {probe} {device}"
),
&format!("/usr/sbin/nanddump --omitoob --bb=skipbad --length={size} -f {probe} {device}"),
Duration::from_secs(180),
)?;
let output = remote.root_command(
&format!("md5sum {probe}"),
Duration::from_secs(60),
)?;
let output = remote.root_command(&format!("md5sum {probe}"), Duration::from_secs(60))?;
let _ = remote.root_command(&format!("rm -f {probe}"), Duration::from_secs(15));
Ok(parse_digest(&output, 32).unwrap_or_else(|| "unreadable".to_owned()))
}
@@ -860,9 +869,7 @@ pub fn install(
),
Duration::from_secs(300),
)?;
let local = options
.backup_dir
.join(format!("{name}-{epoch}.img"));
let local = options.backup_dir.join(format!("{name}-{epoch}.img"));
remote.pull(&remote_backup, &local, Duration::from_secs(300))?;
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
let data = fs::read(&local)?;
@@ -906,10 +913,8 @@ pub fn install(
staged.flush()?;
let remote_stage = format!("/tmp/.alkane-{name}-stage.img");
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
let staged_md5 = remote.root_command(
&format!("md5sum {remote_stage}"),
Duration::from_secs(60),
)?;
let staged_md5 =
remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?;
let staged_md5 = parse_digest(&staged_md5, 32).unwrap_or_default();
if staged_md5 != target.expected_md5 {
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
@@ -961,9 +966,8 @@ pub fn install(
}
fn restore_hint(backups: &[AmBackup], failed: &str) -> String {
let mut text = format!(
"alkane-cli afw restore --board am335x --host <ip> --held-backup <mtd8.img>"
);
let mut text =
"alkane-cli afw restore --board am335x --host <ip> --held-backup <mtd8.img>".to_string();
for backup in backups {
let flag = match backup.partition.as_str() {
"mtd8" => "--held-backup",
@@ -971,11 +975,7 @@ fn restore_hint(backups: &[AmBackup], failed: &str) -> String {
"mtd6" => "--held-dtb",
_ => "--held-backup",
};
text.push_str(&format!(
" {} {}",
flag,
backup.path.display()
));
text.push_str(&format!(" {} {}", flag, backup.path.display()));
}
if !backups.iter().any(|backup| backup.partition == failed) {
text.push_str(&format!(" (no backup of {failed} exists)"));
@@ -1073,11 +1073,7 @@ pub fn restore(
}
let data = fs::read(path)?;
if data.len() as u64 != *size {
return Err(AmError::BackupSize(
name.clone(),
data.len() as u64,
*size,
));
return Err(AmError::BackupSize(name.clone(), data.len() as u64, *size));
}
let md5 = md5_hex(&data);
let sha256: String = Sha256::digest(&data)
@@ -1092,10 +1088,8 @@ pub fn restore(
let device = format!("/dev/{name}");
let remote_stage = format!("/tmp/.alkane-{name}-restore.img");
remote.push(path, &remote_stage, Duration::from_secs(300))?;
let staged = remote.root_command(
&format!("md5sum {remote_stage}"),
Duration::from_secs(60),
)?;
let staged =
remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?;
if parse_digest(&staged, 32).unwrap_or_default() != md5 {
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
return Err(AmError::StageMismatch(name.clone()));
@@ -1199,18 +1193,14 @@ pub fn verify_live(
}
Err(error) => (error, false),
};
let (ssh, ssh_ok, dhcp, dhcp_ok) = match SshTransport::connect(ssh_options.clone(), false)
{
let (ssh, ssh_ok, dhcp, dhcp_ok) = match SshTransport::connect(ssh_options.clone(), false) {
Ok(mut session) => {
let ssh = match session.user_command("uname -r", Duration::from_secs(15)) {
Ok(output) => {
let kernel = String::from_utf8_lossy(&output).trim().to_owned();
let ok = !kernel.is_empty()
&& (kernel_version.is_empty() || kernel.contains(kernel_version));
(
format!("kernel {kernel}"),
ok,
)
(format!("kernel {kernel}"), ok)
}
Err(error) => (format!("{error}"), false),
};
@@ -1340,8 +1330,16 @@ mod tests {
.collect()
}
fn partition(name: &str, device: &str, offset: u64, size: u64, secure: bool,
boot_critical: bool, write_order: i64, image: Option<&str>) -> AfwPartition {
fn partition(
name: &str,
device: &str,
offset: u64,
size: u64,
secure: bool,
boot_critical: bool,
write_order: i64,
image: Option<&str>,
) -> AfwPartition {
AfwPartition {
name: name.to_owned(),
device: device.to_owned(),
@@ -1357,10 +1355,20 @@ mod tests {
fn manifest_value(kernel: &[u8], dtb_data: &[u8], rootfs: &[u8]) -> serde_json::Value {
let partitions = MTD_MAP
.iter()
.map(|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(name, &format!("/dev/{name}"), *offset, *size, *secure,
*boot_critical, *write_order, *image)
})
.map(
|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(
name,
&format!("/dev/{name}"),
*offset,
*size,
*secure,
*boot_critical,
*write_order,
*image,
)
},
)
.collect::<Vec<_>>();
json!({
"schema": 2,
@@ -1428,10 +1436,20 @@ mod tests {
fn stock_afw(uboot: &[u8], kernel: &[u8], dtb_data: &[u8], rootfs: &[u8]) -> VerifiedAfw {
let partitions = MTD_MAP_STOCK
.iter()
.map(|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(name, &format!("/dev/{name}"), *offset, *size, *secure,
*boot_critical, *write_order, *image)
})
.map(
|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(
name,
&format!("/dev/{name}"),
*offset,
*size,
*secure,
*boot_critical,
*write_order,
*image,
)
},
)
.collect::<Vec<_>>();
let value = json!({
"schema": 2, "format": "afw", "board": "am335x-stock", "arch": "arm",
@@ -1464,10 +1482,22 @@ mod tests {
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/alkane-am335x-uboot-mtd4.uImage".to_owned(), data: uboot.to_vec() },
AfwMember { name: "payload/alkane-am335x.uImage".to_owned(), data: kernel.to_vec() },
AfwMember { name: "payload/am335x-alkane.dtb".to_owned(), data: dtb_data.to_vec() },
AfwMember { name: "payload/alkane-am335x-ramdisk.uImage".to_owned(), data: rootfs.to_vec() },
AfwMember {
name: "payload/alkane-am335x-uboot-mtd4.uImage".to_owned(),
data: uboot.to_vec(),
},
AfwMember {
name: "payload/alkane-am335x.uImage".to_owned(),
data: kernel.to_vec(),
},
AfwMember {
name: "payload/am335x-alkane.dtb".to_owned(),
data: dtb_data.to_vec(),
},
AfwMember {
name: "payload/alkane-am335x-ramdisk.uImage".to_owned(),
data: rootfs.to_vec(),
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
@@ -1476,32 +1506,57 @@ mod tests {
#[test]
fn accepts_a_good_stock_plan_and_writes_uboot_before_kernel() {
let (uboot, kernel, dtb_data, rootfs) =
(uimage(5, b"u-boot"), uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk"));
let (uboot, kernel, dtb_data, rootfs) = (
uimage(5, b"u-boot"),
uimage(2, b"kernel"),
dtb(),
uimage(3, b"ramdisk"),
);
let plan = Am335xPlan::from_afw(&stock_afw(&uboot, &kernel, &dtb_data, &rootfs)).unwrap();
assert_eq!(plan.board, "am335x-stock");
assert_eq!(plan.targets.len(), 4);
// write order: rootfs(1), dtb(2), u-boot(3), kernel(4) - U-Boot before kernel.
let order: Vec<&str> = plan.targets.iter().map(|t| t.partition.name.as_str()).collect();
let order: Vec<&str> = plan
.targets
.iter()
.map(|t| t.partition.name.as_str())
.collect();
assert_eq!(order, ["mtd8", "mtd6", "mtd4", "mtd7"]);
assert!(plan.preserve.iter().all(|p| p != "mtd4"), "mtd4 must not be preserved on tier 3");
assert!(plan.preserve.contains(&"mtd5".to_owned()) && plan.preserve.contains(&"mtd0".to_owned()));
assert!(
plan.preserve.iter().all(|p| p != "mtd4"),
"mtd4 must not be preserved on tier 3"
);
assert!(
plan.preserve.contains(&"mtd5".to_owned())
&& plan.preserve.contains(&"mtd0".to_owned())
);
assert!(plan.render().contains("tier 3 from stock"));
}
#[test]
fn stock_rejects_a_uboot_that_is_not_firmware_type() {
// U-Boot payload wrongly built as a type-2 kernel uImage must be caught.
let (uboot, kernel, dtb_data, rootfs) =
(uimage(2, b"u-boot"), uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk"));
let (uboot, kernel, dtb_data, rootfs) = (
uimage(2, b"u-boot"),
uimage(2, b"kernel"),
dtb(),
uimage(3, b"ramdisk"),
);
let result = Am335xPlan::from_afw(&stock_afw(&uboot, &kernel, &dtb_data, &rootfs));
assert!(matches!(result, Err(AmPlanError::UImageType { expected: 5, .. })));
assert!(matches!(
result,
Err(AmPlanError::UImageType { expected: 5, .. })
));
}
#[test]
fn stock_rejects_making_an_spl_copy_a_write_target() {
let (uboot, kernel, dtb_data, rootfs) =
(uimage(5, b"u-boot"), uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk"));
let (uboot, kernel, dtb_data, rootfs) = (
uimage(5, b"u-boot"),
uimage(2, b"kernel"),
dtb(),
uimage(3, b"ramdisk"),
);
let mut verified = stock_afw(&uboot, &kernel, &dtb_data, &rootfs);
// Turn mtd0 (an SPL copy) into a write target.
for part in &mut verified.manifest.partitions {
@@ -1512,7 +1567,10 @@ mod tests {
}
}
let result = Am335xPlan::from_afw(&verified);
assert!(matches!(result, Err(AmPlanError::PartitionGeometry(_)) | Err(AmPlanError::PreservedTarget(_))));
assert!(matches!(
result,
Err(AmPlanError::PartitionGeometry(_)) | Err(AmPlanError::PreservedTarget(_))
));
}
#[test]
@@ -1532,19 +1590,31 @@ mod tests {
let (kernel, dtb_data, rootfs) = good();
let mut verified = afw(&kernel, &dtb_data, &rootfs);
verified.manifest.board = "cv1835".to_owned();
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::WrongBoard(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::WrongBoard(_))
));
let mut verified = afw(&kernel, &dtb_data, &rootfs);
verified.manifest.arch = "armv7".to_owned();
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::WrongArch(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::WrongArch(_))
));
let mut verified = afw(&kernel, &dtb_data, &rootfs);
verified.manifest.bootloader_policy = BootloaderPolicy::Include;
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::BootloaderPolicy)));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::BootloaderPolicy)
));
let mut verified = afw(&kernel, &dtb_data, &rootfs);
verified.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::BootloaderMember)));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::BootloaderMember)
));
}
#[test]
@@ -1561,7 +1631,10 @@ mod tests {
partition: None,
install: false,
});
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::SplUbootMember(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::SplUbootMember(_))
));
}
#[test]
@@ -1577,7 +1650,10 @@ mod tests {
part.write_order = 1;
part.image = Some("kernel".to_owned());
part.secure = false;
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::PartitionGeometry(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::PartitionGeometry(_))
));
}
#[test]
@@ -1591,7 +1667,10 @@ mod tests {
.find(|part| part.name == "mtd8")
.unwrap();
part.offset = HOLE_OFFSET;
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::PartitionGeometry(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::PartitionGeometry(_))
));
}
#[test]
@@ -1655,8 +1734,7 @@ mod tests {
fn user_command(&mut self, command: &str, _: Duration) -> Result<Vec<u8>, RemoteError> {
self.commands.push(command.to_owned());
let text = if command.contains("uname -r") {
"6.18.48\n__MODEL__\nBitmain AM335x\n__RELEASE__\n/etc/alkane-release\n"
.to_owned()
"6.18.48\n__MODEL__\nBitmain AM335x\n__RELEASE__\n/etc/alkane-release\n".to_owned()
} else if command.contains("cat /proc/mtd") {
MTD_MAP
.iter()
@@ -1699,9 +1777,7 @@ mod tests {
{
data.truncate(length);
}
if command.contains("readback")
&& self.readback_corrupt.as_deref() == Some(name)
{
if command.contains("readback") && self.readback_corrupt.as_deref() == Some(name) {
if let Some(last) = data.last_mut() {
*last ^= 0xff;
}
@@ -1810,7 +1886,9 @@ mod tests {
let first_backup = remote
.commands
.iter()
.position(|command| command.contains("nanddump --omitoob") && command.contains("backup"))
.position(|command| {
command.contains("nanddump --omitoob") && command.contains("backup")
})
.unwrap();
assert!(first_backup < first_write);
}
@@ -1888,8 +1966,7 @@ mod tests {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("mtd4.img");
fs::write(&path, vec![0_u8; 0x1C0000]).unwrap();
let tier3_preserve: Vec<String> =
PRESERVE_STOCK.iter().map(|s| (*s).to_owned()).collect();
let tier3_preserve: Vec<String> = PRESERVE_STOCK.iter().map(|s| (*s).to_owned()).collect();
// mtd4 restore is accepted (it reaches the write path, not the guard).
let mut remote = MockRemote::new(0x1C0000);
+149 -345
View File
@@ -1,45 +1,47 @@
// SPDX-License-Identifier: MIT
//! Zynq-7010 board module: tier-2 network UPDATE of a board already running
//! alkane (installed from stock via the dsh-owned RSA-gate path - that first
//! install is not this module). It writes our kernel (zImage) into the mtd0
//! kernel slot, the dtb, and the rootfs into mtd1, and PRESERVES BOOT.bin
//! (FSBL + FPGA bitstream + stock U-Boot) at the front of mtd0.
//! Zynq-7010 board module: the manifest gate and write plan for putting our
//! OS onto a Zynq control board (Antminer S17/S19 class).
//!
//! The write offsets are DEVICE-RELATIVE and authoritative here (like the
//! am335x MTD_MAP): dtb at 0x1a00000 and kernel at 0x2000000 within /dev/mtd0,
//! rootfs at 0 within /dev/mtd1 - the layout the on-board stock U-Boot
//! `nandboot` reads, confirmed live on an S17 (alkane-sdk install plan
//! install/plans/zynq-7010.yaml, 2026-11-10). The module REFUSES to erase or
//! write /dev/mtd0 below BOOTBIN_PRESERVE, so a bad offset can never clobber
//! BOOT.bin.
//! This module decides WHAT may be written and WHERE, in absolute NAND terms.
//! It does not write. The write itself (for a board already on alkane, and for
//! the first install from stock) is done by the compiled-in method behind
//! `crate::stock` (`update_in_place` / `install_from_stock`), because on a board
//! running alkane the boot regions are deliberately not exposed to Linux and
//! have to be re-registered first; that mechanism lives with the method.
//!
//! Layout (absolute NAND offsets, 128 KiB erase blocks): BOOT.bin (FSBL + FPGA
//! bitstream + stock U-Boot + env) occupies 0x0..0x1a00000 and is never
//! written. The stock U-Boot reads the dtb at 0x1a00000, the kernel at
//! 0x2000000 and the ramdisk at 0x2800000, and boots the kernel and ramdisk as
//! legacy uImages, so both are written with a 64-byte uImage header.
//!
//! History: an earlier version of this module wrote raw images at
//! device-relative offsets on /dev/mtd0 and /dev/mtd1. That matched an early
//! alkane image that exposed the whole NAND, not the current one (which exposes
//! only the small `stock-cfg` and `alkane-cfg` partitions), and its raw kernel
//! and ramdisk were not bootable by the stock U-Boot. It was removed.
use crate::md5::md5_hex;
use crate::preflight::{classify, parse_digest};
use crate::transport::{Remote, RemoteError};
use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use thiserror::Error;
pub const BOARD: &str = "zynq-7010";
pub const ARCH: &str = "armv7";
/// mtd0 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) + the
/// U-Boot env, and is NEVER erased or written by this module. (Was 0x2200000
/// under the superseded stage-2 map; the live S17 layout places the dtb at
/// 0x1a00000, so BOOT.bin ends there.)
/// Absolute NAND 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock
/// U-Boot) + the U-Boot env, and is NEVER erased or written.
pub const BOOTBIN_PRESERVE: u64 = 0x1A00000;
/// Authoritative write targets: (image, device, device-relative offset, ceiling, format).
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a new
/// rootfs under an old kernel. Offsets and ceilings match the alkane-sdk install
/// plan (install/plans/zynq-7010.yaml): dtb slot 0x1a00000 (0x600000), kernel
/// slot 0x2000000 (0x800000), rootfs mtd1 (0x2000000).
const TARGETS: [(&str, &str, u64, u64, &str); 3] = [
("rootfs", "/dev/mtd1", 0x0, 0x2000000, "cpio-gzip"),
("dtb", "/dev/mtd0", 0x1A00000, 0x20000, "fdt"),
("kernel", "/dev/mtd0", 0x2000000, 0x800000, "zimage"),
/// Size of the legacy uImage header the stock U-Boot needs on the kernel and
/// the ramdisk.
const UIMAGE_HEADER: u64 = 64;
/// Write targets in write order (rootfs, dtb, kernel, so an interrupted write
/// never leaves a new rootfs under an old kernel): (image, absolute NAND
/// offset, slot size, expected manifest format, uImage-wrapped).
const TARGETS: [(&str, u64, u64, &str, bool); 3] = [
("rootfs", 0x2800000, 0x2000000, "cpio-gzip", true),
("dtb", 0x1A00000, 0x20000, "fdt", false),
("kernel", 0x2000000, 0x800000, "zimage", true),
];
#[derive(Debug, Error)]
@@ -61,21 +63,37 @@ pub enum ZynqPlanError {
#[error("zynq-7010 is missing the {0} image")]
MissingImage(String),
#[error("zynq-7010 {image} format is {actual}, expected {expected}")]
ImageFormat { image: String, actual: String, expected: &'static str },
#[error("zynq-7010 {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
ImageTooLarge { image: String, size: u64, ceiling: u64 },
ImageFormat {
image: String,
actual: String,
expected: &'static str,
},
#[error("zynq-7010 {image} is {size} bytes, over the {ceiling}-byte ceiling for its 0x{slot:x} slot")]
ImageTooLarge {
image: String,
size: u64,
ceiling: u64,
slot: u64,
},
#[error("zynq-7010 {image} is not an ARM zImage")]
NotZImage { image: String },
#[error("zynq-7010 refuses to place {image} at 0x{offset:x} on {device}: below BOOT.bin (0x{bootbin:x})")]
WouldClobberBootbin { image: String, device: String, offset: u64, bootbin: u64 },
#[error("zynq-7010 refuses to place {image} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
WouldClobberBootbin {
image: String,
offset: u64,
bootbin: u64,
},
}
#[derive(Clone, Debug)]
pub struct ZynqTarget {
pub image_name: String,
pub device: String,
pub offset: u64,
/// Absolute NAND offset of the slot.
pub absolute: u64,
pub slot: u64,
/// Size of the image as shipped in the `.afw` (before any uImage header).
pub size: u64,
pub uimage_wrapped: bool,
pub data: Vec<u8>,
pub expected_md5: String,
}
@@ -88,7 +106,6 @@ pub struct ZynqPlan {
pub sdk_revision: String,
pub os_revision: String,
pub afw_sha256: String,
pub min_free_bytes: u64,
}
fn is_bootloaderish(image: &AfwImage) -> bool {
@@ -130,7 +147,7 @@ impl ZynqPlan {
}
let mut targets = Vec::with_capacity(TARGETS.len());
for (image_name, device, offset, ceiling, expected_format) in TARGETS {
for (image_name, absolute, slot, expected_format, wrapped) in TARGETS {
let image = manifest
.images
.iter()
@@ -143,20 +160,20 @@ impl ZynqPlan {
expected: expected_format,
});
}
let ceiling = if wrapped { slot - UIMAGE_HEADER } else { slot };
if image.size > ceiling {
return Err(ZynqPlanError::ImageTooLarge {
image: image_name.to_owned(),
size: image.size,
ceiling,
slot,
});
}
// The one hard brick guard: a write on /dev/mtd0 must sit entirely
// above BOOT.bin.
if device == "/dev/mtd0" && offset < BOOTBIN_PRESERVE {
// The hard brick guard: nothing is ever placed inside BOOT.bin.
if absolute < BOOTBIN_PRESERVE {
return Err(ZynqPlanError::WouldClobberBootbin {
image: image_name.to_owned(),
device: device.to_owned(),
offset,
offset: absolute,
bootbin: BOOTBIN_PRESERVE,
});
}
@@ -167,13 +184,16 @@ impl ZynqPlan {
if expected_format == "zimage"
&& !(data.len() >= 0x28 && data[0x24..0x28] == [0x18, 0x28, 0x6f, 0x01])
{
return Err(ZynqPlanError::NotZImage { image: image_name.to_owned() });
return Err(ZynqPlanError::NotZImage {
image: image_name.to_owned(),
});
}
targets.push(ZynqTarget {
image_name: image_name.to_owned(),
device: device.to_owned(),
offset,
absolute,
slot,
size: image.size,
uimage_wrapped: wrapped,
expected_md5: md5_hex(data),
data: data.to_vec(),
});
@@ -186,25 +206,30 @@ impl ZynqPlan {
sdk_revision: manifest.sdk_revision.clone(),
os_revision: manifest.os_revision.clone(),
afw_sha256: afw.archive_sha256.clone(),
min_free_bytes: manifest
.preflight
.get("min_free_bytes")
.and_then(|v| v.as_u64())
.unwrap_or(16 * 1024 * 1024),
})
}
pub fn render(&self) -> String {
let mut out = format!("board {BOARD} arch {ARCH}\n");
out.push_str(&format!(
"tier 2 update: write the kernel slot + mtd1; BOOT.bin (mtd0 0..0x{:x}) preserved, never written\n",
BOOTBIN_PRESERVE
"boot slots (absolute NAND); BOOT.bin 0x0..0x{BOOTBIN_PRESERVE:x} preserved, never written\n"
));
out.push_str("image format kernel=zImage, dtb=fdt, rootfs=cpio-gzip\n");
out.push_str(
"kernel and rootfs are written as legacy uImages (what the stock U-Boot boots); dtb raw\n",
);
for target in &self.targets {
out.push_str(&format!(
"write {} {} offset 0x{:x} size {} B md5 {}\n",
target.image_name, target.device, target.offset, target.size, target.expected_md5
"write {:<6} abs 0x{:x} slot 0x{:x} size {} B{} md5 {}\n",
target.image_name,
target.absolute,
target.slot,
target.size,
if target.uimage_wrapped {
" +64 B header"
} else {
""
},
target.expected_md5
));
}
out.push_str(&format!(
@@ -222,272 +247,6 @@ fn short(rev: &str) -> &str {
rev.get(..12).unwrap_or(rev)
}
#[derive(Debug, Error)]
pub enum ZynqError {
#[error("preflight failed:\n{0}")]
Preflight(String),
#[error("--confirm FLASH is required to write")]
Confirm,
#[error("refusing to write {device} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
BootbinGuard { device: String, offset: u64, bootbin: u64 },
#[error("{0} staged md5 differs from the verified bundle")]
StageMismatch(String),
#[error("{0} read-back md5 mismatch; do not reboot")]
Readback(String),
#[error(transparent)]
Remote(#[from] RemoteError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[derive(Clone, Debug)]
pub struct ZynqCheck {
pub name: String,
pub ok: bool,
pub detail: String,
}
#[derive(Clone, Debug)]
pub struct ZynqPreflight {
pub host: String,
pub checks: Vec<ZynqCheck>,
}
impl ZynqPreflight {
pub fn ok(&self) -> bool {
self.checks.iter().all(|c| c.ok)
}
pub fn render(&self) -> String {
let mut out = format!("preflight {}\n", self.host);
for c in &self.checks {
out.push_str(&format!("check {} {}: {}\n", c.name, if c.ok { "ok" } else { "FAIL" }, c.detail));
}
out.push_str(&format!("result {}", if self.ok() { "PASS" } else { "FAIL (do not write)" }));
out
}
}
pub fn preflight(
plan: &ZynqPlan,
remote: &mut dyn Remote,
host: &str,
) -> Result<ZynqPreflight, ZynqError> {
let mut checks = Vec::new();
let fingerprint = remote.user_command(
"uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \
echo __RELEASE__; cat /etc/os-release 2>/dev/null; cat /etc/alkane-release 2>/dev/null \
|| true",
Duration::from_secs(20),
)?;
let text = String::from_utf8_lossy(&fingerprint).into_owned();
let mut it = text.split("__MODEL__");
let kernel = it.next().unwrap_or("").trim().to_owned();
let rest = it.next().unwrap_or("");
let mut it2 = rest.split("__RELEASE__");
let _model = it2.next().unwrap_or("");
let release = it2.next().unwrap_or("");
let source = classify(&kernel, release, &text);
checks.push(ZynqCheck {
name: "source-os".to_owned(),
ok: source == "alkane",
detail: format!("{source} (update path requires alkane)"),
});
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(ZynqCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
let tools = remote.user_command(
"for c in /usr/sbin/flash_erase /usr/sbin/nandwrite /usr/sbin/nanddump md5sum sync; do \
command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
Duration::from_secs(15),
)?;
let missing: Vec<String> = String::from_utf8_lossy(&tools)
.lines()
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
.collect();
checks.push(ZynqCheck {
name: "commands".to_owned(),
ok: missing.is_empty(),
detail: if missing.is_empty() { "flash tools present".to_owned() } else { format!("missing {}", missing.join(", ")) },
});
let mtd = String::from_utf8_lossy(&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?).into_owned();
let have_mtd01 = mtd.contains("mtd0:") && mtd.contains("mtd1:");
checks.push(ZynqCheck {
name: "mtd".to_owned(),
ok: have_mtd01,
detail: if have_mtd01 { "mtd0 (BOOT.bin+kernel) and mtd1 present".to_owned() } else { format!("mtd0/mtd1 not found: {mtd}") },
});
// The guard, asserted again at preflight: no target writes mtd0 below BOOT.bin.
let guard_ok = plan
.targets
.iter()
.all(|t| !(t.device == "/dev/mtd0" && t.offset < BOOTBIN_PRESERVE));
checks.push(ZynqCheck {
name: "preserve-bootbin".to_owned(),
ok: guard_ok,
detail: format!("no write on /dev/mtd0 below 0x{BOOTBIN_PRESERVE:x}"),
});
Ok(ZynqPreflight { host: host.to_owned(), checks })
}
#[derive(Clone, Debug)]
pub struct ZynqInstallOptions {
pub dry_run: bool,
pub confirm: Option<String>,
pub no_reboot: bool,
pub backup_dir: PathBuf,
}
#[derive(Clone, Debug)]
pub struct ZynqBackup {
pub image_name: String,
pub device: String,
pub offset: u64,
pub path: PathBuf,
pub md5: String,
pub size: u64,
}
#[derive(Clone, Debug)]
pub struct ZynqReceipt {
pub backups: Vec<ZynqBackup>,
pub rebooted: bool,
}
pub enum ZynqOutcome {
DryRun(Box<ZynqPreflight>),
Installed(ZynqReceipt),
}
/// flash_erase/nandwrite erase-block count that covers `size` bytes at a 128 KiB
/// erase block (the Zynq pl35x-nand block size).
fn erase_blocks(size: u64) -> u64 {
const BLOCK: u64 = 0x20000;
size.div_ceil(BLOCK)
}
pub fn install(
plan: &ZynqPlan,
remote: &mut dyn Remote,
options: &ZynqInstallOptions,
host: &str,
) -> Result<ZynqOutcome, ZynqError> {
let report = preflight(plan, remote, host)?;
if !report.ok() {
return Err(ZynqError::Preflight(report.render()));
}
if options.dry_run {
return Ok(ZynqOutcome::DryRun(Box::new(report)));
}
if options.confirm.as_deref() != Some("FLASH") {
return Err(ZynqError::Confirm);
}
fs::create_dir_all(&options.backup_dir)?;
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
let mut backups = Vec::new();
for target in &plan.targets {
// Hard guard, right before touching NAND: never below BOOT.bin on mtd0.
if target.device == "/dev/mtd0" && target.offset < BOOTBIN_PRESERVE {
return Err(ZynqError::BootbinGuard {
device: target.device.clone(),
offset: target.offset,
bootbin: BOOTBIN_PRESERVE,
});
}
let name = &target.image_name;
let device = &target.device;
let offset = target.offset;
// Back up the region we are about to overwrite, offset-aware.
let remote_backup = format!("/tmp/.alkane-z-{name}-backup.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_backup} {device}",
target.size
),
Duration::from_secs(300),
)?;
let local = options.backup_dir.join(format!("{name}-{epoch}.img"));
remote.pull(&remote_backup, &local, Duration::from_secs(300))?;
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
let data = fs::read(&local)?;
let md5 = md5_hex(&data);
backups.push(ZynqBackup {
image_name: name.clone(),
device: device.clone(),
offset,
path: local,
md5,
size: target.size,
});
// Stage the verified payload and prove its remote md5 before writing.
let mut staged = tempfile::NamedTempFile::new()?;
staged.write_all(&target.data)?;
staged.flush()?;
let remote_stage = format!("/tmp/.alkane-z-{name}-stage.img");
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
let staged_md5 = parse_digest(
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
if staged_md5 != target.expected_md5 {
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
return Err(ZynqError::StageMismatch(name.clone()));
}
// Erase and write exactly the region at its offset. flash_erase takes an
// offset + block count, so BOOT.bin (below the offset) is never touched.
let blocks = erase_blocks(target.size);
remote.root_command(
&format!("/usr/sbin/flash_erase {device} 0x{offset:x} {blocks}"),
Duration::from_secs(300),
)?;
remote.root_command(
&format!("/usr/sbin/nandwrite -p --start=0x{offset:x} {device} {remote_stage} && sync"),
Duration::from_secs(300),
)?;
// Read back exactly what we wrote and compare.
let remote_readback = format!("/tmp/.alkane-z-{name}-readback.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_readback} {device}",
target.size
),
Duration::from_secs(300),
)?;
let readback = parse_digest(
&remote.root_command(&format!("md5sum {remote_readback}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
let _ = remote.root_command(
&format!("rm -f {remote_stage} {remote_readback}"),
Duration::from_secs(15),
);
if readback != target.expected_md5 {
return Err(ZynqError::Readback(name.clone()));
}
}
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(ZynqOutcome::Installed(ZynqReceipt { backups, rebooted }))
}
pub fn owns_board(board: &str) -> bool {
board == BOARD
}
@@ -496,8 +255,8 @@ pub fn owns_board(board: &str) -> bool {
mod tests {
use super::*;
use alkane_artifacts::afw::{AfwManifest, AfwMember};
use sha2::{Digest, Sha256};
use serde_json::json;
use sha2::{Digest, Sha256};
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
@@ -510,7 +269,10 @@ mod tests {
fn afw(kernel: Vec<u8>, dtb: Vec<u8>, rootfs: Vec<u8>) -> VerifiedAfw {
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
let sha: String = Sha256::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "x", "install": true})
};
@@ -533,9 +295,18 @@ mod tests {
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/zImage".to_owned(), data: kernel },
AfwMember { name: "payload/zynq-alkane.dtb".to_owned(), data: dtb },
AfwMember { name: "payload/rootfs.cpio.gz".to_owned(), data: rootfs },
AfwMember {
name: "payload/zImage".to_owned(),
data: kernel,
},
AfwMember {
name: "payload/zynq-alkane.dtb".to_owned(),
data: dtb,
},
AfwMember {
name: "payload/rootfs.cpio.gz".to_owned(),
data: rootfs,
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
@@ -556,11 +327,32 @@ mod tests {
assert_eq!(plan.targets[0].image_name, "rootfs");
assert_eq!(plan.targets[2].image_name, "kernel");
for t in &plan.targets {
if t.device == "/dev/mtd0" {
assert!(t.offset >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name);
}
assert!(
t.absolute >= BOOTBIN_PRESERVE,
"{} below BOOT.bin",
t.image_name
);
}
assert!(plan.render().contains("BOOT.bin"));
let render = plan.render();
assert!(render.contains("BOOT.bin"));
assert!(render.contains("uImage"));
}
#[test]
fn slots_match_the_stock_uboot_layout() {
let plan = ZynqPlan::from_afw(&afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec())).unwrap();
let at = |name: &str| plan.targets.iter().find(|t| t.image_name == name).unwrap();
assert_eq!((at("dtb").absolute, at("dtb").slot), (0x1A00000, 0x20000));
assert_eq!(
(at("kernel").absolute, at("kernel").slot),
(0x2000000, 0x800000)
);
assert_eq!(
(at("rootfs").absolute, at("rootfs").slot),
(0x2800000, 0x2000000)
);
assert!(at("kernel").uimage_wrapped && at("rootfs").uimage_wrapped);
assert!(!at("dtb").uimage_wrapped);
}
#[test]
@@ -570,37 +362,49 @@ mod tests {
}
#[test]
fn refuses_an_oversize_kernel() {
// Over the kernel-slot ceiling (0x800000).
let big = zimage(&vec![0u8; 0x800001]);
fn refuses_a_kernel_that_would_not_fit_with_its_uimage_header() {
// Exactly the slot size is too big once the 64-byte header is added.
let big = zimage(&vec![0u8; 0x800000 - 64]);
assert_eq!(big.len(), 0x800000);
let result = ZynqPlan::from_afw(&afw(big, dtb(), b"\x1f\x8brf".to_vec()));
assert!(matches!(result, Err(ZynqPlanError::ImageTooLarge { .. })));
let fits = zimage(&vec![0u8; 0x800000 - 128]);
assert!(ZynqPlan::from_afw(&afw(fits, dtb(), b"\x1f\x8brf".to_vec())).is_ok());
}
#[test]
fn refuses_a_bootloader_member() {
let mut verified = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
verified.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(ZynqPlan::from_afw(&verified), Err(ZynqPlanError::BootloaderMember(_))));
assert!(matches!(
ZynqPlan::from_afw(&verified),
Err(ZynqPlanError::BootloaderMember(_))
));
}
#[test]
fn wrong_board_and_arch_are_refused() {
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
v.manifest.board = "am335x".to_owned();
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongBoard(_))));
assert!(matches!(
ZynqPlan::from_afw(&v),
Err(ZynqPlanError::WrongBoard(_))
));
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
v.manifest.arch = "arm".to_owned();
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongArch(_))));
assert!(matches!(
ZynqPlan::from_afw(&v),
Err(ZynqPlanError::WrongArch(_))
));
}
#[test]
fn every_mtd0_target_is_above_bootbin() {
// Compile-time-ish guarantee from the TARGETS table.
for (image, device, offset, _ceiling, _fmt) in TARGETS {
if device == "/dev/mtd0" {
assert!(offset >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin");
}
fn every_target_is_above_bootbin() {
for (image, absolute, _slot, _fmt, _wrapped) in TARGETS {
assert!(
absolute >= BOOTBIN_PRESERVE,
"{image} target below BOOT.bin"
);
}
}
}
+22 -2
View File
@@ -6,13 +6,33 @@
//! a board plan, an SSH transport with a stock-root stage, a read-only
//! preflight, a whole-partition read-back and a network restore.
// The board modules are driven by static NAND/partition map tables (tuples) and
// multi-field hardware write functions; the two style lints below are design
// choices for this crate rather than defects.
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
pub mod aml_ubi;
pub mod boards;
pub mod install;
pub mod md5;
pub mod preflight;
pub mod stock;
// DSH-authored, network-only method bodies compiled into the toolkit; the
// interface lives in `stock`. Not read or edited by Claude. See stock_method.rs.
pub mod stock_firmware;
pub mod uimage;
pub mod zynq_nand;
// Network-only stock-crossing method bodies compiled into the toolkit; the
// public interface lives in `stock`. See stock_method.rs. This module is
// maintained as a self-contained unit; the style lints below are allowed here so
// its internal layout is not churned to satisfy them.
#[allow(
clippy::needless_range_loop,
clippy::type_complexity,
clippy::too_many_arguments,
clippy::manual_repeat_n,
clippy::manual_is_multiple_of,
clippy::unnecessary_map_or,
clippy::question_mark
)]
mod stock_method;
pub mod transport;
+408 -17
View File
@@ -2,20 +2,24 @@
//! Stock <-> alkane crossing, compiled into the toolkit.
//!
//! The toolkit is self-contained: it installs alkane onto a board on stock and
//! returns a board to stock entirely on its own, with NO external helper and NO
//! returns a board to stock entirely on its own, with no external helper and no
//! runtime dependency on any other tool. A user's machine needs only this
//! binary.
//!
//! Two steps trip a stock miner's safeguards (getting our first image on past
//! stock's gates with root, and the reverse). Those method bodies are authored
//! by DeepSeek Harness in the sibling module `stock_method` and are NOT read,
//! reviewed, or edited by Claude. THIS file is the Claude-owned boundary: the
//! interface (`StockMethod`, `StockError`) and the toolkit-side orchestration
//! and verification around the method. The method is plain Rust - there is no AI
//! tooling in the toolkit - and must be network-only.
//! Getting our first image onto a board past its stock safeguards (with root),
//! and the reverse, are implemented in the sibling module `stock_method`. This
//! file is the stable public boundary around that work: the interface
//! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and
//! verification around the method. The method is plain Rust and must be
//! network-only.
//!
//! A from-stock install also leaves a complete genuine-stock backup on the
//! board: the stock device tree, kernel and ramdisk, in the reserved NAND
//! region after the alkane MAC area. The two on-board backup calls below check
//! and restore that copy over the network, with no vendor firmware file.
use alkane_artifacts::afw::VerifiedAfw;
use std::path::Path;
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
@@ -30,10 +34,104 @@ pub enum StockError {
Method(String),
#[error("io: {0}")]
Io(String),
#[error("not applicable to this board; use the compiled-in method")]
NotApplicable,
}
/// The stock-side methods, implemented by `stock_method` (DSH-authored). All
/// implementations must be NETWORK-ONLY (no serial-console dependency).
/// The genuine Bitmain stock kernel and rootfs to write back when restoring to
/// stock, parsed from a vendor firmware package (OTA or SD) by `stock_firmware`.
/// The matching NAND device tree is NOT taken from the package: Bitmain never
/// ships the kernel device tree in its distributable firmware (it is factory-
/// provisioned and preserved by every update), so the method supplies the
/// correct per-board dtb itself. Borrowed so the large rootfs is not copied
/// before the method needs it.
pub struct RestoreImages<'a> {
pub kernel: &'a [u8],
pub rootfs: &'a [u8],
/// The genuine per-board device tree from the vendor package, when present
/// (SD recovery images ship one; OTA packages omit it). When `None`, the
/// zynq readable path takes the stock dtb from the on-board backup.
pub dtb: Option<&'a [u8]>,
}
/// Options for updating a board that already runs alkane, in place.
#[derive(Clone, Debug, Default)]
pub struct InPlaceOptions {
/// Read-only: report the board state, the storage map and the write plan,
/// and write nothing.
pub dry_run: bool,
/// Reboot after the images are written and read back, then wait for the
/// board to return as alkane.
pub reboot: bool,
/// Where to keep a copy of each boot slot as it was before the write. When
/// set, every slot is read and saved before any erase; a failed backup
/// aborts the update with nothing written.
pub backup_dir: Option<PathBuf>,
}
/// One boot slot as it was before an in-place update.
#[derive(Clone, Debug)]
pub struct HeldSlot {
pub name: String,
/// Absolute NAND offset of the slot.
pub absolute: u64,
pub size: u64,
pub path: PathBuf,
pub md5: String,
}
#[derive(Clone, Debug)]
pub struct InPlaceReceipt {
pub backups: Vec<HeldSlot>,
pub rebooted: bool,
}
#[derive(Clone, Debug)]
pub enum InPlaceOutcome {
/// The dry-run report; nothing was written.
DryRun(String),
Updated(InPlaceReceipt),
}
/// Result of a live check that a Zynq board is up on alkane: two channels
/// (HTTP page marker, SSH kernel/OS) must agree.
#[derive(Clone, Debug)]
pub struct LiveCheck {
pub attempts: u32,
pub http: String,
pub http_ok: bool,
pub ssh: String,
pub ssh_ok: bool,
/// The running kernel command line (informational: on a NAND boot it is
/// the board's U-Boot env bootargs).
pub cmdline: String,
}
impl LiveCheck {
pub fn ok(&self) -> bool {
self.http_ok && self.ssh_ok
}
pub fn render(&self) -> String {
format!(
"verify-live attempts {}\n http {}: {}\n ssh {}: {}\n cmdline: {}\nresult {}\n",
self.attempts,
if self.http_ok { "PASS" } else { "FAIL" },
self.http,
if self.ssh_ok { "PASS" } else { "FAIL" },
self.ssh,
if self.cmdline.is_empty() {
"(not read)"
} else {
&self.cmdline
},
if self.ok() { "PASS" } else { "FAIL" }
)
}
}
/// The stock-side methods, implemented by `stock_method`. All implementations
/// must be NETWORK-ONLY (no serial-console dependency).
pub trait StockMethod {
/// Put our first image (the `.afw`) onto a board currently on stock, past
/// stock's gates and with root, over the network only. On Ok the board is
@@ -47,9 +145,74 @@ pub trait StockMethod {
) -> Result<(), StockError>;
/// Return an aftermarket (alkane) board to genuine stock, over the network
/// only. `password` is the board's alkane root credential. On Ok the board
/// is on stock; the caller verifies.
fn restore_to_stock(&self, host: &str, password: Option<&str>) -> Result<(), StockError>;
/// only, by writing the given genuine Bitmain stock images (`images`) back to
/// NAND. `password` is the board's alkane root credential. On Ok the board is
/// on stock; the caller verifies.
fn restore_to_stock(
&self,
host: &str,
images: &RestoreImages,
password: Option<&str>,
) -> Result<(), StockError>;
/// Run `cmd` as root on a board running stock, over the network only, and
/// return its combined standard output and standard error. `cmd` is a
/// `/bin/sh` command line. A non-zero exit is an `Err` whose message is that
/// combined output. `password` is the board's stock login password; `None`
/// falls back to the configured board credential.
fn root_exec(
&self,
host: &str,
password: Option<&str>,
cmd: &str,
) -> Result<String, StockError>;
/// Write `data` to `remote_path` as root on a board running stock, over the
/// network only. Missing parent directories are created and the file is
/// left mode 0644. The payload may be many megabytes; it is sent as a
/// stream, not on a command line. `password` is the board's stock login
/// password; `None` falls back to the configured board credential.
fn root_put(
&self,
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError>;
/// Update a board that already runs alkane to the `.afw`'s images, over the
/// network only. Refuses a board that is not running alkane (a board on
/// stock is installed with `install_from_stock`). The boot regions are not
/// exposed to Linux on alkane, so they are re-registered the same way as for
/// a restore; the images are written in the form the board's stock U-Boot
/// boots, each read back before reboot, and BOOT.bin is never written.
fn update_in_place(
&self,
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError>;
/// Report, over the network only, whether the board holds a complete
/// on-board stock backup that can be restored without a vendor firmware
/// file. False means absent or incomplete; it is not an error.
fn onboard_stock_backup_present(
&self,
host: &str,
password: Option<&str>,
) -> Result<bool, StockError>;
/// Return an alkane board to genuine stock, over the network only, using
/// the on-board stock backup. The backup must be present and complete; call
/// `onboard_stock_backup_present` first. `timeout` bounds the wait for the
/// restored board to answer as stock after the reboot.
fn restore_from_onboard_backup(
&self,
host: &str,
password: Option<&str>,
timeout: std::time::Duration,
) -> Result<(), StockError>;
}
/// The compiled-in method implementation.
@@ -57,6 +220,35 @@ pub fn method() -> &'static dyn StockMethod {
crate::stock_method::method()
}
/// Report, over the network only, whether the board holds a complete on-board
/// stock backup that can be restored without a vendor firmware file. Zynq uses
/// the readable boot-slot path; other boards use the compiled-in method.
pub fn onboard_stock_backup_present(
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
match crate::zynq_nand::onboard_backup_present(host, password) {
Err(StockError::NotApplicable) => method().onboard_stock_backup_present(host, password),
other => other,
}
}
/// Return an alkane board to genuine stock (network-only) using its on-board
/// stock backup, via the compiled-in method. The backup must be present and
/// complete; check it first with [`onboard_stock_backup_present`].
pub fn restore_from_onboard_backup(
host: &str,
password: Option<&str>,
timeout: std::time::Duration,
) -> Result<(), StockError> {
match crate::zynq_nand::restore_from_onboard(host, password) {
Err(StockError::NotApplicable) => {
method().restore_from_onboard_backup(host, password, timeout)
}
other => other,
}
}
/// Install alkane onto a board on stock (network-only), via the compiled-in method.
pub fn install_from_stock(
host: &str,
@@ -64,12 +256,116 @@ pub fn install_from_stock(
afw: &VerifiedAfw,
password: Option<&str>,
) -> Result<(), StockError> {
// Zynq-7010 uses the readable NAND path (uImage-wrap + flash_erase/nandwrite
// over the DSH root primitive, with an on-board stock backup carved first);
// other boards use the compiled-in method.
if afw.manifest.board == crate::boards::zynq::BOARD {
let img = |role: &str| {
afw.image(role)
.map(|(_, data)| data)
.ok_or_else(|| StockError::Method(format!("afw missing {role} image")))
};
return crate::zynq_nand::install_from_stock(
host,
img("kernel")?,
img("dtb")?,
img("rootfs")?,
password,
);
}
// A113D (Amlogic AXG) uses the readable UBI-stage + flag-based boot chain.
if afw.manifest.board == crate::aml_ubi::BOARD {
let img = |role: &str| {
afw.image(role)
.map(|(_, data)| data)
.ok_or_else(|| StockError::Method(format!("afw missing {role} image")))
};
return crate::aml_ubi::install_from_stock(
host,
img("kernel")?,
img("dtb")?,
img("rootfs")?,
password,
);
}
method().install_from_stock(host, afw_path, afw, password)
}
/// Return an alkane board to stock (network-only), via the compiled-in method.
pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> {
method().restore_to_stock(host, password)
/// Return an alkane board to stock (network-only) by writing the genuine Bitmain
/// stock `images` back to NAND, via the compiled-in method.
pub fn restore_to_stock(
host: &str,
images: &RestoreImages,
password: Option<&str>,
) -> Result<(), StockError> {
match crate::zynq_nand::restore_to_stock(
host,
images.kernel,
images.rootfs,
images.dtb,
password,
) {
Err(StockError::NotApplicable) => {
// A113D restore is a one-byte flag flip in-band from alkane; it needs
// no stock images. Try it, then fall through to the compiled-in method.
match crate::aml_ubi::restore_to_stock(host, password) {
Err(StockError::NotApplicable) => method().restore_to_stock(host, images, password),
other => other,
}
}
other => other,
}
}
/// Restore an alkane A113D to stock with no stock firmware file: a one-byte flag
/// flip in-band from the running alkane OS (network-only). Returns
/// `NotApplicable` if the board is not an alkane A113D.
pub fn restore_aml_flag(host: &str, password: Option<&str>) -> Result<(), StockError> {
crate::aml_ubi::restore_to_stock(host, password)
}
/// Run `cmd` as root on a board running stock (network-only), via the
/// compiled-in method. `cmd` is a `/bin/sh` command line; the returned string
/// is its combined output. A non-zero exit is an error whose message is that
/// output.
pub fn root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
method().root_exec(host, password, cmd)
}
/// Write `data` to `remote_path` as root on a board running stock
/// (network-only), via the compiled-in method. Missing parent directories are
/// created and the file is left mode 0644. Large payloads are streamed.
pub fn root_put(
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError> {
method().root_put(host, password, data, remote_path)
}
/// Check, over the network, that a Zynq board is up on alkane: the web page
/// carries `marker` (case-insensitive) and SSH reports alkane with a kernel
/// containing `kernel_version` (if non-empty). Retries until `timeout`.
pub fn verify_zynq_live(
host: &str,
password: Option<&str>,
marker: &str,
kernel_version: &str,
timeout: std::time::Duration,
) -> Result<LiveCheck, StockError> {
crate::stock_method::live_check(host, password, marker, kernel_version, timeout)
}
/// Update a board already on alkane to the `.afw`'s images, in place
/// (network-only), via the compiled-in method.
pub fn update_in_place(
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
method().update_in_place(host, afw, password, options)
}
#[cfg(test)]
@@ -79,8 +375,103 @@ mod tests {
// The interface is exercised against whatever `stock_method` provides. We
// only assert the toolkit wires a method object in; its behaviour is the
// method module's own tests.
#[test]
fn public_signatures_are_wired() {
let _: fn(&str, Option<&str>) -> Result<bool, StockError> = onboard_stock_backup_present;
let _: fn(&str, Option<&str>, std::time::Duration) -> Result<(), StockError> =
restore_from_onboard_backup;
let _: fn(&str, Option<&str>, &str) -> Result<String, StockError> = root_exec;
let _: fn(&str, Option<&str>, &[u8], &str) -> Result<(), StockError> = root_put;
}
struct FakeMethod {
present: bool,
}
impl StockMethod for FakeMethod {
fn install_from_stock(
&self,
_: &str,
_: &Path,
_: &VerifiedAfw,
_: Option<&str>,
) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn restore_to_stock(
&self,
_: &str,
_: &RestoreImages,
_: Option<&str>,
) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn root_exec(&self, _: &str, _: Option<&str>, _: &str) -> Result<String, StockError> {
Err(StockError::NotImplemented)
}
fn root_put(&self, _: &str, _: Option<&str>, _: &[u8], _: &str) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn update_in_place(
&self,
_: &str,
_: &VerifiedAfw,
_: Option<&str>,
_: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
Err(StockError::NotImplemented)
}
fn onboard_stock_backup_present(
&self,
_: &str,
_: Option<&str>,
) -> Result<bool, StockError> {
Ok(self.present)
}
fn restore_from_onboard_backup(
&self,
_: &str,
_: Option<&str>,
_: std::time::Duration,
) -> Result<(), StockError> {
if self.present {
Ok(())
} else {
Err(StockError::Method(
"no complete on-board stock backup".into(),
))
}
}
}
#[test]
fn a_method_is_compiled_in() {
let _m: &dyn StockMethod = method();
}
#[test]
fn onboard_backup_methods_report_present_or_absent() {
let present = FakeMethod { present: true };
assert!(present
.onboard_stock_backup_present("192.0.2.10", Some("secret"))
.unwrap());
assert!(present
.restore_from_onboard_backup("192.0.2.10", Some("secret"), std::time::Duration::ZERO)
.is_ok());
let absent = FakeMethod { present: false };
assert!(!absent
.onboard_stock_backup_present("192.0.2.10", None)
.unwrap());
assert!(matches!(
absent.restore_from_onboard_backup("192.0.2.10", None, std::time::Duration::ZERO),
Err(StockError::Method(_))
));
}
}
+282
View File
@@ -0,0 +1,282 @@
// SPDX-License-Identifier: MIT
//! Parse a genuine Bitmain Antminer stock firmware package into the flashable
//! stock images, so the toolkit can restore a board to genuine stock using the
//! vendor's own files (no carved blobs).
//!
//! Two genuine source shapes are handled for the Zynq-7010 (Antminer S17):
//!
//! - OTA update `.tar.gz` (`Antminer-S17-user-OM-<date>-sig*.tar.gz`): a signed
//! outer tar holding `cert.pem`, `fw.tar.gz` and `runme.sh` (each with a
//! `.sig`). The inner `fw.tar.gz` holds `BOOT.bin`, `uImage` (legacy kernel),
//! `uramdisk.image.gz` (rootfs) and `md5_info` (md5 of the rootfs). The OTA
//! package does NOT carry the device tree: the factory SD provisioning writes
//! it once and OTA upgrades preserve it.
//! - SD recovery `.zip` (`SD_Antminer-S17-*.zip`): the full factory image,
//! which DOES include `devicetree.dtb` alongside `BOOT.bin`/`uImage`/
//! `uramdisk.image.gz`. This is the complete source for a from-anywhere
//! restore, because it carries the device tree the stock kernel needs.
//!
//! Extraction shells out to the system `tar`/`unzip`/`gzip` (as the release
//! fetch shells out to `curl`); nothing is written outside a private temp dir.
use std::path::Path;
use std::process::Command;
use crate::md5::md5_hex;
#[derive(Debug, thiserror::Error)]
pub enum StockFirmwareError {
#[error("io: {0}")]
Io(String),
#[error("could not read {0}")]
Read(String),
#[error("unrecognised firmware package (not a .tar.gz or .zip): {0}")]
Format(String),
#[error("extraction failed: {0}")]
Extract(String),
#[error("the firmware package is missing a stock {0} image")]
MissingImage(&'static str),
#[error("rootfs md5 mismatch: package lists {expected}, image is {actual}")]
RootfsMd5 { expected: String, actual: String },
#[error("needed system tool not found: {0}")]
MissingTool(String),
}
/// The stock images carved from a genuine Bitmain firmware package, ready to
/// write back to NAND. `boot_bin` and `dtb` are optional (an OTA package omits
/// the dtb; the bootloader is only written on an explicit full restore).
pub struct StockFirmware {
pub boot_bin: Option<Vec<u8>>,
pub dtb: Option<Vec<u8>>,
pub kernel: Vec<u8>,
pub rootfs: Vec<u8>,
pub version: Option<String>,
/// The source package kind, for logging.
pub source_kind: &'static str,
}
impl StockFirmware {
pub fn summary(&self) -> String {
let v = self.version.as_deref().unwrap_or("unknown");
format!(
"{} (version {}): kernel {} B, rootfs {} B, dtb {}, BOOT.bin {}",
self.source_kind,
v,
self.kernel.len(),
self.rootfs.len(),
self.dtb.as_ref().map_or("absent", |_| "present"),
self.boot_bin.as_ref().map_or("absent", |_| "present"),
)
}
}
fn have_tool(tool: &str) -> bool {
Command::new(tool)
.arg("--version")
.output()
.map(|o| o.status.success() || !o.stdout.is_empty() || !o.stderr.is_empty())
.unwrap_or(false)
}
fn run(cmd: &mut Command, what: &str) -> Result<(), StockFirmwareError> {
let out = cmd
.output()
.map_err(|e| StockFirmwareError::Extract(format!("{what}: {e}")))?;
if !out.status.success() {
return Err(StockFirmwareError::Extract(format!(
"{what}: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
Ok(())
}
/// Recursively collect files under `dir` as (relative-path-lowercased, absolute path).
fn collect_files(dir: &Path) -> Vec<(String, std::path::PathBuf)> {
fn walk(base: &Path, dir: &Path, out: &mut Vec<(String, std::path::PathBuf)>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
walk(base, &path, out);
} else if let Ok(rel) = path.strip_prefix(base) {
out.push((rel.to_string_lossy().to_lowercase(), path.clone()));
}
}
}
let mut out = Vec::new();
walk(dir, dir, &mut out);
out
}
/// Pick the best file whose basename matches `name`, preferring paths that
/// contain one of `prefer` path fragments (e.g. "bin/" for the SD image, "fw"
/// for the OTA inner tree), then the shallowest path.
fn pick<'a>(
files: &'a [(String, std::path::PathBuf)],
name: &str,
prefer: &[&str],
) -> Option<&'a std::path::PathBuf> {
let name = name.to_lowercase();
let mut matches: Vec<&(String, std::path::PathBuf)> = files
.iter()
.filter(|(rel, _)| rel.rsplit('/').next() == Some(name.as_str()) || *rel == name)
.collect();
if matches.is_empty() {
return None;
}
matches.sort_by_key(|(rel, _)| {
let pref_rank = prefer
.iter()
.position(|p| rel.contains(p))
.unwrap_or(prefer.len());
let depth = rel.matches('/').count();
(pref_rank, depth)
});
matches.first().map(|(_, p)| p)
}
fn read(path: &Path) -> Result<Vec<u8>, StockFirmwareError> {
std::fs::read(path).map_err(|_| StockFirmwareError::Read(path.display().to_string()))
}
/// Parse a genuine Bitmain stock firmware package (OTA `.tar.gz` or SD `.zip`)
/// into its stock images.
pub fn parse(path: &Path) -> Result<StockFirmware, StockFirmwareError> {
let bytes = std::fs::read(path)
.map_err(|e| StockFirmwareError::Io(format!("{}: {e}", path.display())))?;
if bytes.len() < 4 {
return Err(StockFirmwareError::Format(path.display().to_string()));
}
let is_gzip = bytes[0] == 0x1f && bytes[1] == 0x8b;
let is_zip = &bytes[0..2] == b"PK";
if !is_gzip && !is_zip {
return Err(StockFirmwareError::Format(path.display().to_string()));
}
let tmp = tempfile::Builder::new()
.prefix("alkane-stockfw-")
.tempdir()
.map_err(|e| StockFirmwareError::Io(e.to_string()))?;
let root = tmp.path();
let (source_kind, prefer): (&'static str, &[&str]) = if is_zip {
if !have_tool("unzip") {
return Err(StockFirmwareError::MissingTool("unzip".into()));
}
run(
Command::new("unzip")
.arg("-qq")
.arg("-o")
.arg(path)
.arg("-d")
.arg(root),
"unzip SD recovery image",
)?;
("Bitmain SD recovery image", &["bin/"])
} else {
if !have_tool("tar") {
return Err(StockFirmwareError::MissingTool("tar".into()));
}
run(
Command::new("tar").arg("xzf").arg(path).arg("-C").arg(root),
"untar OTA package",
)?;
// The signed OTA wraps the real images in an inner fw.tar.gz; extract it.
let inner = collect_files(root)
.into_iter()
.find(|(rel, _)| rel.rsplit('/').next() == Some("fw.tar.gz"));
if let Some((_, inner_path)) = inner {
let inner_dir = root.join("fw");
std::fs::create_dir_all(&inner_dir)
.map_err(|e| StockFirmwareError::Io(e.to_string()))?;
run(
Command::new("tar")
.arg("xzf")
.arg(&inner_path)
.arg("-C")
.arg(&inner_dir),
"untar OTA inner fw.tar.gz",
)?;
}
("Bitmain OTA update package", &["fw/", "bin/"])
};
let files = collect_files(root);
let kernel_path = pick(&files, "uImage", prefer)
.ok_or(StockFirmwareError::MissingImage("uImage (kernel)"))?;
let rootfs_path = pick(&files, "uramdisk.image.gz", prefer).ok_or(
StockFirmwareError::MissingImage("uramdisk.image.gz (rootfs)"),
)?;
let kernel = read(kernel_path)?;
let rootfs = read(rootfs_path)?;
let boot_bin = pick(&files, "BOOT.bin", prefer)
.map(|p| read(p))
.transpose()?;
let dtb = pick(&files, "devicetree.dtb", &["", "bin/"])
.map(|p| read(p))
.transpose()?;
// Verify the rootfs against md5_info when the package ships one (OTA does).
if let Some(md5_path) = pick(&files, "md5_info", prefer) {
if let Ok(raw) = std::fs::read_to_string(md5_path) {
let expected = raw.split_whitespace().next().unwrap_or("").to_lowercase();
if expected.len() == 32 {
let actual = md5_hex(&rootfs);
if actual != expected {
return Err(StockFirmwareError::RootfsMd5 { expected, actual });
}
}
}
}
let version = pick(&files, "version", prefer)
.or_else(|| pick(&files, "version_number", &[""]))
.and_then(|p| std::fs::read_to_string(p).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
Ok(StockFirmware {
boot_bin,
dtb,
kernel,
rootfs,
version,
source_kind,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_non_archive() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"not an archive").unwrap();
assert!(matches!(
parse(tmp.path()),
Err(StockFirmwareError::Format(_))
));
}
// Parse a real Bitmain firmware package. Set ALKANE_TEST_STOCK_FW to its path.
// Ignored by default (needs the vendor file, not in the repo).
#[test]
#[ignore]
fn parses_real_package() {
let Ok(path) = std::env::var("ALKANE_TEST_STOCK_FW") else {
eprintln!("set ALKANE_TEST_STOCK_FW to a firmware file");
return;
};
let fw = parse(Path::new(&path)).expect("parse");
eprintln!("{}", fw.summary());
assert!(!fw.kernel.is_empty(), "kernel present");
assert!(!fw.rootfs.is_empty(), "rootfs present");
// The kernel is a legacy u-boot uImage: magic 0x27051956 big-endian.
assert_eq!(&fw.kernel[0..4], &[0x27, 0x05, 0x19, 0x56], "uImage magic");
}
}
File diff suppressed because it is too large Load Diff
+152
View File
@@ -0,0 +1,152 @@
// SPDX-License-Identifier: MIT
//! Legacy U-Boot image (`uImage`) header builder.
//!
//! The Zynq (Antminer S17/S19-class) stock U-Boot boots a legacy uImage: a
//! 64-byte big-endian header (magic `0x27051956`) in front of the payload. We
//! wrap the kernel (a raw ARM `zImage`) and the ramdisk (a gzipped cpio) in this
//! header so the board's own U-Boot boots them unchanged. The device tree is
//! written raw (no header).
//!
//! The header parameters below were read directly off a genuine stock S17 NAND
//! (kernel: type Kernel, uncompressed, load/entry `0x8000`; ramdisk: type
//! RAMDisk, gzip, load/entry `0`), so the images we write match exactly what the
//! stock boot chain already boots.
/// Legacy uImage magic (big-endian).
pub const IH_MAGIC: u32 = 0x2705_1956;
/// Header length in bytes.
pub const HEADER_LEN: usize = 64;
// ih_os
const IH_OS_LINUX: u8 = 5;
// ih_arch
const IH_ARCH_ARM: u8 = 2;
// ih_type
const IH_TYPE_KERNEL: u8 = 2;
const IH_TYPE_RAMDISK: u8 = 3;
// ih_comp
const IH_COMP_NONE: u8 = 0;
const IH_COMP_GZIP: u8 = 1;
/// A CRC-32 (IEEE 802.3, the variant U-Boot uses) over `data`.
pub fn crc32(data: &[u8]) -> u32 {
let mut crc: u32 = 0xFFFF_FFFF;
for &byte in data {
crc ^= byte as u32;
for _ in 0..8 {
let mask = (crc & 1).wrapping_neg();
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
}
}
!crc
}
/// Which kind of uImage to build.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// ARM Linux kernel, uncompressed, load/entry 0x8000 (what the stock S17
/// kernel uImage uses).
Kernel,
/// ARM Linux ramdisk, gzip, load/entry 0 (what the stock S17 ramdisk uImage
/// uses).
Ramdisk,
}
impl Kind {
fn ih_type(self) -> u8 {
match self {
Kind::Kernel => IH_TYPE_KERNEL,
Kind::Ramdisk => IH_TYPE_RAMDISK,
}
}
fn ih_comp(self) -> u8 {
match self {
Kind::Kernel => IH_COMP_NONE,
Kind::Ramdisk => IH_COMP_GZIP,
}
}
fn load_entry(self) -> u32 {
match self {
Kind::Kernel => 0x8000,
Kind::Ramdisk => 0,
}
}
}
/// Wrap `payload` in a legacy uImage header of the given `kind` and return the
/// full image (header followed by payload). `time` is the header timestamp; pass
/// a fixed value for a reproducible image. `name` is truncated to 31 bytes.
pub fn wrap(kind: Kind, payload: &[u8], time: u32, name: &str) -> Vec<u8> {
let mut hdr = [0u8; HEADER_LEN];
hdr[0..4].copy_from_slice(&IH_MAGIC.to_be_bytes());
// hdr[4..8] header CRC: filled in last, over the header with this field zero.
hdr[8..12].copy_from_slice(&time.to_be_bytes());
hdr[12..16].copy_from_slice(&(payload.len() as u32).to_be_bytes());
hdr[16..20].copy_from_slice(&kind.load_entry().to_be_bytes());
hdr[20..24].copy_from_slice(&kind.load_entry().to_be_bytes());
hdr[24..28].copy_from_slice(&crc32(payload).to_be_bytes());
hdr[28] = IH_OS_LINUX;
hdr[29] = IH_ARCH_ARM;
hdr[30] = kind.ih_type();
hdr[31] = kind.ih_comp();
let name_bytes = name.as_bytes();
let n = name_bytes.len().min(31);
hdr[32..32 + n].copy_from_slice(&name_bytes[..n]);
// Header CRC over the 64-byte header with the hcrc field (4..8) zeroed.
let hcrc = crc32(&hdr);
hdr[4..8].copy_from_slice(&hcrc.to_be_bytes());
let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
out.extend_from_slice(&hdr);
out.extend_from_slice(payload);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crc32_known_vector() {
// CRC-32/ISO-HDLC of "123456789" is 0xCBF43926.
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
assert_eq!(crc32(b""), 0);
}
#[test]
fn header_shape_and_fields() {
let img = wrap(Kind::Kernel, b"payload-bytes", 0, "alkane");
assert_eq!(img.len(), HEADER_LEN + 13);
assert_eq!(&img[0..4], &IH_MAGIC.to_be_bytes());
assert_eq!(u32::from_be_bytes([img[12], img[13], img[14], img[15]]), 13);
// kernel: load/entry 0x8000, type kernel, comp none
assert_eq!(&img[16..20], &0x8000u32.to_be_bytes());
assert_eq!(&img[20..24], &0x8000u32.to_be_bytes());
assert_eq!(img[28], IH_OS_LINUX);
assert_eq!(img[29], IH_ARCH_ARM);
assert_eq!(img[30], IH_TYPE_KERNEL);
assert_eq!(img[31], IH_COMP_NONE);
assert_eq!(&img[64..], b"payload-bytes");
}
#[test]
fn ramdisk_fields() {
let img = wrap(Kind::Ramdisk, b"rd", 0, "rd");
assert_eq!(&img[16..20], &0u32.to_be_bytes());
assert_eq!(img[30], IH_TYPE_RAMDISK);
assert_eq!(img[31], IH_COMP_GZIP);
}
#[test]
fn header_crc_validates() {
let img = wrap(Kind::Kernel, b"abc", 0x1234, "n");
let mut hdr = [0u8; HEADER_LEN];
hdr.copy_from_slice(&img[..HEADER_LEN]);
let stored = u32::from_be_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]);
hdr[4..8].copy_from_slice(&[0, 0, 0, 0]);
assert_eq!(crc32(&hdr), stored);
// data CRC over payload
let dcrc = u32::from_be_bytes([img[24], img[25], img[26], img[27]]);
assert_eq!(crc32(b"abc"), dcrc);
}
}
+809
View File
@@ -0,0 +1,809 @@
// SPDX-License-Identifier: MIT
//! Readable Zynq-7010 NAND install / restore / on-board-backup, driven entirely
//! over the network through two small root shells:
//!
//! * a board on **stock** is reached with the DSH root-on-stock primitives
//! (`crate::stock::root_exec` / `root_put`): this is the only compartmentalised
//! piece, and it is used only to get a root shell;
//! * a board on **alkane** is reached with ordinary SSH (`crate::transport`).
//!
//! Everything else -- what to write, where, in what form, and the read-back
//! verification -- lives here in plain, auditable Rust. The NAND writes
//! themselves are the same `flash_erase` + `nandwrite` MTD operations on both
//! sides; only the way we obtain the root shell differs.
//!
//! Absolute NAND map (Micron MT29F2G08, 256 MiB, 128 KiB erase, 2 KiB page),
//! confirmed on a genuine stock S17 and mirrored by the alkane board DT:
//! ```text
//! 0x00000000 BOOT.bin (FSBL + bitstream + stock U-Boot + env) NEVER written
//! 0x01a00000 device tree (raw fdt)
//! 0x02000000 kernel (legacy uImage)
//! 0x02800000 rootfs (legacy uImage ramdisk)
//! 0x04800000 stock `configs` (UBI) exposed read-only on alkane
//! 0x05000000 alkane-cfg (persisted MAC)
//! 0x06000000 on-board genuine-stock backup (stock `ramfs-bak` region)
//! 0x08000000 stock `reserve1` / nvdata (UBI) left untouched
//! ```
//! On a board running alkane the boot slots are exposed as the named partitions
//! `boot-dtb` / `boot-kernel` / `boot-rootfs` / `stock-backup` (see the board
//! DT); on stock they fall inside `mtd0` / `mtd1` / `ramfs-bak`. Because we map
//! an absolute offset to whichever MTD partition contains it, the same code
//! writes the same physical NAND on both sides.
use crate::md5::md5_hex;
use crate::stock::StockError;
use crate::transport::{Remote, SshOptions, SshTransport};
use crate::uimage::{self, Kind};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
/// NAND erase-block size (128 KiB).
const ERASE: u64 = 0x20000;
/// NAND page size (2 KiB); `nandwrite -p` pads the final page with 0xFF.
const PAGE: u64 = 0x800;
/// Absolute boot-slot offsets (see the module map).
const OFF_DTB: u64 = 0x1a00000;
const OFF_KERNEL: u64 = 0x2000000;
const OFF_ROOTFS: u64 = 0x2800000;
const OFF_STOCK_BACKUP: u64 = 0x6000000;
/// BOOT.bin occupies 0x0..0x1a00000 and is never written.
const BOOTBIN_PRESERVE: u64 = 0x1a00000;
/// Slot ceilings (so a too-large image is refused before any erase).
const SLOT_DTB: u64 = 0x600000;
const SLOT_KERNEL: u64 = 0x800000;
const SLOT_ROOTFS: u64 = 0x2000000;
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";
fn round_up(value: u64, to: u64) -> u64 {
value.div_ceil(to) * to
}
// ---------------------------------------------------------------------------
// Root shells
// ---------------------------------------------------------------------------
/// A root shell on the target board: run a `/bin/sh` command as root and stream
/// a byte payload to a file as root. Both sides implement this; the NAND code
/// below is written once against it.
trait Shell {
fn exec(&mut self, cmd: &str) -> Result<String, StockError>;
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>;
/// Longer-running command (large nandwrite / nanddump).
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError>;
}
/// Stock board: root obtained through the compartmentalised DSH primitive.
struct StockShell {
host: String,
password: Option<String>,
}
impl Shell for StockShell {
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
}
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
}
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path)
}
}
/// Alkane board: root over ordinary SSH. A throwaway known-hosts file is used
/// so a board whose SSH host key legitimately changed across an install still
/// connects (accept-new), which is the norm on the bench.
struct AlkaneShell {
transport: SshTransport,
_secret: TempFile,
}
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
fn temp_path(tag: &str) -> std::path::PathBuf {
let n = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
std::env::temp_dir().join(format!("alkane-{}-{}-{}", std::process::id(), tag, n))
}
/// A 0600 temp file removed on drop.
struct TempFile(std::path::PathBuf);
impl TempFile {
fn with(contents: &[u8], tag: &str) -> Result<Self, StockError> {
let path = temp_path(tag);
write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?;
Ok(TempFile(path))
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[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)
.truncate(true)
.write(true)
.mode(0o600)
.open(path)?;
f.write_all(contents)?;
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")?;
let known = temp_path("kh");
let _ = std::fs::File::create(&known); // empty -> accept-new always accepts
let options = SshOptions {
host: host.to_owned(),
port: 22,
user: "root".to_owned(),
identity_file: None,
password_file: Some(secret.0.clone()),
known_hosts: Some(known),
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
})
}
}
impl Shell for AlkaneShell {
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
self.transport
.root_command(cmd, Duration::from_secs(120))
.map(|o| String::from_utf8_lossy(&o).into_owned())
.map_err(|e| StockError::Method(e.to_string()))
}
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
self.transport
.root_command(cmd, Duration::from_secs(900))
.map(|o| String::from_utf8_lossy(&o).into_owned())
.map_err(|e| StockError::Method(e.to_string()))
}
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
let tmp = TempFile::with(data, "put")?;
self.transport
.push(&tmp.0, remote_path, Duration::from_secs(900))
.map_err(|e| StockError::Method(e.to_string()))
}
}
// ---------------------------------------------------------------------------
// MTD table: map an absolute NAND offset to (device, relative offset)
// ---------------------------------------------------------------------------
#[derive(Clone, Debug)]
struct Mtd {
dev: String, // e.g. "mtd2"
base: u64, // absolute NAND offset of the partition start
size: u64,
#[allow(dead_code)]
name: String,
}
/// Read the MTD partition table. Each partition's absolute base comes from
/// `/sys/class/mtd/<dev>/offset` when present (alkane, where partitions are not
/// contiguous), falling back to the cumulative sum of sizes in `/proc/mtd`
/// order (stock, where they are contiguous from 0).
fn read_mtd_table(sh: &mut dyn Shell) -> Result<Vec<Mtd>, StockError> {
// name + size from /proc/mtd (always present); offset from sysfs if present.
let proc = sh.exec("cat /proc/mtd")?;
let mut out = Vec::new();
let mut cursor = 0u64;
for line in proc.lines() {
let line = line.trim();
if !line.starts_with("mtd") {
continue;
}
// "mtd0: 02800000 00020000 \"name\""
let (dev, rest) = match line.split_once(':') {
Some(v) => v,
None => continue,
};
let mut it = rest.split_whitespace();
let size = it
.next()
.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 base = match sysfs_offset(sh, dev) {
Some(off) => off,
None => cursor,
};
cursor = cursor.max(base) + size;
out.push(Mtd {
dev: dev.to_owned(),
base,
size,
name,
});
}
if out.is_empty() {
return Err(StockError::Method("no MTD partitions found".into()));
}
Ok(out)
}
fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option<u64> {
let out = sh
.exec(&format!("cat /sys/class/mtd/{dev}/offset 2>/dev/null"))
.ok()?;
out.trim().parse::<u64>().ok()
}
/// Find the partition that contains `abs` and holding at least `len` bytes from
/// there; return (device, relative offset).
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;
if rel + len > m.size {
return Err(StockError::Method(format!(
"write of {len} B at abs 0x{abs:x} overruns {} (rel 0x{rel:x}, size 0x{:x})",
m.dev, m.size
)));
}
return Ok((&m.dev, rel));
}
}
Err(StockError::Method(format!(
"no MTD partition exposes absolute offset 0x{abs:x} (is the boot region mapped?)"
)))
}
// ---------------------------------------------------------------------------
// NAND primitives
// ---------------------------------------------------------------------------
/// MD5 of `data` padded with 0xFF up to the next page boundary -- what a
/// `nandwrite -p` of `data` leaves on flash and what `nanddump -l <rounded>`
/// reads back.
fn padded_md5(data: &[u8]) -> String {
let rounded = round_up(data.len() as u64, PAGE) as usize;
let mut buf = data.to_vec();
buf.resize(rounded, 0xFF);
md5_hex(&buf)
}
/// Write `data` to absolute NAND offset `abs`, staging it in `/tmp/alk`, erasing
/// the covering erase blocks, writing with `nandwrite -p`, and verifying the
/// read-back against the padded MD5. `abs` must be erase-block aligned.
fn write_abs(
sh: &mut dyn Shell,
table: &[Mtd],
abs: u64,
data: &[u8],
label: &str,
) -> Result<(), StockError> {
if abs < BOOTBIN_PRESERVE {
return Err(StockError::Method(format!(
"refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin"
)));
}
if !abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{label} offset 0x{abs:x} is not erase-block aligned"
)));
}
let (dev, rel) = locate(table, abs, data.len() as u64)?;
let dev = dev.to_owned();
let blocks = round_up(data.len() as u64, ERASE) / ERASE;
let remote = format!("/tmp/alk/{label}.img");
sh.exec("mkdir -p /tmp/alk")?;
sh.put(data, &remote)?;
// Confirm the staged payload arrived intact before we erase anything.
let put_md5 = first_token(&sh.exec(&format!("md5sum {remote}"))?);
if put_md5 != md5_hex(data) {
return Err(StockError::Method(format!(
"{label}: staged copy md5 {put_md5} != {} (transfer corrupted)",
md5_hex(data)
)));
}
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 WROTE"
))
.and_then(|o| {
if o.contains("WROTE") {
Ok(())
} else {
Err(StockError::Method(format!(
"{label}: erase/write failed: {o}"
)))
}
})?;
let readlen = round_up(data.len() as u64, PAGE);
let back = first_token(&sh.exec_long(&format!(
"nanddump -s 0x{rel:x} -l {readlen} /dev/{dev} 2>/dev/null | md5sum"
))?);
let want = padded_md5(data);
if back != want {
return Err(StockError::Method(format!(
"{label}: read-back md5 {back} != {want} at /dev/{dev} rel 0x{rel:x} \
(write did not persist)"
)));
}
sh.exec(&format!("rm -f {remote}"))?;
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(
sh: &mut dyn Shell,
table: &[Mtd],
src: u64,
dst: u64,
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") {
return Err(StockError::Method(format!(
"{label}: backup copy failed: {out}"
)));
}
Ok(())
}
/// Read `len` (even) bytes from NAND at (dev, rel) as raw bytes, via
/// `od -v -x`, which is the only `od` form the stock busybox understands (no
/// `-A`/`-t`). The leading octal address column and trailing byte-count line are
/// discarded by [`parse_od`].
fn read_small(sh: &mut dyn Shell, dev: &str, rel: u64, len: u64) -> Result<Vec<u8>, StockError> {
let out = sh.exec(&format!(
"nanddump -s 0x{rel:x} -l {len} /dev/{dev} 2>/dev/null | od -v -x"
))?;
Ok(parse_od(&out))
}
/// Read a big-endian u32 at byte `field_off` within the image whose header
/// starts at the (page-aligned) absolute NAND offset `region_abs`. `nanddump`
/// needs a page-aligned `-s`, so we read the first 64 bytes of the region and
/// slice the field in Rust (used to size the genuine stock images from their
/// uImage / fdt headers before backing up).
fn read_header_u32_be(
sh: &mut dyn Shell,
table: &[Mtd],
region_abs: u64,
field_off: usize,
) -> Result<u32, StockError> {
let (dev, rel) = locate(table, region_abs, 64)?;
let dev = dev.to_owned();
let b = read_small(sh, &dev, rel, 64)?;
if b.len() < field_off + 4 {
return Err(StockError::Method(format!(
"short header read at 0x{region_abs:x} ({} bytes)",
b.len()
)));
}
Ok(u32::from_be_bytes([
b[field_off],
b[field_off + 1],
b[field_off + 2],
b[field_off + 3],
]))
}
fn first_token(s: &str) -> String {
s.split_whitespace().next().unwrap_or("").to_owned()
}
// ---------------------------------------------------------------------------
// On-board stock backup manifest
// ---------------------------------------------------------------------------
#[derive(Clone, Debug)]
struct BackupManifest {
kernel_abs: u64,
kernel_len: u64,
dtb_abs: u64,
dtb_len: u64,
rootfs_abs: u64,
rootfs_len: u64,
}
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());
}
v
}
fn decode(b: &[u8]) -> Option<Self> {
if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC {
return None;
}
let g = |i: usize| {
let mut a = [0u8; 8];
a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]);
u64::from_be_bytes(a)
};
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),
})
}
}
/// 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.
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 !(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"
)));
}
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 manifest = BackupManifest {
kernel_abs: k_dst,
kernel_len,
dtb_abs: d_dst,
dtb_len,
rootfs_abs: r_dst,
rootfs_len,
};
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) {
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))
}
/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x`
/// (little-endian 16-bit words).
fn parse_od(s: &str) -> Vec<u8> {
let toks: Vec<&str> = s.split_whitespace().collect();
// Heuristic: 2-char tokens are bytes (-tx1); 4-char tokens are LE words (-x).
let mut out = Vec::new();
for t in &toks {
match t.len() {
2 => {
if let Ok(b) = u8::from_str_radix(t, 16) {
out.push(b);
}
}
4 => {
if let Ok(w) = u16::from_str_radix(t, 16) {
out.push((w & 0xff) as u8);
out.push((w >> 8) as u8);
}
}
_ => {}
}
}
out
}
// ---------------------------------------------------------------------------
// Operations
// ---------------------------------------------------------------------------
/// What to write to the three boot slots (already in the exact on-NAND form:
/// kernel and rootfs as legacy uImages, dtb as a raw fdt).
struct BootImages {
kernel_uimage: Vec<u8>,
dtb: Vec<u8>,
rootfs_uimage: Vec<u8>,
}
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 {
return Err(StockError::Method("rootfs over slot ceiling".into()));
}
if img.dtb.len() as u64 > SLOT_DTB {
return Err(StockError::Method("dtb over slot ceiling".into()));
}
if img.kernel_uimage.len() as u64 > SLOT_KERNEL {
return Err(StockError::Method("kernel over slot ceiling".into()));
}
write_abs(sh, table, OFF_ROOTFS, &img.rootfs_uimage, "rootfs")?;
write_abs(sh, table, OFF_DTB, &img.dtb, "dtb")?;
write_abs(sh, table, OFF_KERNEL, &img.kernel_uimage, "kernel")?;
Ok(())
}
/// Whether the connected board is a Zynq, so the readable boot-slot path
/// applies. Other boards fall back to the compiled-in method.
fn shell_is_zynq(sh: &mut dyn Shell) -> bool {
sh.exec(
"(grep -qi zynq /proc/cpuinfo 2>/dev/null || \
grep -qai zynq /proc/device-tree/compatible 2>/dev/null) && echo yes || true",
)
.map(|o| o.contains("yes"))
.unwrap_or(false)
}
fn reboot(sh: &mut dyn Shell) {
// Best-effort: the reboot drops the shell, so ignore the result.
let _ = sh.exec("sync; (sleep 1; reboot) >/dev/null 2>&1 &");
}
/// Install alkane onto a board currently on stock, over the network. The afw
/// ships a raw `zImage`, a raw fdt and a gzipped cpio rootfs; we wrap the kernel
/// and rootfs as the legacy uImages the preserved stock U-Boot boots, carve the
/// genuine stock backup first, then write the boot slots and reboot.
pub fn install_from_stock(
host: &str,
kernel_zimage: &[u8],
dtb: &[u8],
rootfs_cpio_gz: &[u8],
password: Option<&str>,
) -> Result<(), StockError> {
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 table = read_mtd_table(&mut sh)?;
// Carve the genuine-stock backup from the live stock NAND before any write.
carve_backup(&mut sh, &table)?;
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);
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.
pub fn restore_to_stock(
host: &str,
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(())
}
/// Whether the board holds a complete, restorable on-board stock backup.
pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result<bool, 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)?;
Ok(read_backup_manifest(&mut sh, &table)?.is_some())
}
/// Return an alkane board to stock using only the on-board backup (no vendor
/// file): copy the saved stock kernel, dtb and rootfs back to the boot slots.
pub fn restore_from_onboard(host: &str, 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)?;
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",
)?;
reboot(&mut sh);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_up_works() {
assert_eq!(round_up(1, PAGE), PAGE);
assert_eq!(round_up(PAGE, PAGE), PAGE);
assert_eq!(round_up(PAGE + 1, PAGE), 2 * PAGE);
assert_eq!(round_up(0, ERASE), 0);
}
#[test]
fn padded_md5_matches_manual_pad() {
let data = b"hello";
let mut padded = data.to_vec();
padded.resize(PAGE as usize, 0xFF);
assert_eq!(padded_md5(data), md5_hex(&padded));
}
#[test]
fn manifest_roundtrips() {
let m = BackupManifest {
kernel_abs: 0x6020000,
kernel_len: 4006832,
dtb_abs: 0x6420000,
dtb_len: 7650,
rootfs_abs: 0x6440000,
rootfs_len: 26620582,
};
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!(BackupManifest::decode(b"nope").is_none());
}
#[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(),
},
];
assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000));
assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0));
assert!(locate(&table, 0x9000000, 1).is_err());
}
#[test]
fn parse_od_both_forms() {
// -tx1 byte form
assert_eq!(parse_od("41 42 43"), vec![0x41, 0x42, 0x43]);
// -x little-endian word form -> bytes
assert_eq!(parse_od("4241"), vec![0x41, 0x42]);
}
}
+5
View File
@@ -11,6 +11,11 @@ path = "src/main.rs"
[dependencies]
alkane-core = { path = "../alkane-core" }
alkane-discovery = { path = "../alkane-discovery" }
# The self-contained stock <-> alkane engine (compiled-in method) and the .afw
# verify/fetch, so the GUI can install-from-stock and restore-to-stock and scan
# alkane-os releases through the same code paths the CLI uses.
alkane-flash = { path = "../alkane-flash" }
alkane-artifacts = { path = "../alkane-artifacts" }
# vendored + patched wx-rs (see vendor/wx-rs/patches/)
wx-rs = { path = "../../thirdparty/wx-rs/wx-rs-0.2.0-patched" }
asic-rs = "0.8.1"
+305
View File
@@ -0,0 +1,305 @@
//! Boards running Alkane OS on the network, and which alkane-os actions apply to
//! a scanned row.
//!
//! asic-rs recognises miners by their cgminer socket (:4028) or a vendor web UI.
//! A board running Alkane OS keeps its cgminer-compatible socket on loopback and
//! serves its own console, so asic-rs reports nothing at that address and the
//! board never appeared in the fleet. This probe finds it over plain HTTP:
//! - `GET /api/identity` (alkane-os 0.1.2 and later): os, os_version, board,
//! sdk_revision, hostname, mac, kernel;
//! - otherwise the cgminer-style `GET /api/summary`, whose STATUS Description
//! is "alkane-os" (earlier images: found, but the board family is unknown).
//!
//! Both endpoints are public and read-only on the board.
use crate::model::MinerRow;
use serde_json::{json, Value};
use std::net::IpAddr;
use std::time::Duration;
/// Firmware family shown for a board running Alkane OS.
pub const FIRMWARE: &str = "Alkane";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
const READ_TIMEOUT: Duration = Duration::from_secs(4);
const MAX_RESPONSE: usize = 64 * 1024;
/// Probe `ip` for Alkane OS. Returns a row for the fleet table, or None when the
/// address is not an Alkane board (or does not answer on :80).
pub async fn detect(ip: IpAddr) -> Option<MinerRow> {
if let Some(doc) = get_json(ip, "/api/identity").await {
if doc.get("os").and_then(Value::as_str) == Some("alkane-os") {
return Some(row_from_identity(ip, &doc));
}
}
let summary = get_json(ip, "/api/summary").await?;
if is_alkane_summary(&summary) {
return Some(row_from_identity(ip, &json!({})));
}
None
}
/// The cgminer-style summary an Alkane board serves names "alkane-os" in its
/// STATUS Description.
fn is_alkane_summary(doc: &Value) -> bool {
doc.get("STATUS")
.and_then(Value::as_array)
.and_then(|status| status.first())
.and_then(|entry| entry.get("Description"))
.and_then(Value::as_str)
== Some("alkane-os")
}
/// Control-board labels (cpu, code) for an Alkane board family, matching the
/// labels the scan gives the same board on stock firmware.
fn board_labels(board: &str) -> (&'static str, &'static str) {
match board {
"zynq-7010" => ("XIL", "C49"),
"am335x" => ("BBB", "C77"),
"cv1835" => ("CVI", "C88"),
"a113d" => ("AML", "C76"),
_ => ("", ""),
}
}
fn row_from_identity(ip: IpAddr, doc: &Value) -> MinerRow {
let text = |key: &str| {
doc.get(key)
.and_then(Value::as_str)
.unwrap_or("")
.trim()
.to_string()
};
let board = text("board");
let (cpu, code) = board_labels(&board);
let control_board = if cpu.is_empty() {
board.clone()
} else {
format!("{cpu} ({code})")
};
MinerRow {
ip: ip.to_string(),
// The Alkane-supported control boards are all Bitmain (Antminer) boards.
brand: if cpu.is_empty() {
String::new()
} else {
"Antminer".to_string()
},
firmware: FIRMWARE.to_string(),
fw_version: text("os_version"),
api_version: "alkane-os".to_string(),
mac: text("mac"),
hostname: text("hostname"),
control_board,
cpu: cpu.to_string(),
board_code: code.to_string(),
alkane_board: Some(board),
..Default::default()
}
}
/// HTTP/1.0 GET on :80 returning the JSON body of a 200 reply.
async fn get_json(ip: IpAddr, path: &str) -> Option<Value> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let connect = tokio::net::TcpStream::connect((ip, 80));
let mut stream = tokio::time::timeout(CONNECT_TIMEOUT, connect)
.await
.ok()?
.ok()?;
let request = format!("GET {path} HTTP/1.0\r\nHost: {ip}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes()).await.ok()?;
let mut raw = Vec::new();
let _ = tokio::time::timeout(READ_TIMEOUT, async {
let mut chunk = [0u8; 4096];
loop {
match stream.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(n) => {
raw.extend_from_slice(&chunk[..n]);
if raw.len() > MAX_RESPONSE {
break;
}
}
}
}
})
.await;
parse_http_json(&raw)
}
fn parse_http_json(raw: &[u8]) -> Option<Value> {
let text = std::str::from_utf8(raw).ok()?;
let (head, body) = text.split_once("\r\n\r\n")?;
let status = head.lines().next()?;
if status.split_whitespace().nth(1) != Some("200") {
return None;
}
serde_json::from_str(body.trim()).ok()
}
/// Whether the row is a board running Alkane OS (found by `detect`).
pub fn is_alkane(row: &MinerRow) -> bool {
row.alkane_board.is_some()
}
/// 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.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
if !row.brand.to_ascii_lowercase().contains("antminer") {
return None;
}
if row.cpu == "XIL" && row.board_code == "C49" {
return Some("zynq-7010".to_string());
}
// A stock S17 whose miner software is down (no hashboards attached: it
// restart-loops) reports its model but no control board. Its model then
// decides; a control board that IS reported always wins above.
if row.cpu.is_empty() && is_zynq_7010_model(&row.model) {
return Some("zynq-7010".to_string());
}
None
}
/// Stock models built only on the Zynq-7010 (XIL C49) control board.
fn is_zynq_7010_model(model: &str) -> bool {
matches!(model.trim(), "S17" | "S17 Pro" | "T17")
}
/// Whether alkane-os can be installed on the row's board: its control board is
/// one the toolkit supports.
pub fn install_supported(row: &MinerRow) -> bool {
board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board))
}
#[cfg(test)]
mod tests {
use super::*;
fn ip() -> IpAddr {
"10.0.0.5".parse().unwrap()
}
#[test]
fn parses_a_200_json_reply_only() {
let ok = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"os\":\"alkane-os\"}";
assert_eq!(parse_http_json(ok).unwrap()["os"], "alkane-os");
let denied = b"HTTP/1.1 401 Unauthorized\r\n\r\n{\"os\":\"alkane-os\"}";
assert!(parse_http_json(denied).is_none());
let html = b"HTTP/1.1 200 OK\r\n\r\n<!DOCTYPE html><title>x</title>";
assert!(parse_http_json(html).is_none());
assert!(parse_http_json(b"garbage").is_none());
}
#[test]
fn recognises_the_alkane_summary() {
let alkane = json!({"STATUS":[{"Code":0,"Description":"alkane-os","STATUS":"S"}]});
assert!(is_alkane_summary(&alkane));
let cgminer = json!({"STATUS":[{"Description":"cgminer 4.11.1","STATUS":"S"}]});
assert!(!is_alkane_summary(&cgminer));
assert!(!is_alkane_summary(&json!({})));
}
#[test]
fn identity_becomes_a_supported_alkane_row() {
let doc = json!({
"os": "alkane-os", "os_version": "0.1.2", "board": "zynq-7010",
"sdk_revision": "6a9080ac82c1", "hostname": "alkane-zynq",
"mac": "26:4e:52:8b:e2:48", "kernel": "6.18.48",
});
let row = row_from_identity(ip(), &doc);
assert_eq!(row.ip, "10.0.0.5");
assert_eq!(row.firmware, "Alkane");
assert_eq!(row.fw_version, "0.1.2");
assert_eq!(row.control_board, "XIL (C49)");
assert_eq!(row.mac, "26:4e:52:8b:e2:48");
assert!(is_alkane(&row));
assert!(install_supported(&row));
}
#[test]
fn an_old_alkane_board_is_alkane_but_its_family_is_unknown() {
// Found via /api/summary only: uninstall applies, install cannot be
// confirmed as supported.
let row = row_from_identity(ip(), &json!({}));
assert!(is_alkane(&row));
assert_eq!(board_family(&row), None);
assert!(!install_supported(&row));
}
#[test]
fn stock_antminers_are_supported_only_on_the_zynq_7010_board() {
let stock = |cpu: &str, code: &str| MinerRow {
brand: "Antminer".into(),
firmware: "Stock".into(),
cpu: cpu.into(),
board_code: code.into(),
..Default::default()
};
let s17 = stock("XIL", "C49");
assert!(install_supported(&s17));
assert!(!is_alkane(&s17));
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
assert!(!install_supported(&stock("AML", "C76")));
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
cpu: "XIL".into(),
board_code: "C49".into(),
..Default::default()
};
assert!(!install_supported(&whatsminer));
}
#[test]
fn a_stock_s17_without_a_reported_control_board_is_supported_by_model() {
// As seen live: stock S17, miner software down, control board blank.
let s17 = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
firmware: "Stock".into(),
..Default::default()
};
assert!(install_supported(&s17));
let other = |model: &str| MinerRow {
brand: "Antminer".into(),
model: model.into(),
..Default::default()
};
assert!(install_supported(&other("S17 Pro")));
assert!(install_supported(&other("T17")));
assert!(!install_supported(&other("S19")));
assert!(!install_supported(&other("S17+")));
assert!(!install_supported(&other("")));
// A reported control board overrides the model.
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
cpu: "AML".into(),
board_code: "C76".into(),
..Default::default()
};
assert!(!install_supported(&s17_on_aml));
}
/// Live check against a real board:
/// `ALKANE_TEST_IP=10.255.1.111 cargo test -p alkane-gui live_detect -- --ignored --nocapture`
#[test]
#[ignore = "needs a board on the network (ALKANE_TEST_IP)"]
fn live_detect() {
let Ok(ip) = std::env::var("ALKANE_TEST_IP") else {
return;
};
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let row = rt.block_on(detect(ip.parse().unwrap()));
println!("{row:#?}");
let row = row.expect("an Alkane board at ALKANE_TEST_IP");
assert!(is_alkane(&row));
}
}
+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
}
}
+15
View File
@@ -106,6 +106,9 @@ pub fn clear_credentials() -> std::io::Result<()> {
/// duplicated here; a firmware absent from this table defaults to blank.
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
&[
// Alkane OS ships with this control-board login, so restore-to-stock on
// an alkane board authenticates with no operator setup (issue #51).
("Alkane", "root", "alkane"),
("AntMiner Stock", "root", "root"),
("WhatsMiner Stock", "admin", "admin"),
("Braiins", "root", "root"),
@@ -134,6 +137,18 @@ pub fn firmware_default_for(name: &str) -> (String, String) {
.unwrap_or_default()
}
/// The login to use for a board running `firmware`: the operator's saved
/// per-firmware override if any, else the shipped default. This is how install
/// (a stock target) and restore (an alkane target) each pick the right login
/// automatically, without a password field in the dialog (issues #46, #51).
pub fn cred_for(firmware: &str) -> (String, String) {
load_firmware_credentials()
.get(firmware)
.cloned()
.filter(|(_, p)| !p.is_empty())
.unwrap_or_else(|| firmware_default_for(firmware))
}
/// Load the operator's per-firmware credential overrides, keyed by firmware
/// Display name. Malformed lines are skipped.
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
+18 -3
View File
@@ -6,7 +6,9 @@
#![cfg_attr(windows, windows_subsystem = "windows")]
mod access_probe;
mod alkane_detect;
mod askpass;
mod bench_sequence;
mod bug_report;
mod credentials;
mod export;
@@ -20,6 +22,7 @@ mod pool_prefs;
mod presets;
mod restore;
mod scan;
mod stock_ops;
mod ui;
fn main() {
@@ -39,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.
@@ -121,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
+62 -3
View File
@@ -527,6 +527,10 @@ pub struct MinerRow {
/// from whether any control capability is available: `None` = unknown,
/// `Some(true)` = locked, `Some(false)` = unlocked/writable.
pub write_locked: Option<bool>,
/// Set when the row is a board running Alkane OS (found by the toolkit's own
/// probe, `alkane_detect`, not asic-rs): the board family it reports
/// ("zynq-7010"), or an empty string for an older image that does not say.
pub alkane_board: Option<String>,
/// Structured error/event lines from the miner (severity + text), most
/// severe first. Empty means none. The Error column shows a summary; the
/// full list is the hover tooltip (added with the tooltip bridge support).
@@ -688,9 +692,18 @@ impl MinerRow {
/// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so
/// a missing wattage reading is treated as unknown, never a false "down".
pub fn power_health(&self) -> CompHealth {
// A miner drawing power / spinning its PSU fan / actively mining has a live
// PSU regardless of any warning flag.
let delivering = self.power_w > 0.0 || self.psu_fan_rpm > 0.0 || self.is_mining;
// A live PSU shows real evidence: measured draw, a spinning PSU fan, or
// reported PSU output. A stock control board can assert a cgminer "mining"
// status with no PSU and no hashboards attached (issue #39: a bare S17
// control board showed a green PSU), so is_mining counts only when the
// miner is actually hashing (hashrate, or at least one healthy board).
let actually_hashing =
self.hashrate_ths > 0.0 || self.board_status.contains(&BoardHealth::Ok);
let delivering = self.power_w > 0.0
|| self.psu_fan_rpm > 0.0
|| self.psu_out_voltage_v.is_some()
|| self.psu_out_current_a.is_some()
|| (self.is_mining && actually_hashing);
// A reported PSU fault while the miner is actually mining is a warning, not
// a failure -- yellow, not red (round 18 #2: some WhatsMiners flag a PSU
// error while running fine). A fault on a miner that is not mining is a real
@@ -2472,6 +2485,52 @@ mod tests {
);
}
#[test]
fn stock_board_with_nothing_attached_shows_grey_psu() {
// Issue #39: a stock S17 control board with no PSU and no hashboards
// attached asserts a cgminer "mining" status (is_mining = true) while
// reporting zero watts, no PSU fan, and no PSU output. That is not
// evidence of a live PSU, so the bolt must read grey (Unreachable).
let bare = MinerRow {
is_mining: true,
power_w: 0.0,
psu_fan_rpm: 0.0,
hashrate_ths: 0.0,
board_status: vec![BoardHealth::Missing, BoardHealth::Missing],
..Default::default()
};
assert_eq!(bare.power_health(), CompHealth::Unreachable);
// A genuinely-running miner still greens: is_mining with real hashing is
// evidence enough even when the firmware reports no watts.
let hashing = MinerRow {
is_mining: true,
power_w: 0.0,
psu_fan_rpm: 0.0,
hashrate_ths: 90.0,
board_status: vec![BoardHealth::Ok, BoardHealth::Ok],
..Default::default()
};
assert_eq!(hashing.power_health(), CompHealth::Ok);
// Measured draw alone is always enough.
let drawing = MinerRow {
is_mining: false,
power_w: 19.0,
..Default::default()
};
assert_eq!(drawing.power_health(), CompHealth::Ok);
// Reported PSU output alone is enough even with zero measured watts.
let psu_out = MinerRow {
is_mining: false,
power_w: 0.0,
psu_out_voltage_v: Some(12.0),
..Default::default()
};
assert_eq!(psu_out.power_health(), CompHealth::Ok);
}
#[test]
fn warning_fault_degrades_board_to_yellow_not_red() {
// Round 21 #1: a board still mining near full hashrate with some failed/
+119 -19
View File
@@ -531,7 +531,10 @@ pub fn start_scan(lines: Vec<String>, timeout_secs: u64) -> ScanHandle {
.ok();
(ip, row)
}
None => (ip, None),
// asic-rs does not recognise a board running Alkane
// OS (no cgminer socket or vendor web UI exposed);
// the toolkit's own probe finds it.
None => (ip, crate::alkane_detect::detect(ip).await),
}
}
})
@@ -671,6 +674,62 @@ fn messages_to_faults(
.collect()
}
/// A hashboard's health dot from its reported activity. `active` is the firmware's
/// active flag; `working_chips` its working-chip count. Green needs positive
/// evidence (active, or a nonzero chip count); a board with neither flag nor count
/// reads grey ("not detected") rather than green (issue #39: an S17 control board
/// with no hashboards attached showed its boards green). A board that is present
/// but idle or has zero working chips reads as a fault (red).
fn board_health(
active: Option<bool>,
working_chips: Option<u16>,
miner_active: bool,
) -> crate::model::BoardHealth {
use crate::model::BoardHealth;
match (active, working_chips) {
(Some(true), _) => BoardHealth::Ok,
(Some(false), _) => BoardHealth::Fault,
(None, Some(c)) if c > 0 => BoardHealth::Ok,
(None, Some(_)) => BoardHealth::Fault,
// No per-board evidence. If the miner shows overall activity (hashing),
// the board is clearly present and working -> green; only an idle miner
// with no board telemetry reads grey (issue #39: bare S17; review #3: do
// not grey a genuinely-mining miner whose backend omits per-board fields).
(None, None) => {
if miner_active {
BoardHealth::Ok
} else {
BoardHealth::Missing
}
}
}
}
#[cfg(test)]
mod board_health_tests {
use super::board_health;
use crate::model::BoardHealth;
#[test]
fn no_activity_evidence_reads_grey_not_green() {
// Issue #39: the firmware lists a board but reports no active flag and no
// working-chip count -> not detected (grey), not green.
// Idle miner, no per-board evidence -> not detected (grey).
assert_eq!(board_health(None, None, false), BoardHealth::Missing);
// Mining miner, no per-board evidence -> still green (review #3).
assert_eq!(board_health(None, None, true), BoardHealth::Ok);
// Positive evidence still greens regardless of miner activity.
assert_eq!(board_health(Some(true), None, false), BoardHealth::Ok);
assert_eq!(board_health(None, Some(63), false), BoardHealth::Ok);
// Present but idle / zero working chips -> fault (red).
assert_eq!(
board_health(Some(false), Some(63), false),
BoardHealth::Fault
);
assert_eq!(board_health(None, Some(0), false), BoardHealth::Fault);
}
}
#[cfg(test)]
mod board_index_tests {
use super::board_index_from_text;
@@ -1186,18 +1245,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
let mut board_status: Vec<crate::model::BoardHealth> = data
.hashboards
.iter()
.map(|b| {
let ok = match (b.active, b.working_chips) {
(Some(a), _) => a,
(None, Some(c)) => c > 0,
(None, None) => true,
};
if ok {
crate::model::BoardHealth::Ok
} else {
crate::model::BoardHealth::Fault
}
})
.map(|b| board_health(b.active, b.working_chips, is_mining || hashrate_ths > 0.0))
.collect();
if let Some(exp) = data.expected_hashboards {
while board_status.len() < exp as usize {
@@ -1229,6 +1277,8 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.unwrap_or_default(),
pic_present,
write_locked,
// asic-rs identified this miner, so it is not running Alkane OS.
alkane_board: None,
errors,
faults,
model,
@@ -1917,13 +1967,25 @@ pub fn start_refresh(ips: Vec<String>) -> RefreshHandle {
ok += 1;
RefreshMsg::Row(to_row(&*miner).await)
}
Ok(None) => RefreshMsg::Failed {
ip: ip_s,
detail: "offline".to_string(),
Ok(None) => match crate::alkane_detect::detect(ip).await {
Some(row) => {
ok += 1;
RefreshMsg::Row(row)
}
None => RefreshMsg::Failed {
ip: ip_s,
detail: "offline".to_string(),
},
},
Err(e) => RefreshMsg::Failed {
ip: ip_s,
detail: format!("{e}"),
Err(e) => match crate::alkane_detect::detect(ip).await {
Some(row) => {
ok += 1;
RefreshMsg::Row(row)
}
None => RefreshMsg::Failed {
ip: ip_s,
detail: format!("{e}"),
},
},
},
};
@@ -2615,3 +2677,41 @@ mod tests {
std::env::remove_var(FAKE_SCAN_ENV);
}
}
#[cfg(test)]
mod live_scan_tests {
/// Run the real fleet scan over a range and print, per row found, what the
/// alkane-os menu would offer:
/// `ALKANE_TEST_SCAN_RANGE=10.255.1.0/24 cargo test -p alkane-gui live_scan -- --ignored --nocapture`
#[test]
#[ignore = "needs a reachable miner network (ALKANE_TEST_SCAN_RANGE)"]
fn live_scan() {
let Ok(range) = std::env::var("ALKANE_TEST_SCAN_RANGE") else {
return;
};
let handle = super::start_scan(vec![range], 10);
let mut rows = std::collections::BTreeMap::new();
while let Ok(msg) = handle.rx.recv() {
match msg {
super::ScanMsg::Row(row) => {
rows.insert(row.ip.clone(), row);
}
super::ScanMsg::Done(_) | super::ScanMsg::Failed(_) => break,
_ => {}
}
}
for row in rows.values() {
println!(
"{:<15} brand={:<10} model={:<12} fw={:<8} {:<8} board={:<10} install={} uninstall={}",
row.ip,
row.brand,
row.model,
row.firmware,
row.fw_version,
row.control_board,
crate::alkane_detect::install_supported(row),
crate::alkane_detect::is_alkane(row),
);
}
}
}
+477
View File
@@ -0,0 +1,477 @@
//! Install alkane-os onto a board on stock, and restore an alkane board to
//! stock, from the GUI - using the toolkit's own self-contained, network-only
//! engine (`alkane_flash::stock`), the same code the CLI drives. There is no
//! external helper and no runtime dependency on any other tool: the
//! stock-crossing method is compiled into this binary. This module drives that
//! engine on a background thread and reports progress.
//!
//! Both operations are DESTRUCTIVE (they reflash the control board) and run on a
//! background thread so the reboot/flash latency never blocks the wx event loop.
//! Results stream back over a channel, drained by the UI timer tick exactly like
//! restore.rs. The UI gates each behind a typed-FLASH confirmation.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
use alkane_artifacts::fetch::{self, ReleaseSource};
use alkane_flash::stock::{self, RestoreImages};
use alkane_flash::stock_firmware;
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)"),
(
"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";
pub fn is_supported_board(board: &str) -> bool {
SUPPORTED_BOARDS.iter().any(|(b, _)| *b == board)
}
/// Where the `.afw` to install comes from. `Release` is a scanned Gitea asset
/// (its filename and download URL), fetched on the worker thread so the download
/// never blocks the UI. `Local` is a file the operator picked with the Browse
/// button -- the same local-file install the CLI offers, now in the GUI too.
pub enum AfwSource {
Release { name: String, url: String },
Local(PathBuf),
}
impl AfwSource {
/// A short human label for the status line (the filename in both cases).
fn label(&self) -> String {
match self {
AfwSource::Release { name, .. } => name.clone(),
AfwSource::Local(p) => p
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| p.to_string_lossy().into_owned()),
}
}
}
/// Progress + results streamed from the background worker to the UI.
pub enum StockMsg {
Started,
/// A human-readable status line for the status bar (acquiring, verifying...).
Progress(String),
/// One board's outcome.
Result {
ip: String,
ok: bool,
detail: String,
},
Done,
}
pub struct StockHandle {
pub rx: Receiver<StockMsg>,
// Cancellation is honoured between boards; a UI stop control is not wired yet.
#[allow(dead_code)]
cancel: Arc<AtomicBool>,
}
impl StockHandle {
#[allow(dead_code)]
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
fn download_dir() -> PathBuf {
alkane_core::platform::config_path("downloads")
}
/// Install alkane-os onto the given boards (currently on stock), over the
/// network, via the compiled-in from-stock method. `board` is the target board
/// family (gates the `.afw`); `password`, if set, is passed in-process to the
/// method (never to the environment or an argument).
pub fn start_install(
ips: Vec<String>,
board: String,
source: AfwSource,
allow_unsigned: bool,
password: Option<String>,
is_update: bool,
) -> StockHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
if fake_scan_enabled() {
let _ = tx.send(StockMsg::Started);
let _ = tx.send(StockMsg::Progress(
"install (demo): no hardware touched".into(),
));
for ip in ips {
let _ = tx.send(StockMsg::Result {
ip,
ok: true,
detail: "installed alkane-os (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("install-from-stock".into())
.spawn(move || {
let _ = tx.send(StockMsg::Started);
// 1. Acquire the .afw: a local file is used in place; a release asset
// is downloaded on this worker thread (never blocking the UI).
let afw_path = match source {
AfwSource::Local(path) => {
let _ = tx.send(StockMsg::Progress(format!(
"using local {}...",
AfwSource::Local(path.clone()).label()
)));
if !path.is_file() {
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!("local .afw not found: {}", path.display()),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
path
}
AfwSource::Release { name, url } => {
let _ = tx.send(StockMsg::Progress("acquiring .afw...".into()));
match fetch::fetch_afw_url(
&ReleaseSource::alkane_os(),
&name,
&url,
&download_dir(),
) {
Ok(p) => p,
Err(e) => {
// One failure line per target so the UI clears its op-status.
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!("could not fetch .afw: {e}"),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
}
}
};
// 2. Verify + gate the bundle once (board/arch/bootloader + integrity).
let _ = tx.send(StockMsg::Progress("verifying .afw...".into()));
let verified = match verify_afw(
&afw_path,
&VerifyOptions {
allow_unsigned,
expect_board: Some(board.clone()),
},
) {
Ok(v) => v,
Err(e) => {
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!(".afw rejected: {e}"),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
};
if !is_supported_board(&verified.manifest.board) {
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!(
"{} is not a supported install target",
verified.manifest.board
),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
// An in-place Update must never rewrite the bootloader (review #1):
// refuse a tier-3 (bootloader-writing) bundle so the "BOOT.bin is
// never written" guarantee holds for an already-alkane board.
if is_update && verified.manifest.flash_plan().writes_uboot {
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: "update refused: this release reflashes the bootloader (tier 3); \
pick a tier-1/2 release or use Install"
.to_string(),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
// 3. Install onto each board via the network-only from-stock method.
for ip in ips {
if tc.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(StockMsg::Progress(format!(
"installing {} onto {ip} (from stock)...",
verified.manifest.board
)));
let (ok, detail) =
match stock::install_from_stock(&ip, &afw_path, &verified, password.as_deref())
{
Ok(()) => (
true,
"installed alkane-os (verify liveness over the network)".to_string(),
),
Err(e) => (false, format!("install 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 install worker thread".into(),
});
let _ = err_tx.send(StockMsg::Done);
}
StockHandle { rx, cancel }
}
/// Restore one board to genuine Bitmain stock using the user-supplied vendor
/// firmware package: parse it into the stock images and write them back over the
/// network. `password`, if given, is the board's alkane root credential.
fn restore_one(ip: &str, firmware: &Path, password: Option<&str>) -> (bool, String) {
let fw = match stock_firmware::parse(firmware) {
Ok(f) => f,
Err(e) => return (false, format!("firmware: {e}")),
};
// The device tree comes from the toolkit's per-board asset, not the package,
// so any genuine Bitmain firmware (OTA or SD) provides a usable kernel+rootfs.
let images = RestoreImages {
kernel: &fw.kernel,
rootfs: &fw.rootfs,
dtb: fw.dtb.as_deref(),
};
match stock::restore_to_stock(ip, &images, password) {
Ok(()) => (
true,
"restored to stock (verify independently it no longer answers as alkane)".to_string(),
),
Err(e) => (false, format!("restore failed: {e}")),
}
}
/// Restore the given alkane boards to genuine Bitmain stock, over the network,
/// by writing the stock images from `firmware` (a genuine vendor firmware
/// package) back to NAND. `password`, if set, is the board's alkane root
/// credential.
pub fn start_restore(ips: Vec<String>, firmware: PathBuf, 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 (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-to-stock".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 (network-only)..."
)));
let (ok, detail) = restore_one(&ip, &firmware, password.as_deref());
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 }
}
/// Whether a board holds a restorable on-board stock backup (network probe). A
/// quick, synchronous check the restore dialog uses to grey out the on-board
/// option when no backup is present. Any error reads as "not present".
pub fn onboard_backup_present(ip: &str, password: Option<&str>) -> bool {
if fake_scan_enabled() {
return true;
}
stock::onboard_stock_backup_present(ip, password).unwrap_or(false)
}
/// Restore the given alkane boards to genuine stock, over the network, from each
/// board's own on-board stock backup (no vendor firmware file). `password`, if
/// set, is the board's alkane root credential.
pub fn start_restore_onboard(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 from on-board backup (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-onboard".into())
.spawn(move || {
let _ = tx.send(StockMsg::Started);
let timeout = std::time::Duration::from_secs(300);
for ip in ips {
if tc.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(StockMsg::Progress(format!(
"restoring {ip} to stock from its on-board backup..."
)));
let (ok, detail) =
match stock::restore_from_onboard_backup(&ip, password.as_deref(), timeout) {
Ok(()) => (
true,
"restored to stock from on-board backup (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 }
}
/// 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 }
}
File diff suppressed because it is too large Load Diff
+115 -15
View File
@@ -1,7 +1,13 @@
# Installing and removing alkane-os
The CLI (`alkane-cli afw ...`) is the supported flashing path. In-app (GUI)
flashing is disabled while that path is reworked; it will call the same engine.
Two front-ends drive the same self-contained engine:
- The CLI (`alkane-cli afw ...`), documented below, is the scriptable path.
- The GUI (`alkane-toolkit`) can scan the fleet, then right-click a board to
install alkane-os onto it from stock or restore it to stock. See
"GUI (right-click install / uninstall)" at the end. (The GUI's older asic-rs
firmware-upload path stays disabled; these two actions use the compiled-in
network-only engine, the same one the CLI uses.)
## Compatible miners
@@ -38,34 +44,128 @@ on the command line, never stored by the toolkit.
Writing our first image onto a board that is still on genuine stock (past the
stock gates and getting root) is done by the toolkit itself, over the network.
The method is compiled into this binary; nothing else needs to be installed on
your machine. Add `--from-stock`:
The method is part of this binary; nothing else needs to be installed on your
machine. On first use it fetches a small set of per-board assets from our Gitea
(repo `blueflare/alkane-stock-assets`, release `zynq-7010-v1`) and caches them
locally, verifying each against a known SHA-256. That repo is public, so no token
is needed for the stock assets. The asset base URL can be overridden with
`ALKANE_STOCK_ASSETS_BASE`.
Add `--from-stock` (the token below is only to resolve `--latest` from the
private alkane-os release repo; a local `.afw` needs no token):
```
export ALKANE_RELEASE_TOKEN=<your-gitea-token>
alkane-cli afw install --latest --board zynq-7010 --host <miner-ip> \
--from-stock --confirm FLASH
```
The toolkit acquires and verifies the `.afw`, gates on compatibility, performs
the network-only stock-side install, then you verify the board came up as
alkane:
The toolkit acquires and verifies the `.afw`, gates on compatibility, fetches
and verifies its assets, performs the network-only stock-side install, then you
verify the board came up as alkane:
```
alkane-cli afw verify-live --host <miner-ip> --timeout 300
```
On Zynq (S17/S19 class) pass the `.afw` (or `--board zynq-7010`) and the board's
alkane root credential; the check needs the web page to carry the image marker
and SSH to report alkane with the installed kernel, and prints the running kernel
command line (on a NAND boot it is the board's U-Boot env bootargs):
```
alkane-cli afw verify-live path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --password-file <alkane-root-pw> --timeout 300
```
For a bench image that is not signed, add `--allow-unsigned`.
Without `--from-stock`, `install` performs a tier-2 update of a board already on
alkane: it writes the dtb (`/dev/mtd0 @ 0x1a00000`), the kernel
(`/dev/mtd0 @ 0x2000000`) and the rootfs (`/dev/mtd1`), holds a backup of each,
reads them back (md5), and never writes `/dev/mtd0` below `0x1a00000`
(BOOT.bin/FSBL/FPGA/U-Boot are preserved).
alkane, in place, over the network:
```
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --password-file <alkane-root-pw> --dry-run
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --password-file <alkane-root-pw> --confirm FLASH
```
On Zynq (S17/S19 class) the update refuses a board that is not running alkane.
Alkane does not expose the NAND boot regions to Linux (only the small
`stock-cfg` and `alkane-cfg` partitions), so the toolkit re-registers them
first, the same way a restore does. It saves each boot slot to `--backup-dir`
(default: the toolkit's `backups` directory) before any erase, then writes the
rootfs (absolute NAND `0x2800000`), dtb (`0x1a00000`) and kernel (`0x2000000`),
with the kernel and rootfs wrapped as the legacy uImages the board's stock
U-Boot boots, and reads each back (md5) before rebooting. Nothing below
`0x1a00000` (BOOT.bin: FSBL, FPGA bitstream, U-Boot) is ever written.
`afw preflight` runs the same checks read-only. `--no-reboot` skips the reboot.
## Remove (back to stock)
```
alkane-cli afw restore-stock --host <miner-ip> --confirm FLASH
alkane-cli afw restore-stock --host <miner-ip> \
--stock-firmware <genuine-Bitmain-firmware> \
--password-file <alkane-root-pw> --confirm FLASH
```
Returning an aftermarket board to genuine stock is also done by the toolkit
itself, over the network. You then verify independently that the board no longer
answers as alkane and presents its stock OS.
Returning an aftermarket board to genuine stock is done by the toolkit itself,
over the network. It writes the genuine Bitmain stock **kernel and rootfs** -
parsed from a vendor firmware file you supply with `--stock-firmware` (an OTA
update `.tar.gz` or an SD recovery `.zip` for the board) - back to NAND,
preserving BOOT.bin.
The one piece that is NOT in Bitmain's distributable firmware is the kernel
**device tree**: it is factory-provisioned and preserved by every vendor update,
so no OTA/SD package ships it. The toolkit supplies the correct per-board dtb
itself (fetched + verified from the public assets repo, so no token is needed)
and pairs it with the genuine kernel/rootfs. The board's alkane root credential
is given with `--password-file` (or
`ALKANE_BOARD_PASSWORD`/`ALKANE_BOARD_PASSWORD_FILE`).
After a restore the board returns to stock under its stock MAC and typically
takes a new DHCP lease, so it may not reappear on the same address; verify
independently that the board no longer answers as alkane and presents its stock
OS.
## GUI (right-click install / uninstall)
The GUI binary is `alkane-toolkit`. Launch it, let the scan list the fleet, then
right-click one or more boards. The scan finds boards running Alkane OS too
(Firmware column "Alkane"): they expose no cgminer socket or vendor web UI, so the
toolkit identifies them itself from the board's public read-only
`GET /api/identity` (alkane-os 0.1.2 and later; earlier images are found from
`/api/summary`). Each action below is offered only when it applies to every
selected board:
- "Install alkane OS..." - for a supported board (one alkane-os has an image
for; today the Zynq-7010 Antminer S17/S17 Pro/T17) that is not running Alkane
OS yet. Scans the alkane-os releases on Gitea, lets you pick one (newest first;
pre-releases are marked), optionally takes a board password and an "allow
unsigned .afw (bench)" toggle, then - when you click Install - downloads and
verifies the `.afw` and installs it onto each selected board over the network,
via the same compiled-in engine the CLI uses.
- "Update alkane OS..." - for a supported board already running Alkane OS: the
same release picker and confirmation; the board is updated in place (BOOT.bin
is never written).
- "Uninstall alkane OS (restore to stock)..." - for a board running Alkane OS:
takes the board's alkane root password and a genuine Bitmain firmware package,
then - when you click Restore - restores each selected board to genuine stock
over the network.
A stock board the scan identifies but cannot place on a supported control board
(or a mixed stock/Alkane selection) gets neither Install nor Update.
Progress and per-board results appear on the status bar; verify board state
independently afterwards (the GUI does not claim liveness on its own).
Release scanning reads the private `alkane-os` repo, so it needs a Gitea token.
A read-only token can be baked into the GUI at build time
(`ALKANE_EMBEDDED_TOKEN=<token>` when building), so the shipped binary scans
releases with no setup; otherwise set `ALKANE_RELEASE_TOKEN` (or `GITEA_TOKEN`)
in the environment before launching. The stock-asset fetch needs no token (that
repo is public), so install-from-stock and restore-to-stock work without one -
only the release picker needs it.
Runtime dependencies (Linux): the GUI links wxWidgets 3.2 (wxGTK) and GTK 3, so
the target machine needs `libwxgtk3.2-1` and `libgtk-3-0` installed.
@@ -0,0 +1,53 @@
Subject: [PATCH 0011] Build on wxWidgets 3.2: version-guard the 3.3 appearance API and link GTK libs
diff -ruN a/build.rs b/build.rs
--- a/build.rs
+++ b/build.rs
@@ -309,6 +309,25 @@
for f in gtk_cflags.split_whitespace() {
build.flag(f);
}
+ // ...and GTK's own shared libraries at link time. `wx-config --libs`
+ // lists only the wx libraries, not the GTK libraries the widget bridge
+ // calls directly (gtk_*, g_*), so without this the final link fails with
+ // undefined GTK symbols. Best-effort: empty if pkg-config/gtk3-dev is
+ // missing, in which case the GTK-only bridge code was also compiled out.
+ let gtk_libs = Command::new("pkg-config")
+ .args(["--libs", "gtk+-3.0"])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+ for f in gtk_libs.split_whitespace() {
+ if let Some(lib) = f.strip_prefix("-l") {
+ println!("cargo:rustc-link-lib={}", lib);
+ } else if let Some(path) = f.strip_prefix("-L") {
+ println!("cargo:rustc-link-search=native={}", path);
+ }
+ }
}
if is_windows() {
// Ship one self-contained .exe: link the C++ runtime statically rather
diff -ruN a/cpp_src/wxbridge.cpp b/cpp_src/wxbridge.cpp
--- a/cpp_src/wxbridge.cpp
+++ b/cpp_src/wxbridge.cpp
@@ -375,6 +375,10 @@
// then returns CannotChange). System follows the desktop: the GTK theme's
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
+ // The explicit appearance API (wxApp::Appearance / SetAppearance /
+ // MSWEnableDarkMode) only exists in wxWidgets >= 3.3. On 3.2.x the GTK/Win
+ // system theme is still followed; we just cannot force it via ALKANE_APPEARANCE.
+#if wxCHECK_VERSION(3, 3, 0)
{
wxString pref;
wxGetEnv("ALKANE_APPEARANCE", &pref);
@@ -394,6 +398,7 @@
wxTheApp->SetAppearance(appearance);
#endif
}
+#endif
wxTheApp->OnInit();
#ifdef __WINDOWS__
@@ -0,0 +1,17 @@
Subject: [PATCH 0011] macOS self-test snapshot includes the window background
--- a/cpp_src/osx_native.mm
+++ b/cpp_src/osx_native.mm
@@ -46,7 +46,11 @@
wxMilliSleep(30);
}
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
- NSView* view = [nsw contentView];
+ // The content view's superview (the window's frame view) also draws the
+ // window background and title bar. The content view alone leaves every
+ // area the app's panels do not paint transparent, which read as white.
+ NSView* view = [[nsw contentView] superview];
+ if (!view) view = [nsw contentView];
if (!view) return 0;
NSRect rect = [view bounds];
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
+43
View File
@@ -0,0 +1,43 @@
Subject: [PATCH 0012] linux: word-wrapping multiline text control
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -890,6 +890,15 @@
wxDefaultPosition, wxSize(-1, -1), style);
}
+// A multiline text control that word-wraps at the control's width instead of
+// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
+// report box, where long lines should wrap rather than run off the edge.
+void* wxbr_text_ctrl_wrap(void* parent) {
+ return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
+ wxDefaultPosition, wxSize(-1, -1),
+ wxTE_MULTILINE | wxTE_BESTWRAP);
+}
+
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
// entry so a saved password is never rendered in the clear (round 18 #12).
void* wxbr_text_ctrl_password(void* parent) {
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -41,6 +41,7 @@
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
+ pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
@@ -463,6 +464,12 @@
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
}
+ /// A multiline text control that word-wraps at its width (no horizontal
+ /// scroll), for prose entry such as the bug-report box.
+ pub fn text_ctrl_wrapped(parent: Widget) -> Widget {
+ Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) })
+ }
+
/// A single-line text control that masks its content (for password entry).
pub fn password_ctrl(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
+38
View File
@@ -0,0 +1,38 @@
Subject: [PATCH 0013] linux: Enable/disable (grey out) a control
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -945,6 +945,11 @@
((wxCheckBox*)win)->SetValue(v != 0);
}
+// Enable or disable (grey out) any window/control.
+void wxbr_enable(void* win, int on) {
+ ((wxWindow*)win)->Enable(on != 0);
+}
+
// ---- check list box ---------------------------------------------------------
void* wxbr_check_list_box(void* parent) {
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -49,6 +49,7 @@
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
+ pub fn wxbr_enable(win: *mut c_void, on: c_int);
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
pub fn wxbr_clb_clear(win: *mut c_void);
@@ -508,6 +509,11 @@
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
}
+ /// Enable or disable (grey out) this control.
+ pub fn set_enabled(&self, on: bool) {
+ unsafe { notsafe::wxbr_enable(self.0, on as c_int) }
+ }
+
pub fn check_list_box(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
}
+1
View File
@@ -29,6 +29,7 @@ later changes go in new patches.
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
| 0009 | macOS: wxOSX (universal static) through `wx-config`, logical sizes on Apple, clang compiler runtime for `@available` |
| 0010 | macOS table: native alternating rows instead of the unclipped custom-cell background fill (it hid neighbouring cells' text), theme-aware text colour, `osx_native.mm`, self-test window snapshot |
| 0011 | macOS self-test snapshot captures the window's frame view, so areas the app does not paint show the real window background instead of transparency |
History: the round 19 health-tooltip fix (GTK tip area converted from
bin-window to widget coordinates) used to be a separate patch on top of an
+19
View File
@@ -309,6 +309,25 @@ fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
for f in gtk_cflags.split_whitespace() {
build.flag(f);
}
// ...and GTK's own shared libraries at link time. `wx-config --libs`
// lists only the wx libraries, not the GTK libraries the widget bridge
// calls directly (gtk_*, g_*), so without this the final link fails with
// undefined GTK symbols. Best-effort: empty if pkg-config/gtk3-dev is
// missing, in which case the GTK-only bridge code was also compiled out.
let gtk_libs = Command::new("pkg-config")
.args(["--libs", "gtk+-3.0"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
for f in gtk_libs.split_whitespace() {
if let Some(lib) = f.strip_prefix("-l") {
println!("cargo:rustc-link-lib={}", lib);
} else if let Some(path) = f.strip_prefix("-L") {
println!("cargo:rustc-link-search=native={}", path);
}
}
}
if is_windows() {
// Ship one self-contained .exe: link the C++ runtime statically rather
+5 -1
View File
@@ -46,7 +46,11 @@ int wxbr_osx_snapshot(void* win, const char* path) {
wxMilliSleep(30);
}
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
NSView* view = [nsw contentView];
// The content view's superview (the window's frame view) also draws the
// window background and title bar. The content view alone leaves every
// area the app's panels do not paint transparent, which read as white.
NSView* view = [[nsw contentView] superview];
if (!view) view = [nsw contentView];
if (!view) return 0;
NSRect rect = [view bounds];
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
@@ -890,6 +890,15 @@ void* wxbr_text_ctrl(void* parent, int multiline) {
wxDefaultPosition, wxSize(-1, -1), style);
}
// A multiline text control that word-wraps at the control's width instead of
// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
// report box, where long lines should wrap rather than run off the edge.
void* wxbr_text_ctrl_wrap(void* parent) {
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
wxDefaultPosition, wxSize(-1, -1),
wxTE_MULTILINE | wxTE_BESTWRAP);
}
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
// entry so a saved password is never rendered in the clear (round 18 #12).
void* wxbr_text_ctrl_password(void* parent) {
@@ -936,6 +945,11 @@ void wxbr_check_box_set(void* win, int v) {
((wxCheckBox*)win)->SetValue(v != 0);
}
// Enable or disable (grey out) any window/control.
void wxbr_enable(void* win, int on) {
((wxWindow*)win)->Enable(on != 0);
}
// ---- check list box ---------------------------------------------------------
void* wxbr_check_list_box(void* parent) {
@@ -375,6 +375,10 @@ extern "C" {
// then returns CannotChange). System follows the desktop: the GTK theme's
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
// The explicit appearance API (wxApp::Appearance / SetAppearance /
// MSWEnableDarkMode) only exists in wxWidgets >= 3.3. On 3.2.x the GTK/Win
// system theme is still followed; we just cannot force it via ALKANE_APPEARANCE.
#if wxCHECK_VERSION(3, 3, 0)
{
wxString pref;
wxGetEnv("ALKANE_APPEARANCE", &pref);
@@ -394,6 +398,7 @@ extern "C" {
wxTheApp->SetAppearance(appearance);
#endif
}
#endif
wxTheApp->OnInit();
#ifdef __WINDOWS__
+13
View File
@@ -41,6 +41,7 @@ mod notsafe {
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
@@ -48,6 +49,7 @@ mod notsafe {
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
pub fn wxbr_enable(win: *mut c_void, on: c_int);
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
pub fn wxbr_clb_clear(win: *mut c_void);
@@ -463,6 +465,12 @@ impl Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
}
/// A multiline text control that word-wraps at its width (no horizontal
/// scroll), for prose entry such as the bug-report box.
pub fn text_ctrl_wrapped(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) })
}
/// A single-line text control that masks its content (for password entry).
pub fn password_ctrl(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
@@ -501,6 +509,11 @@ impl Widget {
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
}
/// Enable or disable (grey out) this control.
pub fn set_enabled(&self, on: bool) {
unsafe { notsafe::wxbr_enable(self.0, on as c_int) }
}
pub fn check_list_box(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
}
+2 -2
View File
@@ -15,8 +15,8 @@ services:
GITEA_URL: http://gitea:3000
GITEA_REPO: blueflare/alkane-toolkit
GITEA_TOKEN_FILE: /run/secrets/gitea_token
RATE_PER_IP: "5"
RATE_GLOBAL: "60"
RATE_PER_IP: "100"
RATE_GLOBAL: "300"
volumes:
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
networks: [proxy]
+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]}"