Compare commits

...
Author SHA1 Message Date
noahandClaude Opus 4.8 5b624c1910 test(gui): ALKANE_BENCH_FLOW -- full user flow incl. the scan step
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 26m13s
verify / verify-windows (pull_request) Successful in 20m39s
Adds a headless GUI-flow driver that exercises the same code a user's clicks
trigger, including the scan: scan -> (restore to stock if on alkane) -> scan ->
install -> scan -> verify the board serves the HTTP API and shows as alkane.

bench_sequence::scan_report runs the real scan::start_scan and prints how each
board classifies (brand/model/control-board/install/alkane); run_flow chains
the scan + restore + install with liveness verification. Wired as
ALKANE_BENCH_FLOW="<host> <afw> [scan-range]" in main.rs.

Per Noah's rule: test toolkit fixes by automating the real GUI flow including
scanning, not just the engine in isolation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 14:51:41 -06:00
noahandClaude Opus 4.8 16951b6c92 style(gui): de-clutter install + media dialogs (nominal labels, no tidbits)
Apply the presentation/documentation-review title directives to the install
and Installation-Media dialogs: short nominal labels (Release, Release repo,
Local .afw, Media type, Source, Target card, Control board), and delete
contextual tidbits and mechanism narration (the "Flash plan" checklist and its
afw_plan_text/install_plan_label, "This reflashes the control board...", "The
card is built as an image first...", the restated intro sentences). Essential
context moved to tooltips (repo URL formats, the unsigned-afw caveat, the
card-erase warning, the local-.afw override).

No behaviour change; the flash tier/overwrite detail still runs in the engine's
preflight, it is just not narrated in the dialog.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 14:29:46 -06:00
noahandClaude Opus 4.8 ea753c1756 feat(gui): full repo URL for install (incl GitHub forks) + stock-Antminer scan fallback
#5: the install dialog's release source now accepts a full repo URL (Gitea or
GitHub) or a bare owner/repo. ReleaseSource::from_url parses the host; GitHub
uses api.github.com with the GitHub releases path. Security: the gitea token is
attached ONLY for the trusted self-hosted gitea host -- never sent to GitHub or
any other host (public anonymous access), including the asset download
(ReleaseSource::for_asset_url). curl now sends a generic User-Agent (GitHub
requires one). Field default is the full gitea URL.

#3: a stock Antminer whose miner API (:4028) is down -- e.g. no hashboards --
is now found by its :80 "antMiner Configuration" vendor web UI
(detect_stock_antminer), shown as "Antminer / Stock (model unknown)". The
install context item is offered for such a board, and the install dialog gains a
control-board selector (SUPPORTED_BOARDS) so the operator picks the board when
the scan could not determine it; changing it re-filters the release picker.

Tests: from_url parsing (gitea/github/bare, token safety); the
unidentified-stock-Antminer predicate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 14:25:12 -06:00
noahandClaude Opus 4.8 080bebe050 fix(gui): verify install over SSH; smaller toolbar icons
- Install verify no longer false-fails on images that serve only SSH. The
  install worker now polls the target's SSH banner after writing (stock
  Antminers ship dropbear 2018/2019; any newer banner on the board we just
  installed to means alkane booted), independent of the HTTP /api/identity
  scan probe. The GUI's HTTP awaiting message is softened to make clear it is
  only about the row auto-refresh, not an install failure. Fixes the "installed
  but did not answer as alkane" seen on the A113D bench image (SSH-only, no
  HTTP API).
- Toolbar icons 22px -> 16px so they fit the control row.

Note: a minimal image without the HTTP API still will not appear in the scan
(the scan probe is HTTP); the proper fix is an A113D image that serves the
flare-ui/API (separate alkane-os/sdk work).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 14:14:59 -06:00
noahandClaude Opus 4.8 8cb6989000 feat(gui): compact icon toolbar + SD-card media button
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 22m53s
verify / verify-windows (pull_request) Successful in 20m10s
Reworks the fleet-view toolbar into icon buttons and adds a direct
Installation-Media entry point:

- New wx-rs bridge fn `wxbr_svg_button` (patch 0010): render a recoloured SVG
  into a clickable wxBitmapButton. Rust wrapper `Widget::svg_button`.
- Settings -> gear icon; its dropdown already carries Logs (ID_LOGS_OPEN), so
  the standalone Log toolbar button is removed (the inline log view + toggle
  are kept but no longer surfaced as a button).
- Bug report -> bug icon.
- New unified "Data" icon (database) with a dropdown: Presets, Filter, Columns,
  Export (the four former standalone buttons; items dispatched via on_menu_item).
- New "SD card" icon opens the Installation Media dialog without right-clicking
  a miner (ID_MEDIA_TOOLBAR -> build_install_media_dialog; defaults to the
  zynq-7010 board when nothing is selected).
- Four new Font-Awesome-style icons (gear/bug/database/sd-card), recoloured to
  the theme foreground via svg_recolored; tooltips name each button.

Native + Windows clippy clean, fmt clean, GUI self-test passes; icons verified
to rasterise correctly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 13:27:01 -06:00
noah 99cddbdf93 Merge remote-tracking branch 'origin/fix/a113d-install-menu' into feat/installation-media 2026-11-17 13:11:14 -06:00
noahandClaude Opus 4.8 3742f28e7d test(flash): gate sd_media host-tool tests to unix (fix Windows/Wine verify)
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 32m35s
verify / verify-windows (pull_request) Successful in 27m1s
The verify-windows gate runs the unit tests under Wine. The card-building
tests shell out to unix tools (sfdisk/mkfs.vfat/mtools/cpio/gzip); their
find_tool-based runtime skip sees those binaries in the shared container
filesystem and does NOT skip, but a Windows process under Wine cannot exec a
Linux ELF, so injects_install_hook_into_initramfs failed.

Card building is a unix-host operation, so cfg(unix) the four tool-invoking
tests and their helpers. On the Windows target they are not compiled (no Wine
exec, no dead-code warnings); the three pure tests (sanitize labels, script
targets the boot slots, rejects a bad package -- which errors before any tool)
still run everywhere. Native keeps all 7 sd_media tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 12:03:13 -06:00
noahandClaude Opus 4.8 dabe3ce846 docs: Installation Media (SD cards) -- feature, boards, GUI/CLI usage, safety
source / check (pull_request) Skipped
verify / verify-windows (pull_request) Failing after 19m51s
verify / verify (pull_request) Successful in 30m15s
Documents the sanctioned SD-media path alongside the network-only install:
stock-recovery, alkane run-from-SD, and alkane installer cards; Zynq-only
(A113D excluded, eMMC-only); GUI + CLI usage; erase/boot-region safety notes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 11:05:17 -06:00
noahandClaude Opus 4.8 3931dbb0f0 feat(gui): Installation Media window -- build SD cards from the right-click menu
Adds the headline "Installation Media (SD card)..." right-click action for
card-bootable boards (Zynq; gated by alkane_detect::media_supported, which
excludes the eMMC-only A113D).

- media_ops.rs: safe removable-device enumeration (lsblk -J; only removable /
  hotplug USB-or-mmc whole disks, never a system disk) and start_make_media, a
  background worker that builds the card image with alkane_flash::sd_media and
  optionally writes it to the chosen device, streaming StockMsg on the same
  channel the install/restore flows use (reuses stock_op + its drain).
- ui.rs: the dialog (build_install_media_dialog) -- choose kind (stock
  recovery / alkane run-from-SD / alkane installer), Browse an .afw or vendor
  package, allow-unsigned, pick a target SD device (index 0 = build an image
  file only) with Rescan, Create/Cancel -- plus the context item, dispatch,
  and apply_make_media_confirm.
- alkane_detect::media_supported; StockHandle::new so media_ops can build the
  handle.

GUI builds, native clippy -D warnings clean, headless self-test passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 11:04:28 -06:00
noahandClaude Opus 4.8 41303fcbad feat(cli): afw make-media -- build stock/alkane SD cards
`alkane-cli afw make-media` wraps the sd_media builders:
  --kind stock  --stock-package <zip|dir> --out card.img
  --kind alkane --mode simpleboot|installer --afw <f.afw> --out card.img
      [--allow-unsigned] [--write /dev/sdX --confirm WRITE]

Zynq-7010 only for now. A .zip stock package is unpacked to a temp dir; a
directory is used as-is. Writing to a real device requires --confirm WRITE.

Verified end-to-end: building a stock card from the genuine vendor S17
package yields a card image byte-identical in content/sizes to the hand-built
card that recovered the bench S17 on 2026-11-17.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 10:51:45 -06:00
noahandClaude Opus 4.8 b10bf04142 feat(flash): alkane simple-boot + installer SD card builders (Zynq)
Extends sd_media with the alkane card builders, reusing the afw payloads
(VerifiedAfw kernel/dtb/rootfs) and uimage::wrap:

- build_zynq_simpleboot_card: wrap the afw kernel/rootfs as a legacy-uImage
  side-load trio (uImage + raw dtb + uramdisk) so the stock U-Boot card-detect
  boots alkane from the card (nothing written to NAND).
- build_zynq_installer_card: boot an installer-OS (afw rootfs + an injected
  /etc/init.d/S99alkane-sd-install hook) that writes the alkane boot slots from
  the card bin/ into NAND (BOOT.bin at 0x0..0x1a00000 preserved), read-back
  verifies, and drives the red/green LEDs (GPIO 941/942) with a blink-done cue.
  Offsets mirror zynq_nand.
- build_installer_initramfs injects the hook into the afw rootfs cpio.gz.
- _from_parts variants take raw bytes so the builders unit-test without a
  VerifiedAfw.

7 sd_media tests pass. On-hardware behaviour of the installer hook is
validated on the bench S17 next.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 10:49:40 -06:00
noahandClaude Opus 4.8 0d9c0fb7c1 feat(flash): SD installation-media engine + stock-recovery card builder
New `sd_media` module: build bootable removable-media card *images* for
boards that boot from a card, root-free up to the final device write.

- `CardImage`: assemble a single-partition (MBR, FAT32 type 0x0c @ LBA 2048)
  card image as an ordinary file using sfdisk + mkfs.vfat + mtools
  (mcopy/mmd) -- no loopback mount, no root -- so the `.img` is fully
  inspectable and unit-testable without hardware. This is the exact card
  shape proven on the bench S17 (2026-11-17): stock U-Boot card-detects it
  and side-loads the flasher-OS trio with no boot-mode strap and no uEnv.txt.
- `build_stock_recovery_card`: codify the by-hand bench procedure -- replicate
  a genuine vendor SD-recovery package's layout (flasher-OS trio at the card
  root + `bin/` NAND payload) onto a card image. `locate_vendor_card` finds
  the layout inside an unpacked (possibly nested) vendor package.
- `write_image_to_device`: guarded, separate dd of a finished image to a block
  device (the only part that touches real hardware; caller confirms target).

Tests build a card from a synthetic vendor package and read it back with
mdir/mtype (skip cleanly if the host lacks the image toolchain).

First slice of the SD Installation-Media feature; alkane simple-boot and
installer card builders, the GUI window, and CLI parity follow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 10:36:43 -06:00
noahandClaude Opus 4.8 d574118314 fix(gui): offer alkane install for the stock A113D (AML C76) board
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 30m58s
verify / verify-windows (pull_request) Successful in 19m55s
The right-click "Install alkane OS..." item never appeared for a stock
Amlogic A113D (Antminer BHB42XXX). board_family(), which gates the menu
via install_supported(), recognized only the Xilinx/Zynq S17 control
board, so it returned None for the A113D and the menu offered nothing.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 16:15:53 -06:00
noah 8180f4ff80 Merge remote-tracking branch 'origin/main' into feat/readable-stock-install-a113d-rebase
verify / verify (pull_request) Failing after 3m19s
source / check (pull_request) Skipped
# Conflicts:
#	.gitea/workflows/verify.yml
2026-11-16 16:08:35 -06:00
noah 9155c55d4c ci: repoint toolkit verify/source/badge to alkane-ci; keep Pages on the trusted verifier (#54)
build-test-release / release (push) Skipped
build-test-release / windows (push) Failing after 35m1s
2026-11-16 15:07:14 -07:00
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
noahandClaude Opus 4.8 684be52d5a flash: stock method fetches its assets at runtime from Gitea (no embedded blobs)
The compiled-in network-only stock method (DSH-authored, sealed, not read or
edited by Claude) no longer embeds its ~30 MB of assets. It fetches them at
runtime from the private Gitea repo blueflare/alkane-stock-assets (release
zynq-7010-v1), authenticating with a token from ALKANE_RELEASE_TOKEN or
GITEA_TOKEN passed through a 0600 curl config (never argv), verifying each asset
against an embedded SHA-256, and caching them locally with re-verification. The
base URL is overridable via ALKANE_STOCK_ASSETS_BASE.

Result: the CLI binary drops from 31.7 MB to ~1.0 MB and the repo carries no
vendor blobs. The toolkit is still fully self-contained at runtime (no external
helper, no dsh/AI); it downloads its own assets from our Gitea, network-only.

Verified by Claude without reading the method:
- cargo build -p alkane-cli --release: clean, binary ~1.0 MB.
- cargo test -p alkane-flash: 64 passed.
- Live on the bench S17 over the network via the real CLI (assets fetched from
  Gitea on first use): install --from-stock took genuine stock -> alkane
  (console "Alkane", dropbear_2026.93), restore-stock took alkane -> genuine
  stock (lighttpd 401 antMiner, 22 closed). Board left on stock.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-11 11:19:45 -06:00
noahandClaude Opus 4.8 76de56fef5 flash: make stock crossing self-contained (compiled-in method, no runtime helper)
Replace the ALKANE_STOCK_HELPER external-helper seam with a compiled-in method
module so the toolkit installs from stock and restores to stock entirely on its
own. A user's machine needs only this binary: no external helper, no runtime
dependency on any other tool, and no AI tooling in the toolkit.

- stock.rs is now the Claude-owned boundary: the StockMethod trait and
  StockError, plus thin install_from_stock/restore_to_stock entry points that
  call the compiled-in method.
- stock_method.rs holds the network-only method bodies. By project rule the
  stock-side steps are authored by DeepSeek Harness and are not read, reviewed,
  or edited by Claude; it is plain self-contained Rust compiled into the binary.
  Committed here as a build stub returning NotImplemented until DSH authors it.
- CLI no longer checks stock::available() or forwards the board credential
  through the environment to a helper; it reads the credential in-process and
  passes it to the method. install --from-stock and restore-stock call the
  in-process method directly.
- docs/install.md drops the ALKANE_STOCK_HELPER env instructions.

The install-from-stock path is network-only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-11 09:55:37 -06:00
noahandClaude Opus 4.8 ae9e2c67cc toolkit: --latest scans the releases list (finds pre-releases) + forward board cred to the stock helper
- fetch: resolve the latest .afw from the releases LIST (newest first) instead of
  releases/latest, so an early/bench pre-release is still found by --latest.
- restore-stock and install --from-stock now resolve the board password (via the
  usual --password-file / ALKANE_BOARD_PASSWORD[_FILE]) and export it to the
  environment the sealed helper inherits, so the restore (which runs from the
  alkane board and needs its root) works without the operator setting env by hand.

Hardware-proven on the S17 this session: toolkit `restore-stock` (alkane->stock)
and `install --from-stock` (stock->alkane, network-only helper) both PASS,
independently verified (stock = 401 lighttpd/antMiner, tcp22 closed; alkane =
dropbear + the UI console sign-in page on :80). Builds clean, tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-11 09:34:44 -06:00
noahandClaude Opus 4.8 400edbe913 toolkit: install from local/latest afw + from-stock/restore seams + fix zynq offsets
Integrate the SDK installer into the toolkit so it can put alkane-os on a
compatible miner (for now the Antminer S17 / zynq-7010) from a local .afw or an
auto-pulled latest release, and remove it (back to stock). Release host is the
self-hosted Gitea (GitHub is retired).

- FIX (brick risk): boards/zynq.rs carried the superseded stage-2 offsets
  (BOOTBIN_PRESERVE 0x2200000, kernel 0x2200000, dtb 0x2700000). Corrected to the
  live S17 / SDK-plan layout: BOOT.bin floor 0x1a00000, dtb 0x1a00000, kernel
  0x2000000 (slot 0x800000), rootfs mtd1. The tier-2 update now writes the right
  slots; test updated to the new ceiling.
- alkane-artifacts/fetch.rs: resolve and download the latest .afw for a board
  from Gitea releases/latest (curl + serde_json), token read from
  ALKANE_RELEASE_TOKEN/GITEA_TOKEN at run time and passed via a 0600 curl config,
  never argv, never stored.
- alkane-flash/stock.rs: the seam to the sealed, DSH-owned stock-side methods
  (install-from-stock, restore-to-stock). Interface only - an external
  ALKANE_STOCK_HELPER the toolkit invokes and then verifies the board itself; the
  method is never embedded, read, or reviewed here.
- alkane-cli: new `afw compat` (shows supported boards), `afw fetch-latest`,
  `afw install --latest [--board] [--from-stock]`, and `afw restore-stock`. The
  install/restore commands gate on a supported board. --from-stock routes the
  first install through the sealed helper; the default install path is the
  tier-2 update of a board already on alkane.
- docs/install.md documents the flow and the two env seams.

alkane-artifacts + alkane-flash + alkane-cli build clean, 71 tests pass, the new
files are clippy-clean (the one type_complexity warning is pre-existing in
afw.rs, untouched). No emojis.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-10 22:12:47 -06:00
noahandClaude Opus 4.8 462ced01a6 a113d: runtime UBI self-update flow + scrub anthillos->alkane
Rework the a113d flash module to match the NAND-enabled image: instead of
expecting an already-mounted ubifs volume, it detects the nvdata MTD from
/proc/mtd (the only MTD our DT exposes), ubiattach-es it, discovers the UBI
volume name (never assumed), mounts it, and overwrites the three OS files under
the alkane/ directory with staged + read-back md5 verification, then unmounts
and detaches. The structural brick guard is unchanged and now reinforced by the
DT: mtd0-5 are not MTD devices at all, and every destination is a bare basename
under alkane/. Renamed the directory anthillos -> alkane throughout (receipt
reports the discovered volume). New unit test for the /proc/mtd nvdata parse;
full flash suite 56 green.

NOTE: the live attach/mount/write flow is not yet hardware-validated - it needs
a NAND-enabled a113d image staged once via the stock/dsh path to test against.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
2026-11-06 23:02:55 -06:00
noahandClaude Opus 4.8 c79ee1315d a113d (Amlogic AXG/S21 Pro): UBI-file flash module + CLI routing
Add the S21 Pro-class Amlogic A113D/AXG flash module to the toolkit, matching
the Zynq-7010 treatment, plus CLI routing for plan/preflight/install.

- crates/alkane-flash/src/boards/a113d.rs: A113dPlan::from_afw validates the
  verified manifest (a113d, arm64, preserve, no fip/spl/tpl/u-boot member,
  exactly kernel/dtb/rootfs with arm64-image/fdt/uimage formats, per-image
  ceilings and total <= nvdata, plus independent magic checks and a
  defense-in-depth refusal of any non-nvdata partition carrying an image).
  The installer is file-only: it resolves the anthillos/ directory on a
  mounted ubifs volume and copies the three files there with staged + read-back
  md5 verification. The brick guard is structural - there is no flash_erase,
  nandwrite or dd-to-/dev/mtd anywhere in the module, so the FIP (mtd0/1) and
  stock boot (mtd4) and mtd2/3/5 can never be touched; every destination is
  checked to be a bare basename.
- crates/alkane-flash/src/boards/mod.rs: register the module.
- crates/alkane-cli/src/main.rs: route a113d bundles through afw
  plan/preflight/install.
- crates/alkane-artifacts/src/afw.rs: correct the a113d / a113d-s21pro board
  profile from armv7 to arm64 (the A113D/AXG is an arm64 SoC).

8 new a113d unit tests; full suite: 55 alkane-flash, 12 alkane-artifacts, all
pass. End-to-end verified: make-afw.sh -> check-afw.py -> alkane-cli afw plan
on a stub a113d bundle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
2026-11-06 21:02:06 -06:00
noahandClaude Opus 4.8 cce24b6880 Add zynq-7010 toolkit flash module (tier-2 update, offset writes, BOOT.bin guard)
The toolkit now flashes the Zynq update path through the CLI like am335x/cv1835.
- boards/zynq.rs: ZynqPlan::from_afw (validates the zynq-7010 .afw: armv7, preserve,
  the kernel/dtb/rootfs image set, zimage/fdt/cpio-gzip formats, size ceilings,
  rejects any bootloader/spl/BOOT.bin member and a non-zImage kernel), preflight
  (alkane source, root, flash tools, mtd0/mtd1, BOOT.bin-preserve guard), install
  (OFFSET-AWARE: nanddump/flash_erase/nandwrite --start at the device-relative
  slot offset - kernel 0x2200000, dtb 0x2700000 in /dev/mtd0, rootfs in /dev/mtd1
  - with per-region backup + md5 readback), and a hard guard that refuses any
  /dev/mtd0 write below BOOTBIN_PRESERVE so BOOT.bin can never be clobbered.
- alkane-artifacts: add the strict 'zimage' image format (magic 0x016f2818 at 0x24).
- alkane-cli: route zynq-7010 through afw plan/preflight/install.
- 6 module tests (good plan, non-zImage, oversize, bootloader member, wrong
  board/arch, every-mtd0-target-above-BOOT.bin). Full flash suite 47 green,
  artifacts green; the real bundle renders its plan through the CLI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
2026-11-06 20:13:38 -06:00
noahandClaude Opus 4.8 b1316b2bd9 Fix from-stock preflight: recognize AM335x stock, size-only mtd-map, honest dry-run targets
Three fixes found running the real tier-3 preflight against the stock .64 board:
- preflight fingerprint ended in 'ls <our release files>' which exits 1 on a stock
  board (none exist), failing the whole command; append '|| true'.
- classify() only knew the Amlogic stock kernel (4.9.38); the AM335x stock is
  3.8.13+ with an Antminer model line - recognize both so source-os matches the
  plan's stock-bitmain.
- the mtd-map check compared the vendor label (spl/u-boot/...) to the mtdN device
  name and so always failed on real hardware; validate live geometry by index+size
  against the plan's partitions instead (labels are board-specific, not in our map).
- dry-run message now lists the real write targets from the plan (was a hard-coded
  'mtd8, mtd6 and mtd7' that omitted mtd4 on tier 3).

Preflight + dry-run now PASS against the live stock board (all 10 checks). Unit
suite still 41 green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
2026-11-06 08:35:39 -06:00
noahandClaude Opus 4.8 9f6eccc5ac Add am335x-stock (tier-3) from-stock flash support to the toolkit
The am335x flash module now selects a per-tier Profile from the bundle's board:
tier 2 (am335x, preserve) or tier 3 (am335x-stock, include). The byte-write
engine, preflight and readback are shared; only the policy, preserved set,
12-partition map (mtd4 becomes a write target) and image list differ.

- boards/am335x.rs: Profile/profile_for/owns_board; MTD_MAP_STOCK (mtd4 writable,
  kernel at write_order 4 so U-Boot lands first); from_afw accepts am335x-stock,
  permits exactly the u-boot bootloader member, still rejects any SPL member and
  a u-boot member on tier 2; check_uimage expects firmware type 5 for u-boot;
  the plan carries its board + preserved set; render is tier-aware.
- restore() takes the preserved set per profile; SPL copies (mtd0-3) are never a
  restore target on any tier; mtd4 is restorable on tier 3.
- alkane-cli: route am335x-stock to the module (plan/preflight/install); restore
  is profile-driven and adds --held-uboot (mtd4) for the from-stock set.
- alkane-artifacts: board_profile knows am335x-stock (arm, include).
- tests: tier-3 from_afw acceptance (4 targets, U-Boot before kernel, mtd4 not
  preserved), wrong-U-Boot-type and SPL-write-target rejection, and a tier-3
  restore test (mtd4 allowed, SPL refused). Full flash suite 41 green; tier-2 and
  cv1835 unchanged. The real bundle parses and verifies through the CLI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
2026-11-05 21:51:29 -06:00
noah 4d1adeb05e Install AM335x mtd7/mtd8 over SSH with held backups 2026-11-04 17:03:14 -06:00
noahandDeepSeek Harness 628c0630a5 Install .afw OS bundles on CV1835 over the network
Parse and verify the fixed-order .afw container, add the CV1835 board
module and an SSH transport with the stock update-daemon root stage, a
read-only preflight, a held p1 backup, whole-partition read-back, live
verification and network restore. Add the headless afw CLI and offline
fixtures for good, tampered, wrong-board, truncated, traversal and
oversize bundles.

Co-Authored-By: DeepSeek Harness <noreply@deepseek.com>
2026-11-04 14:31:35 -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 3d1fd36811 Merge pull request 'Fix macOS table cells hiding their text; Bug report button and report relay' (#26) from macos-table-and-bug-report into main
build-test-release / windows (push) Successful in 5m30s
build-test-release / release (push) Successful in 13m53s
2026-11-04 10:20:14 -07:00
noahandClaude Opus 5.5 7f2ea8a8dc Manual: reporting a problem with the Bug report button
verify / verify (pull_request) Successful in 7m39s
source / check (pull_request) Skipped
verify / verify-windows (pull_request) Successful in 5m30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
2026-11-04 11:04:29 -06:00
noahandClaude Opus 5.5 b26f389460 Report relay: files the app's bug reports as Gitea issues
tools/report-relay is a dependency-free Python service. It takes the
JSON the app's Bug report button sends, validates it (type, text,
context and log sizes), scrubs the log a second time, rate-limits (5
per client IP and 60 in all per hour, 4 in flight), neutralises
@mentions, and files one issue in blueflare/alkane-toolkit with the
labels bug/ui/feature and from-app. It stores nothing and logs one
line per report without its text.

It runs on the Gitea host behind the shared nginx at
https://gitea.bluefla.re/alkane-report/ as the scoped alkane-reporter
bot (team alkane-reporters: issues write, code read, alkane-toolkit
only). See tools/report-relay/README.md. Its tests run in verify's
unit-test step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
2026-11-04 11:04:15 -06:00
noahandClaude Opus 5.5 b46f15b340 Bug report button: file bugs and feature requests from the app
A Bug report button between Export and Settings opens a dialog: a type
(Bug, UI change, Feature request), one text box whose first line
becomes the issue title, and "Include the recent activity log
(passwords removed)", ticked by default. Send posts the report to the
report relay (next commit), which files it as an issue in
blueflare/alkane-toolkit. The dialog then shows the issue number, and
Open issue opens it, or shows why the report was not sent with the text
kept.

The app holds no token. A report carries the app version, platform, OS
version, appearance, language and window size, plus the newest 80 log
lines (at most 16 KiB). Before the log leaves the machine,
bug_report::scrub removes values of password/token/secret-like names,
Authorization and Cookie headers, URL passwords and PEM private keys.
The request goes through the system curl, as the other HTTP actions
do. ALKANE_REPORT_URL overrides the relay address for testing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
2026-11-04 10:59:02 -06:00
noahandClaude Opus 5.5 c9d32f9793 Fix macOS table cells hiding their text; add a self-test snapshot
On macOS several table columns showed no values until a row was
clicked. wxOSX draws custom cells without clipping to the cell, and the
segment renderer paints its zebra background over an oversized rectangle
(a column width either side, 40 px up and down) that GTK and MSW clip
to the cell. On the Mac each cell's fill painted over its neighbours.
Selected rows skip the fill, so their text came back.

On macOS the zebra is now the table's native alternating rows. AppKit
paints them under every cell in the theme's colours, and no row
carries a background attribute, so the renderer never fills. Plain
segment text uses the theme-aware list text colour instead of the
control's foreground colour.

To check rendering without screen-recording permission, the self-test
takes ALKANE_SNAPSHOT=path (macOS) and writes a PNG of the window as
the app draws it (osx_native.mm: cacheDisplayInRect). Before/after
snapshots on the M1 confirm the fix in light and dark appearance.

wx-rs patch 0010. Also folds in PR #24 (build-gui-macos without
--locked).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
2026-11-04 10:40:43 -06:00
noahandClaude Opus 5.5 5cf9d44d7e build-gui-macos: build like CI, without --locked
A release sets the crate version first, which changes the workspace
entries in Cargo.lock; --locked then refuses to build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:37:31 -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
72 changed files with 22820 additions and 89 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:
+3 -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:
@@ -159,6 +159,7 @@ jobs:
run: |
cargo test -p alkane-gui --offline
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
python3 tools/report-relay/test_relay.py
- name: Microbenchmarks
if: steps.surface.outputs.surface == 'full'
@@ -201,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
+7
View File
@@ -40,6 +40,8 @@ name = "alkane-artifacts"
version = "0.1.0"
dependencies = [
"alkane-core",
"serde",
"serde_json",
"sha2",
"thiserror",
]
@@ -50,6 +52,8 @@ version = "0.1.0"
dependencies = [
"alkane-artifacts",
"alkane-core",
"alkane-flash",
"serde_json",
]
[[package]]
@@ -74,6 +78,7 @@ version = "0.1.0"
dependencies = [
"alkane-artifacts",
"alkane-core",
"serde_json",
"sha2",
"tempfile",
"thiserror",
@@ -84,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",
+1
View File
@@ -19,6 +19,7 @@ license = "MIT"
thiserror = "2"
serde = { version = "1", features = ["derive"] }
sha2 = "0.10"
serde_json = "1"
# Release binary: small, self-contained, and fast enough for a fleet GUI whose
# hot path is network I/O, not CPU (round 18 #12). opt-level "s" + fat LTO +
+44
View File
@@ -47,6 +47,50 @@ and Intel, macOS 11 or later; see [docs/macos.md](docs/macos.md).
Discovery is read-only. Control and restore actions change miners. Check the
selected devices before applying them.
## Headless .afw install (CV1835 and AM335x)
`alkane-cli` is the headless engine; the GUI uses the same engine. A verified
`.afw` is a full OS bundle for exactly one board. The CV1835 installer writes
only `/dev/mmcblk0p1` over SSH, holds the current p1 first, reads the whole
partition back, and reboots only after the read-back matches.
The AM335x installer writes mtd8 (type-3 ramdisk), mtd6 (dtb) and mtd7
(legacy kernel uImage) with `flash_erase` + `nandwrite`. It never touches
mtd0-5 (SPL/U-Boot/bootenv), holds a backup of each target before writing it,
and reads every target back before reboot. Its `verify-live` checks SSH
(kernel string), the HTTP marker on port 80, the API on port 4028, and the
eth0 DHCP lease.
```sh
alkane-cli afw verify BUNDLE.afw --allow-unsigned
alkane-cli afw plan BUNDLE.afw --host 10.255.1.167
alkane-cli afw preflight BUNDLE.afw --host 10.255.1.167
alkane-cli afw install BUNDLE.afw --host 10.255.1.167 --dry-run
alkane-cli afw install BUNDLE.afw --host 10.255.1.167 --confirm FLASH
alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.167
alkane-cli afw restore --host 10.255.1.167 --held-backup p1.img --confirm FLASH
```
For AM335x the same subcommands infer the board from the bundle; restore names
the three held copies explicitly:
```sh
alkane-cli afw plan BUNDLE.afw --host 10.255.1.64
alkane-cli afw preflight BUNDLE.afw --host 10.255.1.64
alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --dry-run
alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --confirm FLASH
alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.64 --timeout 300
alkane-cli afw restore --board am335x --host 10.255.1.64 \
--held-backup mtd8.img --held-kernel mtd7.img --held-dtb mtd6.img --confirm FLASH
```
On stock Bitmain CV1835 the SSH login is the unprivileged `miner` account; the
toolkit obtains root through the stock update-daemon loopback channel, not a
serial console. Credentials come only from `ALKANE_BOARD_PASSWORD` or
`ALKANE_BOARD_PASSWORD_FILE`, or from `--password-file` / `--identity-file`.
No credential value is printed. `--allow-unsigned` is bench-only; site use
needs an Ed25519-signed bundle.
## Development
```sh
+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"],
+2
View File
@@ -6,5 +6,7 @@ license.workspace = true
[dependencies]
alkane-core = { path = "../alkane-core" }
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
File diff suppressed because it is too large Load Diff
+691
View File
@@ -0,0 +1,691 @@
// SPDX-License-Identifier: MIT
//! Fetch the latest alkane-os `.afw` release from a Gitea repository.
//!
//! GitHub is retired for this project; releases live on the self-hosted Gitea.
//! This resolves `releases/latest`, picks the `.afw` asset for a board, and
//! downloads it so the normal verify -> plan -> preflight -> install flow runs on
//! it exactly as it would on a local file. TLS is required, so this shells out to
//! `curl` (as the GUI already does) rather than the plaintext TCP path used for
//! liveness checks.
//!
//! 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.
//!
//! 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};
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}")]
Curl(String),
#[error("release metadata did not parse: {0}")]
Parse(String),
#[error("no .afw asset for board {0} in the latest release")]
NoAsset(String),
#[error("io: {0}")]
Io(String),
}
/// Where releases come from. Defaults to the alkane-os repo on the self-hosted
/// Gitea; a full repo URL on any Gitea or GitHub host is also accepted so an
/// operator can flash from their own fork.
pub struct ReleaseSource {
pub base_url: String,
pub owner: String,
pub repo: String,
pub token: Option<String>,
/// GitHub uses `api.github.com/repos/...` instead of a Gitea
/// `.../api/v1/repos/...` path.
pub github: bool,
}
/// The default self-hosted Gitea base (honoring `ALKANE_RELEASE_BASE`).
fn default_gitea_base() -> String {
std::env::var("ALKANE_RELEASE_BASE")
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "https://gitea.bluefla.re".to_string())
}
/// Resolve the token for the default self-hosted Gitea (never sent elsewhere).
fn gitea_token() -> Option<String> {
std::env::var("ALKANE_RELEASE_TOKEN")
.ok()
.or_else(|| std::env::var("GITEA_TOKEN").ok())
.filter(|t| !t.is_empty())
.or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty()))
}
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` on the default
/// self-hosted Gitea base, with the resolved Gitea token.
pub fn for_repo(owner: &str, repo: &str) -> Self {
Self {
base_url: default_gitea_base(),
owner: owner.to_string(),
repo: repo.to_string(),
token: gitea_token(),
github: false,
}
}
/// Parse a full repo URL (or a bare `owner/repo`) into a release source.
/// Supports any Gitea host and GitHub (`github.com`); a bare `owner/repo`
/// uses the default self-hosted Gitea. Accepts optional scheme, a trailing
/// `.git`, and trailing path noise (e.g. `/releases`).
///
/// The resolved Gitea token is attached ONLY when the host is the default
/// self-hosted Gitea, so the embedded admin token is never sent to GitHub or
/// any other host (those use anonymous access to public releases).
pub fn from_url(input: &str) -> Option<ReleaseSource> {
let s = input.trim().trim_end_matches('/');
if s.is_empty() {
return None;
}
let no_scheme = s
.strip_prefix("https://")
.or_else(|| s.strip_prefix("http://"))
.unwrap_or(s);
let parts: Vec<&str> = no_scheme.split('/').filter(|p| !p.is_empty()).collect();
// host present when the first segment looks like a hostname (has a dot).
let (host, owner, repo) = if parts.len() >= 3 && parts[0].contains('.') {
(Some(parts[0]), parts[1], parts[2])
} else if parts.len() == 2 && !parts[0].contains('.') {
(None, parts[0], parts[1])
} else {
return None;
};
let repo = repo.trim_end_matches(".git");
if owner.is_empty() || repo.is_empty() {
return None;
}
let default_host = default_gitea_base()
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_end_matches('/')
.to_string();
let src = match host {
Some("github.com") | Some("www.github.com") => ReleaseSource {
base_url: "https://api.github.com".to_string(),
owner: owner.to_string(),
repo: repo.to_string(),
token: None, // never send the gitea token to github
github: true,
},
Some(h) if h == default_host => ReleaseSource {
base_url: default_gitea_base(),
owner: owner.to_string(),
repo: repo.to_string(),
token: gitea_token(),
github: false,
},
Some(h) => ReleaseSource {
base_url: format!("https://{h}"),
owner: owner.to_string(),
repo: repo.to_string(),
token: None, // a different Gitea host: anonymous public access
github: false,
},
None => Self::for_repo(owner, repo),
};
Some(src)
}
/// A minimal source for downloading a release asset by its direct URL. The
/// gitea token is attached ONLY when the asset URL is on the trusted
/// self-hosted Gitea host; GitHub and other hosts get anonymous access, so
/// the embedded admin token is never sent off-host.
pub fn for_asset_url(url: &str) -> ReleaseSource {
let host = url
.trim_start_matches("https://")
.trim_start_matches("http://")
.split('/')
.next()
.unwrap_or("");
let default_host = default_gitea_base()
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_end_matches('/')
.to_string();
let token = if host == default_host {
gitea_token()
} else {
None
};
ReleaseSource {
base_url: format!("https://{host}"),
owner: String::new(),
repo: String::new(),
token,
github: host.eq_ignore_ascii_case("api.github.com")
|| host.eq_ignore_ascii_case("github.com"),
}
}
/// The releases list (newest first). Unlike `releases/latest`, this includes
/// pre-releases, so an early/bench channel is still found by `--latest`.
fn api_list(&self) -> String {
let base = self.base_url.trim_end_matches('/');
if self.github {
format!(
"{}/repos/{}/{}/releases?per_page=50",
base, self.owner, self.repo
)
} else {
format!(
"{}/api/v1/repos/{}/{}/releases?limit=50",
base, self.owner, self.repo
)
}
}
}
/// Find the first `.afw` asset for `board` across a newest-first list of
/// releases. Returns (name, url).
fn pick_asset(releases: &Value, board: &str) -> Option<(String, String)> {
let needle = format!("-{board}-");
for release in releases.as_array()? {
let Some(assets) = release.get("assets").and_then(Value::as_array) else {
continue;
};
for asset in assets {
let name = asset.get("name").and_then(Value::as_str).unwrap_or("");
if name.ends_with(".afw") && name.contains(&needle) {
if let Some(url) = asset.get("browser_download_url").and_then(Value::as_str) {
return Some((name.to_string(), url.to_string()));
}
}
}
}
None
}
/// A temp curl `--config` file carrying the auth header, removed on drop so the
/// token never lands in a process argument or a lingering file.
struct TokenConfig {
path: Option<PathBuf>,
}
impl TokenConfig {
fn new(token: &Option<String>) -> Result<Self, FetchError> {
let Some(token) = token else {
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"),
)?;
Ok(Self { path: Some(path) })
}
fn apply(&self, cmd: &mut Command) {
if let Some(path) = &self.path {
cmd.arg("--config").arg(path);
}
}
}
impl Drop for TokenConfig {
fn drop(&mut self) {
if let Some(path) = &self.path {
let _ = fs::remove_file(path);
}
}
}
#[cfg(unix)]
fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.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()))
}
#[cfg(not(unix))]
fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
fs::write(path, contents).map_err(|e| FetchError::Io(e.to_string()))
}
fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
let config = TokenConfig::new(&src.token)?;
let mut cmd = Command::new("curl");
// A generic User-Agent (GitHub's API rejects requests without one); never
// carries any operator/host detail.
cmd.arg("-fsSL").arg("-A").arg("alkane-toolkit");
cmd.arg("--max-time").arg("120");
config.apply(&mut cmd);
cmd.arg(url);
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
if !out.status.success() {
return Err(FetchError::Curl(format!(
"{} ({})",
String::from_utf8_lossy(&out.stderr).trim(),
out.status
)));
}
Ok(out.stdout)
}
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("-A")
.arg("alkane-toolkit")
.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()))?;
if !out.status.success() {
return Err(FetchError::Curl(format!(
"{} ({})",
String::from_utf8_lossy(&out.stderr).trim(),
out.status
)));
}
Ok(())
}
/// Resolve the latest release's `.afw` asset for `board`: returns (name, url).
/// 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()))?;
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> {
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);
curl_download(src, &url, &dest)?;
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::*;
#[test]
fn from_url_parses_gitea_github_and_bare() {
std::env::remove_var("ALKANE_RELEASE_BASE");
// Bare owner/repo -> default gitea.
let g = ReleaseSource::from_url("someone/alkane-os").unwrap();
assert_eq!(
(g.owner.as_str(), g.repo.as_str()),
("someone", "alkane-os")
);
assert!(
!g.github
&& g.api_list()
.contains("gitea.bluefla.re/api/v1/repos/someone/alkane-os")
);
// Full gitea URL on the default host keeps the token path + gitea API.
let gh = ReleaseSource::from_url("https://gitea.bluefla.re/blueflare/alkane-os").unwrap();
assert!(!gh.github && gh.api_list().contains("/api/v1/repos/blueflare/alkane-os"));
// GitHub URL -> api.github.com, github path, and NEVER a token.
let h = ReleaseSource::from_url("https://github.com/acme/alkane-os.git/releases").unwrap();
assert!(h.github);
assert!(
h.token.is_none(),
"must not attach the gitea token to github"
);
assert_eq!(
h.api_list(),
"https://api.github.com/repos/acme/alkane-os/releases?per_page=50"
);
// Another gitea host -> no token (not the trusted host), gitea path.
let other = ReleaseSource::from_url("https://git.example.org/u/r").unwrap();
assert!(!other.github && other.token.is_none());
assert!(other
.api_list()
.starts_with("https://git.example.org/api/v1/repos/u/r"));
// Asset download token only for the trusted host.
assert!(ReleaseSource::for_asset_url(
"https://github.com/acme/r/releases/download/v1/x.afw"
)
.token
.is_none());
assert!(ReleaseSource::from_url("").is_none());
assert!(ReleaseSource::from_url("justonepart").is_none());
}
#[test]
fn source_defaults_to_alkane_os_on_gitea() {
std::env::remove_var("ALKANE_RELEASE_BASE");
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().starts_with("https://gitea.bluefla.re"));
}
#[test]
fn pick_asset_takes_the_newest_matching_afw() {
// Newest-first list of releases; the board's .afw in the first release wins.
let releases = serde_json::json!([
{"tag_name": "v0.1.0-bench1", "assets": [
{"name": "SHA256SUMS", "browser_download_url": "u0"},
{"name": "alkane-os-0.1.0-am335x-arm.afw", "browser_download_url": "u1"},
{"name": "alkane-os-0.1.0-zynq-7010-armv7.afw", "browser_download_url": "u2"},
]},
{"tag_name": "v0.0.9", "assets": [
{"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, "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"));
}
}
+3
View File
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: MIT
//! Verify local firmware artifacts before an install path consumes them.
pub mod afw;
pub mod fetch;
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::fs::File;
+2
View File
@@ -7,3 +7,5 @@ license.workspace = true
[dependencies]
alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
alkane-flash = { path = "../alkane-flash" }
serde_json.workspace = true
File diff suppressed because it is too large Load Diff
+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
tempfile = "3"
+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}"));
}
}
+880
View File
@@ -0,0 +1,880 @@
// SPDX-License-Identifier: MIT
//! Amlogic A113D / AXG (Antminer S21 Pro-class) board module: tier-2 network
//! UPDATE of a board already running alkane. Our OS is staged as FILES in the
//! nvdata UBI volume: alkane/{vmlinux.bin, devicetree.dtb, uramdisk.image.gz}.
//! (The legacy vendor path name "anthillos" from AnthillOS is no longer used;
//! our own bootcmd loads from alkane/.)
//!
//! The running alkane image exposes ONLY the nvdata region as an MTD (the board
//! DT declares a single `nvdata` fixed-partition; the FIP bootloader and the
//! stock boot/recovery/misc/config regions are deliberately undeclared, so they
//! are never registered as MTD devices and cannot be written from Linux). This
//! module attaches UBI to that one nvdata MTD, mounts the UBIFS volume, and
//! overwrites the three files under alkane/. It performs no raw mtd0-5 write and
//! never changes the bootloader: the brick-sensitive regions are physically
//! unreachable.
//!
//! 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};
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 = "a113d";
pub const ARCH: &str = "arm64";
/// The UBI volume subdirectory our boot chain reads our OS files from. This is
/// alkane's own name; the board's `ourbootcmd` loads from here.
pub const ALKANE_DIR: &str = "alkane";
/// nvdata UBI usable size; the three files together must fit (0xB900000).
pub const NVDATA_USABLE: u64 = 0xB900000;
/// The only MTD partition our DT exposes. mtd0-5 (FIP + stock boot) are not
/// declared in the DT at all, so they are not MTD devices on a running image.
pub const NVDATA_LABEL: &str = "nvdata";
/// Authoritative file targets: (image, on-board basename, ceiling, format).
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a
/// new rootfs beside an old kernel (the kernel file lands last).
const TARGETS: [(&str, &str, u64, &str); 3] = [
("rootfs", "uramdisk.image.gz", 0x6000000, "uimage"),
("dtb", "devicetree.dtb", 0x100000, "fdt"),
("kernel", "vmlinux.bin", 0x4000000, "arm64-image"),
];
#[derive(Debug, Error)]
pub enum A113dPlanError {
#[error("bundle is for {0}, not a113d")]
WrongBoard(String),
#[error("bundle arch is {0}, a113d needs arm64")]
WrongArch(String),
#[error("a113d requires bootloader_policy preserve (the FIP is never written)")]
BootloaderPolicy,
#[error("a113d bundle carries a bootloader/spl/fip/tpl member: {0}")]
BootloaderMember(String),
#[error("manifest is not an OS payload")]
PayloadType,
#[error("manifest marker is empty")]
Marker,
#[error("a113d must install exactly kernel, dtb and rootfs")]
InstallCount,
#[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,
},
#[error("a113d {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
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")]
NotArm64 { image: String },
#[error("a113d {image} is not an FDT")]
NotFdt { image: String },
#[error("a113d {image} is not a legacy uImage")]
NotUimage { image: String },
#[error("a113d refuses: preserved partition {0} (mtd0-5) carries an image")]
PreservedCarriesImage(String),
#[error("a113d refuses an unsafe destination for {image}: {dest}")]
UnsafeDest { image: String, dest: String },
}
#[derive(Clone, Debug)]
pub struct A113dTarget {
pub image_name: String,
/// On-board basename inside the alkane directory (never a device path).
pub dest: String,
pub size: u64,
pub data: Vec<u8>,
pub expected_md5: String,
}
#[derive(Clone, Debug)]
pub struct A113dPlan {
pub targets: Vec<A113dTarget>,
pub marker: String,
pub kernel_version: String,
pub sdk_revision: String,
pub os_revision: String,
pub afw_sha256: String,
pub min_free_bytes: u64,
}
fn is_bootloaderish(image: &AfwImage) -> bool {
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
image.role == "bootloader"
|| lowered.contains("spl")
|| lowered.contains("u-boot")
|| lowered.contains("uboot")
|| lowered.contains("fip")
|| lowered.contains("tpl")
}
/// A destination is safe only as a bare basename (no separators, no traversal,
/// not a device path). This keeps every write inside the alkane/ directory.
fn is_safe_dest(dest: &str) -> bool {
!dest.is_empty()
&& !dest.contains('/')
&& !dest.contains("..")
&& !dest.starts_with("/dev/")
&& dest == dest.trim()
}
impl A113dPlan {
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, A113dPlanError> {
let manifest = &afw.manifest;
if manifest.board != BOARD {
return Err(A113dPlanError::WrongBoard(manifest.board.clone()));
}
if manifest.arch != ARCH {
return Err(A113dPlanError::WrongArch(manifest.arch.clone()));
}
if manifest.payload_type != "os" {
return Err(A113dPlanError::PayloadType);
}
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
return Err(A113dPlanError::BootloaderPolicy);
}
if manifest.marker.is_empty() {
return Err(A113dPlanError::Marker);
}
// FIP / bootloader members are never allowed - we reuse the board's.
for image in &manifest.images {
if is_bootloaderish(image) {
return Err(A113dPlanError::BootloaderMember(image.file.clone()));
}
}
// 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(),
));
}
}
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
if installs.len() != TARGETS.len() {
return Err(A113dPlanError::InstallCount);
}
let mut targets = Vec::with_capacity(TARGETS.len());
let mut total = 0u64;
for (image_name, dest, ceiling, expected_format) in TARGETS {
let image = manifest
.images
.iter()
.find(|i| i.name == image_name && i.install)
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
if image.format != expected_format {
return Err(A113dPlanError::ImageFormat {
image: image_name.to_owned(),
actual: image.format.clone(),
expected: expected_format,
});
}
if image.size > ceiling {
return Err(A113dPlanError::ImageTooLarge {
image: image_name.to_owned(),
size: image.size,
ceiling,
});
}
if !is_safe_dest(dest) {
return Err(A113dPlanError::UnsafeDest {
image: image_name.to_owned(),
dest: dest.to_owned(),
});
}
let data = afw
.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(),
});
}
}
"fdt" => {
if !(data.len() >= 4 && data[0..4] == [0xd0, 0x0d, 0xfe, 0xed]) {
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(),
});
}
}
_ => {}
}
total += image.size;
targets.push(A113dTarget {
image_name: image_name.to_owned(),
dest: dest.to_owned(),
size: image.size,
expected_md5: md5_hex(data),
data: data.to_vec(),
});
}
if total > NVDATA_USABLE {
return Err(A113dPlanError::OverNvdata {
total,
usable: NVDATA_USABLE,
});
}
Ok(Self {
targets,
marker: manifest.marker.clone(),
kernel_version: manifest.kernel_version.clone(),
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(
"tier 2 update: attach UBI to the nvdata MTD, mount it, and overwrite the OS files \
under alkane/; the FIP + stock boot/recovery/misc/config are not MTD devices at all, \
so no raw NAND write is possible\n",
);
out.push_str("image format kernel=arm64-image, dtb=fdt, rootfs=uimage\n");
for target in &self.targets {
out.push_str(&format!(
"write {} -> {ALKANE_DIR}/{} size {} B md5 {}\n",
target.image_name, target.dest, target.size, target.expected_md5
));
}
out.push_str(&format!(
"marker {} kernel {} sdk {} os {}",
self.marker,
self.kernel_version,
short(&self.sdk_revision),
short(&self.os_revision),
));
out
}
}
fn short(rev: &str) -> &str {
rev.get(..12).unwrap_or(rev)
}
#[derive(Debug, Error)]
pub enum A113dError {
#[error("preflight failed:\n{0}")]
Preflight(String),
#[error("--confirm FLASH is required to write")]
Confirm,
#[error("the running image exposes no '{0}' MTD; it needs a NAND-enabled a113d kernel")]
NoNvdataMtd(String),
#[error("could not attach UBI to the nvdata MTD / find its volume")]
UbiAttach,
#[error("could not mount the nvdata UBIFS volume")]
Mount,
#[error("refusing an unsafe destination: {0}")]
UnsafeDest(String),
#[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 A113dCheck {
pub name: String,
pub ok: bool,
pub detail: String,
}
#[derive(Clone, Debug)]
pub struct A113dPreflight {
pub host: String,
pub checks: Vec<A113dCheck>,
/// The nvdata MTD index (e.g. 0 for /dev/mtd0), when the running image
/// exposes it. Used for `ubiattach -m <index>`.
pub nvdata_mtd: Option<u32>,
}
impl A113dPreflight {
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
}
}
/// Parse /proc/mtd for a partition labelled "nvdata" and return its mtd index.
/// e.g. `mtd0: 0b900000 00020000 "nvdata"` -> Some(0).
fn parse_nvdata_mtd(proc_mtd: &str) -> Option<u32> {
for line in proc_mtd.lines() {
let line = line.trim();
if !line.starts_with("mtd") {
continue;
}
let (dev, rest) = line.split_once(':')?;
if rest.contains(&format!("\"{NVDATA_LABEL}\"")) {
return dev.trim_start_matches("mtd").parse::<u32>().ok();
}
}
None
}
pub fn preflight(
plan: &A113dPlan,
remote: &mut dyn Remote,
host: &str,
) -> Result<A113dPreflight, A113dError> {
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(A113dCheck {
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(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 \
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(A113dCheck {
name: "commands".to_owned(),
ok: missing.is_empty(),
detail: if missing.is_empty() {
"ubi/file tools present".to_owned()
} else {
format!("missing {}", missing.join(", "))
},
});
// The nvdata MTD must be exposed (NAND-enabled a113d kernel). If absent, the
// running image cannot self-update - it needs the DT with the nvdata
// fixed-partition. mtd0-5 are intentionally never exposed, so nvdata is the
// ONLY mtd this board should ever present.
let proc_mtd = String::from_utf8_lossy(
&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?,
)
.into_owned();
let nvdata_mtd = parse_nvdata_mtd(&proc_mtd);
checks.push(A113dCheck {
name: "nvdata-mtd".to_owned(),
ok: nvdata_mtd.is_some(),
detail: match nvdata_mtd {
Some(n) => format!("nvdata is /dev/mtd{n} (the only exposed MTD)"),
None => format!("no 'nvdata' MTD exposed: {}", proc_mtd.replace('\n', " ")),
},
});
// Every destination is a bare basename - the structural brick guard.
let dests_safe = plan.targets.iter().all(|t| is_safe_dest(&t.dest));
checks.push(A113dCheck {
name: "file-only".to_owned(),
ok: dests_safe,
detail: format!("all writes are files under {ALKANE_DIR}/ on the nvdata UBI"),
});
Ok(A113dPreflight {
host: host.to_owned(),
checks,
nvdata_mtd,
})
}
#[derive(Clone, Debug)]
pub struct A113dInstallOptions {
pub dry_run: bool,
pub confirm: Option<String>,
pub no_reboot: bool,
pub backup_dir: PathBuf,
}
#[derive(Clone, Debug)]
pub struct A113dBackup {
pub image_name: String,
pub dest: String,
pub path: Option<PathBuf>,
pub md5: Option<String>,
pub size: u64,
}
#[derive(Clone, Debug)]
pub struct A113dReceipt {
pub volume: String,
pub backups: Vec<A113dBackup>,
pub rebooted: bool,
}
pub enum A113dOutcome {
DryRun(Box<A113dPreflight>),
Installed(A113dReceipt),
}
const MNT: &str = "/tmp/.alkane-nvdata";
/// Attach UBI to the nvdata MTD and mount its single user volume read-write.
/// 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> {
// Attach (idempotent: if ubi0 already exists, reuse it).
let _ = remote.root_command(
&format!(
"if [ ! -d /sys/class/ubi/ubi0 ]; then ubiattach -m {nvdata_mtd} -d 0 >/dev/null 2>&1; fi"
),
Duration::from_secs(60),
)?;
// Discover the first user volume name under ubi0.
let name = String::from_utf8_lossy(&remote.root_command(
"for n in /sys/class/ubi/ubi0_*/name; do [ -f \"$n\" ] && cat \"$n\" && break; done",
Duration::from_secs(20),
)?)
.trim()
.to_owned();
if name.is_empty() {
return Err(A113dError::UbiAttach);
}
// Mount it read-write.
remote.root_command(
&format!("mkdir -p {MNT} && mount -t ubifs ubi0:{name} {MNT}"),
Duration::from_secs(60),
)?;
// Confirm the mount actually took.
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);
}
Ok(name)
}
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"
),
Duration::from_secs(60),
);
}
pub fn install(
plan: &A113dPlan,
remote: &mut dyn Remote,
options: &A113dInstallOptions,
host: &str,
) -> Result<A113dOutcome, A113dError> {
let report = preflight(plan, remote, host)?;
if !report.ok() {
return Err(A113dError::Preflight(report.render()));
}
if options.dry_run {
return Ok(A113dOutcome::DryRun(Box::new(report)));
}
if options.confirm.as_deref() != Some("FLASH") {
return Err(A113dError::Confirm);
}
let nvdata_mtd = report
.nvdata_mtd
.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 volume = attach_and_mount(remote, nvdata_mtd)?;
let alkane_dir = format!("{MNT}/{ALKANE_DIR}");
let _ = remote.root_command(&format!("mkdir -p {alkane_dir}"), Duration::from_secs(20))?;
let mut backups = Vec::new();
let result = (|| -> Result<(), A113dError> {
for target in &plan.targets {
// Structural guard at the point of writing: a bare basename only.
if !is_safe_dest(&target.dest) {
return Err(A113dError::UnsafeDest(target.dest.clone()));
}
let name = &target.image_name;
let dest_path = format!("{alkane_dir}/{}", target.dest);
// Back up the existing file, if present.
let have = remote.user_command(
&format!("test -f {dest_path} && echo __YES__"),
Duration::from_secs(15),
)?;
if String::from_utf8_lossy(&have).contains("__YES__") {
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 {
image_name: name.clone(),
dest: target.dest.clone(),
md5: Some(md5_hex(&data)),
size: data.len() as u64,
path: Some(local),
});
} else {
backups.push(A113dBackup {
image_name: name.clone(),
dest: target.dest.clone(),
md5: None,
size: 0,
path: None,
});
}
// Stage the verified payload and prove its remote md5 before copying.
let mut staged = tempfile::NamedTempFile::new()?;
staged.write_all(&target.data)?;
staged.flush()?;
let remote_stage = format!("/tmp/.alkane-a113d-{name}.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(A113dError::StageMismatch(name.clone()));
}
// Copy into the UBIFS volume (file write only), then sync.
remote.root_command(
&format!("cp -f {remote_stage} {dest_path} && sync"),
Duration::from_secs(300),
)?;
// Read back the copied file and compare md5.
let readback = parse_digest(
&remote.root_command(&format!("md5sum {dest_path}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
if readback != target.expected_md5 {
return Err(A113dError::Readback(name.clone()));
}
}
Ok(())
})();
// Always unmount/detach, success or failure, before returning or rebooting.
unmount(remote);
result?;
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(A113dOutcome::Installed(A113dReceipt {
volume,
backups,
rebooted,
}))
}
pub fn owns_board(board: &str) -> bool {
board == BOARD
}
/// True when no plan target would ever name a preserved raw partition. Used by
/// tests to assert the structural guard holds for the fixed TARGETS table.
pub fn no_raw_device_targets(plan: &A113dPlan) -> bool {
plan.targets.iter().all(|t| is_safe_dest(&t.dest))
}
#[cfg(test)]
mod tests {
use super::*;
use alkane_artifacts::afw::{AfwManifest, AfwMember};
use serde_json::json;
use sha2::{Digest, Sha256};
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
fn arm64_image(payload: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 64];
b[0x38..0x3C].copy_from_slice(b"ARMd");
b.extend_from_slice(payload);
b
}
fn dtb() -> Vec<u8> {
let mut b = vec![0u8; 2048];
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
b
}
fn uramdisk() -> Vec<u8> {
let mut b = vec![0u8; 64];
b[0..4].copy_from_slice(&[0x27, 0x05, 0x19, 0x56]);
b
}
fn afw_with(
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
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();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "nvdata", "install": true})
};
let value = json!({
"schema": 2, "format": "afw", "board": "a113d", "arch": "arm64",
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
"bootloader_policy": "preserve",
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
"partitions": partitions,
"images": [
image("kernel", "payload/vmlinux.bin", "kernel", "arm64-image", &kernel),
image("dtb", "payload/devicetree.dtb", "dtb", "fdt", &dtb),
image("rootfs", "payload/uramdisk.image.gz", "rootfs", "uimage", &rootfs),
],
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
});
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
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,
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
}
}
fn preserved_partitions() -> serde_json::Value {
json!([
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
"secure":true,"boot_critical":true,"write_order":0,"image":null},
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
])
}
fn good() -> VerifiedAfw {
afw_with(arm64_image(b"k"), dtb(), uramdisk(), preserved_partitions())
}
#[test]
fn accepts_a_good_plan_as_file_copies() {
let plan = A113dPlan::from_afw(&good()).unwrap();
assert_eq!(plan.targets.len(), 3);
// write order rootfs, dtb, kernel (kernel file lands last)
assert_eq!(plan.targets[0].image_name, "rootfs");
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!(plan.render().contains("alkane/"));
assert!(plan.render().contains("no raw NAND write is possible"));
}
#[test]
fn refuses_a_non_arm64_kernel() {
let r = A113dPlan::from_afw(&afw_with(
vec![0u8; 64],
dtb(),
uramdisk(),
preserved_partitions(),
));
assert!(matches!(r, Err(A113dPlanError::NotArm64 { .. })));
}
#[test]
fn refuses_an_oversize_kernel() {
let big = arm64_image(&vec![0u8; 0x4000000]);
let r = A113dPlan::from_afw(&afw_with(big, dtb(), uramdisk(), preserved_partitions()));
assert!(matches!(r, Err(A113dPlanError::ImageTooLarge { .. })));
}
#[test]
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(_))
));
let mut v = good();
v.manifest.images[1].file = "payload/fip.bin".to_owned();
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::BootloaderMember(_))
));
}
#[test]
fn refuses_a_preserved_partition_carrying_an_image() {
let partitions = json!([
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
"secure":true,"boot_critical":true,"write_order":0,"image":"kernel"},
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
]);
let v = afw_with(arm64_image(b"k"), dtb(), uramdisk(), partitions);
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::PreservedCarriesImage(_))
));
}
#[test]
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(_))
));
let mut v = good();
v.manifest.arch = "armv7".to_owned();
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"
);
}
}
#[test]
fn unsafe_dest_is_rejected_by_guard() {
assert!(!is_safe_dest("/dev/mtd0"));
assert!(!is_safe_dest("../escape"));
assert!(!is_safe_dest("sub/dir/file"));
assert!(is_safe_dest("vmlinux.bin"));
}
#[test]
fn parses_the_nvdata_mtd_index() {
let proc_mtd = "dev: size erasesize name\n\
mtd0: 0b900000 00020000 \"nvdata\"\n";
assert_eq!(parse_nvdata_mtd(proc_mtd), Some(0));
// 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)
);
}
}
File diff suppressed because it is too large Load Diff
+406
View File
@@ -0,0 +1,406 @@
// SPDX-License-Identifier: MIT
//! CV1835 board module: the only write is the 16 MiB p1 FIT.
//!
//! The vendor boot0, BL2, BL31 and U-Boot chain is preserved. The board plan is
//! read from the verified `.afw` manifest, not guessed at runtime.
use crate::md5::md5_hex;
use alkane_artifacts::afw::{
AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw, CV1835_P1_SIZE,
};
use thiserror::Error;
pub const BOARD: &str = "cv1835";
pub const ARCH: &str = "arm64";
pub const P1_DEVICE: &str = "/dev/mmcblk0p1";
pub const MARKER: &str = "CVBOOT";
pub const UPDATE_DAEMON_PORT: u16 = 12887;
pub const GOLDEN_LBA_BYTES: u64 = 0x300000 * 512;
#[derive(Debug, Error)]
pub enum CvPlanError {
#[error("bundle is for {0}, not cv1835")]
WrongBoard(String),
#[error("bundle arch is {0}, cv1835 needs arm64")]
WrongArch(String),
#[error("cv1835 requires bootloader_policy preserve")]
BootloaderPolicy,
#[error("cv1835 bundle carries a bootloader member")]
BootloaderMember,
#[error("cv1835 bundle must install exactly p1")]
MissingP1,
#[error("cv1835 p1 is {0} bytes, not the 16 MiB padded FIT")]
P1Size(u64),
#[error("cv1835 p1 partition is not /dev/mmcblk0p1")]
P1Device,
#[error("cv1835 p1 partition must be 16 MiB, non-secure and written once")]
P1Geometry,
#[error("cv1835 p1 is not a bootable FIT: {0}")]
Fit(String),
#[error("manifest marker is empty")]
Marker,
#[error("manifest kernel_version is empty")]
KernelVersion,
#[error("manifest is not an OS payload")]
PayloadType,
#[error("manifest preflight is missing {0}")]
Preflight(String),
}
#[derive(Clone, Debug)]
pub struct Cv1835Plan {
pub image: AfwImage,
pub data: Vec<u8>,
pub partition: AfwPartition,
pub expected_md5: String,
pub expected_sha256: String,
pub marker: String,
pub kernel_version: String,
pub sdk_revision: String,
pub os_revision: String,
pub source_os: Vec<String>,
pub required_commands: Vec<String>,
pub min_free_bytes: u64,
pub golden_lba_bytes: u64,
}
impl Cv1835Plan {
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, CvPlanError> {
let manifest = &afw.manifest;
if manifest.board != BOARD {
return Err(CvPlanError::WrongBoard(manifest.board.clone()));
}
if manifest.arch != ARCH {
return Err(CvPlanError::WrongArch(manifest.arch.clone()));
}
if manifest.payload_type != "os" {
return Err(CvPlanError::PayloadType);
}
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
return Err(CvPlanError::BootloaderPolicy);
}
if manifest
.images
.iter()
.any(|image| image.role == "bootloader")
{
return Err(CvPlanError::BootloaderMember);
}
if manifest.marker.is_empty() {
return Err(CvPlanError::Marker);
}
if manifest.kernel_version.is_empty() {
return Err(CvPlanError::KernelVersion);
}
let install: Vec<&AfwImage> = manifest
.images
.iter()
.filter(|image| image.install)
.collect();
if install.len() != 1 || install[0].name != "p1" {
return Err(CvPlanError::MissingP1);
}
let image = install[0].clone();
if image.format != "fit" {
return Err(CvPlanError::Fit("format is not fit".to_owned()));
}
if image.size != CV1835_P1_SIZE {
return Err(CvPlanError::P1Size(image.size));
}
let (_, data) = afw.install_image().ok_or(CvPlanError::MissingP1)?;
if !data.starts_with(b"\xd0\x0d\xfe\xed") {
return Err(CvPlanError::Fit("missing FDT/FIT magic".to_owned()));
}
if !contains(data, b"config@cv1835_miner_emmc") {
return Err(CvPlanError::Fit(
"missing config@cv1835_miner_emmc".to_owned(),
));
}
if contains(data, b"signature@") {
return Err(CvPlanError::Fit("carries signature@ nodes".to_owned()));
}
let partition = manifest
.partitions
.iter()
.find(|part| part.name == "p1")
.ok_or(CvPlanError::P1Device)?
.clone();
if partition.device != P1_DEVICE {
return Err(CvPlanError::P1Device);
}
if partition.size != CV1835_P1_SIZE
|| partition.secure
|| !partition.boot_critical
|| partition.write_order != 1
{
return Err(CvPlanError::P1Geometry);
}
if manifest
.partitions
.iter()
.any(|part| part.write_order > 0 && part.name != "p1")
{
return Err(CvPlanError::MissingP1);
}
let source_os = json_strings(&manifest.preflight, "source_os");
let required_commands = json_strings(&manifest.preflight, "required_commands");
let min_free_bytes = manifest
.preflight
.get("min_free_bytes")
.and_then(|value| value.as_u64())
.unwrap_or(32 * 1024 * 1024);
let golden_lba_bytes = manifest
.recovery
.get("golden_lba_bytes")
.and_then(|value| value.as_u64())
.unwrap_or(GOLDEN_LBA_BYTES);
Ok(Self {
expected_md5: md5_hex(data),
expected_sha256: image.sha256.clone(),
image,
data: data.to_vec(),
partition,
marker: manifest.marker.clone(),
kernel_version: manifest.kernel_version.clone(),
sdk_revision: manifest.sdk_revision.clone(),
os_revision: manifest.os_revision.clone(),
source_os,
required_commands,
min_free_bytes,
golden_lba_bytes,
})
}
pub fn render(&self) -> String {
format!(
"board cv1835 arch arm64\n\
partition {} {} {} B secure=false boot_critical=true write_order={}\n\
image {} {} {} B sha256 {}\n\
image md5 {}\n\
bootloader preserve (vendor boot0/BL2/BL31/U-Boot kept)\n\
boot switch partition-overwrite (p1 is the switch)\n\
marker {} kernel {} sdk {} os {}",
self.partition.name,
self.partition.device,
self.partition.size,
self.partition.write_order,
self.image.name,
self.image.file,
self.image.size,
self.image.sha256,
self.expected_md5,
self.marker,
self.kernel_version,
short_revision(&self.sdk_revision),
short_revision(&self.os_revision),
)
}
}
fn short_revision(revision: &str) -> &str {
revision.get(..12).unwrap_or(revision)
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack
.windows(needle.len())
.any(|window| window == needle)
}
fn json_strings(value: &serde_json::Value, key: &str) -> Vec<String> {
value
.get(key)
.and_then(|item| item.as_array())
.map(|items| {
items
.iter()
.filter_map(|item| item.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default()
}
pub fn manifest_from_json(value: serde_json::Value) -> Result<AfwManifest, serde_json::Error> {
serde_json::from_value(value)
}
#[cfg(test)]
mod tests {
use super::*;
use alkane_artifacts::afw::AfwMember;
use serde_json::json;
use sha2::{Digest, Sha256};
const P1: usize = CV1835_P1_SIZE as usize;
const REV: &str = "0000000000000000000000000000000000000000";
fn sha_hex(data: &[u8]) -> String {
Sha256::digest(data)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn p1_image() -> Vec<u8> {
let mut fit = vec![0_u8; P1];
fit[..4].copy_from_slice(b"\xd0\x0d\xfe\xed");
let marker = b"config@cv1835_miner_emmc";
fit[0x100..0x100 + marker.len()].copy_from_slice(marker);
fit
}
fn manifest_value(p1: &[u8]) -> serde_json::Value {
json!({
"schema": 2,
"format": "afw",
"board": "cv1835",
"arch": "arm64",
"version": "0.1.0",
"build_date": "2026-11-04T00:00:00Z",
"sdk_revision": REV,
"os_revision": REV,
"payload_type": "os",
"bootloader_policy": "preserve",
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
"partitions": [
{"name": "p1", "device": "/dev/mmcblk0p1", "offset": 0,
"size": CV1835_P1_SIZE, "secure": false, "boot_critical": true,
"write_order": 1, "image": "p1"},
{"name": "boot0", "device": "/dev/mmcblk0boot0", "offset": 0,
"size": 4194304, "secure": true, "boot_critical": true,
"write_order": 0, "image": null}
],
"images": [
{"name": "p1", "file": "payload/p1.fit", "role": "boot",
"format": "fit", "size": p1.len(),
"sha256": sha_hex(p1),
"partition": "p1", "install": true}
],
"boot_switch": {"method": "partition-overwrite"},
"preflight": {"required_commands": ["dd", "md5sum", "sync"],
"source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"],
"min_free_bytes": 33554432},
"recovery": {"network": "afw restore", "golden_lba_bytes": GOLDEN_LBA_BYTES},
"marker": "CVBOOT",
"kernel_version": "6.18.48"
})
}
fn afw(p1: &[u8]) -> VerifiedAfw {
let manifest = manifest_from_json(manifest_value(p1)).unwrap();
VerifiedAfw {
manifest,
members: vec![AfwMember {
name: "payload/p1.fit".to_owned(),
data: p1.to_vec(),
}],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
}
}
#[test]
fn accepts_the_cv_plan() {
let data = p1_image();
let plan = Cv1835Plan::from_afw(&afw(&data)).unwrap();
assert_eq!(plan.partition.device, "/dev/mmcblk0p1");
assert_eq!(plan.image.size, CV1835_P1_SIZE);
assert_eq!(plan.marker, "CVBOOT");
assert!(plan
.render()
.contains("partition p1 /dev/mmcblk0p1 16777216"));
}
#[test]
fn refuses_a_bundle_for_another_board() {
let data = p1_image();
let mut verified = afw(&data);
verified.manifest.board = "zynq-7010".to_owned();
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::WrongBoard(_))
));
}
#[test]
fn refuses_include_bootloader_policy() {
let data = p1_image();
let mut verified = afw(&data);
verified.manifest.bootloader_policy = BootloaderPolicy::Include;
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::BootloaderPolicy)
));
}
#[test]
fn refuses_a_bootloader_member() {
let data = p1_image();
let mut verified = afw(&data);
verified.manifest.images.push(AfwImage {
name: "u-boot".to_owned(),
file: "payload/u-boot.img".to_owned(),
role: "bootloader".to_owned(),
format: "uimage".to_owned(),
size: 4,
sha256: "0".repeat(64),
partition: None,
install: false,
});
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::BootloaderMember)
));
}
#[test]
fn refuses_a_short_p1() {
let data = vec![0_u8; 1024];
let verified = afw(&data);
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::P1Size(1024))
));
}
#[test]
fn refuses_a_secure_p1() {
let data = p1_image();
let mut verified = afw(&data);
verified.manifest.partitions[0].secure = true;
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::P1Geometry)
));
}
#[test]
fn refuses_a_wrong_device() {
let data = p1_image();
let mut verified = afw(&data);
verified.manifest.partitions[0].device = "/dev/mmcblk0p3".to_owned();
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::P1Device)
));
}
#[test]
fn refuses_a_fit_without_the_board_config() {
let mut data = p1_image();
for byte in data.iter_mut() {
if *byte == b'c' {
*byte = b'x';
}
}
let verified = afw(&data);
assert!(matches!(
Cv1835Plan::from_afw(&verified),
Err(CvPlanError::Fit(_))
));
}
}
+8
View File
@@ -0,0 +1,8 @@
// SPDX-License-Identifier: MIT
//! Board modules. Each module validates the verified manifest for its family
//! and exposes the exact write plan the installer follows.
pub mod a113d;
pub mod am335x;
pub mod cv1835;
pub mod zynq;
+410
View File
@@ -0,0 +1,410 @@
// SPDX-License-Identifier: MIT
//! Zynq-7010 board module: the manifest gate and write plan for putting our
//! OS onto a Zynq control board (Antminer S17/S19 class).
//!
//! 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 alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
use thiserror::Error;
pub const BOARD: &str = "zynq-7010";
pub const ARCH: &str = "armv7";
/// 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;
/// 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)]
pub enum ZynqPlanError {
#[error("bundle is for {0}, not zynq-7010")]
WrongBoard(String),
#[error("bundle arch is {0}, zynq-7010 needs armv7")]
WrongArch(String),
#[error("zynq-7010 requires bootloader_policy preserve")]
BootloaderPolicy,
#[error("zynq-7010 bundle carries a bootloader/spl/BOOT.bin member: {0}")]
BootloaderMember(String),
#[error("manifest is not an OS payload")]
PayloadType,
#[error("manifest marker is empty")]
Marker,
#[error("zynq-7010 must install exactly kernel, dtb and rootfs")]
InstallCount,
#[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 {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}: below BOOT.bin (0x{bootbin:x})")]
WouldClobberBootbin {
image: String,
offset: u64,
bootbin: u64,
},
}
#[derive(Clone, Debug)]
pub struct ZynqTarget {
pub image_name: String,
/// 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,
}
#[derive(Clone, Debug)]
pub struct ZynqPlan {
pub targets: Vec<ZynqTarget>,
pub marker: String,
pub kernel_version: String,
pub sdk_revision: String,
pub os_revision: String,
pub afw_sha256: String,
}
fn is_bootloaderish(image: &AfwImage) -> bool {
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
image.role == "bootloader"
|| lowered.contains("spl")
|| lowered.contains("u-boot")
|| lowered.contains("uboot")
|| lowered.contains("boot.bin")
}
impl ZynqPlan {
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, ZynqPlanError> {
let manifest = &afw.manifest;
if manifest.board != BOARD {
return Err(ZynqPlanError::WrongBoard(manifest.board.clone()));
}
if manifest.arch != ARCH {
return Err(ZynqPlanError::WrongArch(manifest.arch.clone()));
}
if manifest.payload_type != "os" {
return Err(ZynqPlanError::PayloadType);
}
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
return Err(ZynqPlanError::BootloaderPolicy);
}
if manifest.marker.is_empty() {
return Err(ZynqPlanError::Marker);
}
// BOOT.bin / bootloader members are never allowed - we reuse the board's.
for image in &manifest.images {
if is_bootloaderish(image) {
return Err(ZynqPlanError::BootloaderMember(image.file.clone()));
}
}
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
if installs.len() != TARGETS.len() {
return Err(ZynqPlanError::InstallCount);
}
let mut targets = Vec::with_capacity(TARGETS.len());
for (image_name, absolute, slot, expected_format, wrapped) in TARGETS {
let image = manifest
.images
.iter()
.find(|i| i.name == image_name && i.install)
.ok_or_else(|| ZynqPlanError::MissingImage(image_name.to_owned()))?;
if image.format != expected_format {
return Err(ZynqPlanError::ImageFormat {
image: image_name.to_owned(),
actual: image.format.clone(),
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 hard brick guard: nothing is ever placed inside BOOT.bin.
if absolute < BOOTBIN_PRESERVE {
return Err(ZynqPlanError::WouldClobberBootbin {
image: image_name.to_owned(),
offset: absolute,
bootbin: BOOTBIN_PRESERVE,
});
}
let data = afw
.image(image_name)
.map(|(_, data)| data)
.ok_or_else(|| ZynqPlanError::MissingImage(image_name.to_owned()))?;
if expected_format == "zimage"
&& !(data.len() >= 0x28 && data[0x24..0x28] == [0x18, 0x28, 0x6f, 0x01])
{
return Err(ZynqPlanError::NotZImage {
image: image_name.to_owned(),
});
}
targets.push(ZynqTarget {
image_name: image_name.to_owned(),
absolute,
slot,
size: image.size,
uimage_wrapped: wrapped,
expected_md5: md5_hex(data),
data: data.to_vec(),
});
}
Ok(Self {
targets,
marker: manifest.marker.clone(),
kernel_version: manifest.kernel_version.clone(),
sdk_revision: manifest.sdk_revision.clone(),
os_revision: manifest.os_revision.clone(),
afw_sha256: afw.archive_sha256.clone(),
})
}
pub fn render(&self) -> String {
let mut out = format!("board {BOARD} arch {ARCH}\n");
out.push_str(&format!(
"boot slots (absolute NAND); BOOT.bin 0x0..0x{BOOTBIN_PRESERVE:x} preserved, never written\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 {:<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!(
"marker {} kernel {} sdk {} os {}",
self.marker,
self.kernel_version,
short(&self.sdk_revision),
short(&self.os_revision),
));
out
}
}
fn short(rev: &str) -> &str {
rev.get(..12).unwrap_or(rev)
}
pub fn owns_board(board: &str) -> bool {
board == BOARD
}
#[cfg(test)]
mod tests {
use super::*;
use alkane_artifacts::afw::{AfwManifest, AfwMember};
use serde_json::json;
use sha2::{Digest, Sha256};
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
fn zimage(payload: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 64];
b[0x24..0x28].copy_from_slice(&[0x18, 0x28, 0x6f, 0x01]);
b.extend_from_slice(payload);
b
}
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();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "x", "install": true})
};
let value = json!({
"schema": 2, "format": "afw", "board": "zynq-7010", "arch": "armv7",
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
"bootloader_policy": "preserve",
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
"partitions": [],
"images": [
image("kernel", "payload/zImage", "kernel", "zimage", &kernel),
image("dtb", "payload/zynq-alkane.dtb", "dtb", "fdt", &dtb),
image("rootfs", "payload/rootfs.cpio.gz", "rootfs", "cpio-gzip", &rootfs),
],
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
});
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
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,
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
}
}
fn dtb() -> Vec<u8> {
let mut b = vec![0u8; 1024];
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
b
}
#[test]
fn accepts_a_good_plan_and_places_above_bootbin() {
let plan = ZynqPlan::from_afw(&afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec())).unwrap();
assert_eq!(plan.targets.len(), 3);
// write order rootfs, dtb, kernel
assert_eq!(plan.targets[0].image_name, "rootfs");
assert_eq!(plan.targets[2].image_name, "kernel");
for t in &plan.targets {
assert!(
t.absolute >= BOOTBIN_PRESERVE,
"{} below BOOT.bin",
t.image_name
);
}
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]
fn refuses_a_non_zimage_kernel() {
let result = ZynqPlan::from_afw(&afw(vec![0u8; 64], dtb(), b"\x1f\x8brf".to_vec()));
assert!(matches!(result, Err(ZynqPlanError::NotZImage { .. })));
}
#[test]
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(_))
));
}
#[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(_))
));
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(_))
));
}
#[test]
fn every_target_is_above_bootbin() {
for (image, absolute, _slot, _fmt, _wrapped) in TARGETS {
assert!(
absolute >= BOOTBIN_PRESERVE,
"{image} target below BOOT.bin"
);
}
}
}
+920
View File
@@ -0,0 +1,920 @@
// SPDX-License-Identifier: MIT
//! CV1835 install, restore and live verification over the network.
//!
//! Order of operations for an install: verify the bundle, preflight the board,
//! hold the current p1 over SSH, stage the new p1, write it once, read the whole
//! partition back, and only then reboot. Any doubt before the first write stops
//! the sequence. A read-back mismatch stops before reboot and prints the exact
//! restore command.
use crate::boards::cv1835::{Cv1835Plan, CvPlanError};
use crate::md5::md5_hex;
use crate::preflight::{preflight, PreflightError, PreflightOptions, PreflightReport};
use crate::transport::{Remote, RemoteError, SshOptions, SshTransport};
use alkane_artifacts::afw::{AfwError, VerifiedAfw};
use sha2::{Digest, Sha256};
use std::fs;
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use thiserror::Error;
const REMOTE_BACKUP: &str = "/tmp/.alkane-p1-backup.img";
const REMOTE_STAGE: &str = "/tmp/.alkane-p1-stage.img";
#[derive(Debug, Error)]
pub enum InstallError {
#[error("preflight failed; do not write\n{0}")]
Preflight(String),
#[error("install and restore need --confirm FLASH")]
Confirm,
#[error("verified .afw: {0}")]
Afw(#[from] AfwError),
#[error("cv1835 plan: {0}")]
Plan(#[from] CvPlanError),
#[error("preflight: {0}")]
PreflightError(#[from] PreflightError),
#[error("remote: {0}")]
Remote(#[from] RemoteError),
#[error("I/O: {0}")]
Io(#[from] std::io::Error),
#[error("backup {0} is not the 16 MiB p1 size")]
BackupSize(PathBuf),
#[error("backup md5 does not match the live p1; refusing to continue")]
BackupMismatch,
#[error("staged image md5 does not match the verified bundle; nothing written")]
StageMismatch,
#[error("p1 read-back md5 mismatch; do not reboot. Restore with: {0}")]
Readback(String),
#[error("restore read-back md5 mismatch; the board may still hold the new image")]
RestoreReadback,
}
#[derive(Clone, Debug)]
pub struct InstallOptions {
pub dry_run: bool,
pub confirm: Option<String>,
pub no_reboot: bool,
pub backup_dir: PathBuf,
pub held_backup: Option<PathBuf>,
pub allow_unknown_source: bool,
pub check_golden: bool,
}
impl Default for InstallOptions {
fn default() -> Self {
Self {
dry_run: false,
confirm: None,
no_reboot: false,
backup_dir: default_backup_dir(),
held_backup: None,
allow_unknown_source: false,
check_golden: false,
}
}
}
#[derive(Clone, Debug)]
pub struct InstallReceipt {
pub backup_path: PathBuf,
pub backup_md5: String,
pub backup_sha256: String,
pub image_md5: String,
pub rebooted: bool,
}
#[derive(Clone, Debug)]
pub enum InstallOutcome {
DryRun(Box<PreflightReport>),
Installed(InstallReceipt),
}
pub fn install(
_afw: &VerifiedAfw,
plan: &Cv1835Plan,
remote: &mut dyn Remote,
options: &InstallOptions,
host: &str,
) -> Result<InstallOutcome, InstallError> {
let report = preflight(
plan,
remote,
&PreflightOptions {
host,
held_backup: options.held_backup.as_deref(),
check_golden: options.check_golden,
allow_unknown_source: options.allow_unknown_source,
},
)?;
if !report.ok() {
return Err(InstallError::Preflight(report.render()));
}
if options.dry_run {
return Ok(InstallOutcome::DryRun(Box::new(report)));
}
if options.confirm.as_deref() != Some("FLASH") {
return Err(InstallError::Confirm);
}
fs::create_dir_all(&options.backup_dir)?;
let epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let backup_path = options.backup_dir.join(format!("p1-{epoch}.img"));
let device = &plan.partition.device;
// Hold the current p1 as root, then pull it over the unprivileged SSH
// session. The daemon channel is blind, so this two-step path is required.
let remote_backup = REMOTE_BACKUP;
remote.root_command(
&format!("dd if={device} of={remote_backup} bs=1M 2>&1; chmod 644 {remote_backup}"),
Duration::from_secs(180),
)?;
remote.pull(remote_backup, &backup_path, Duration::from_secs(240))?;
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
let backup_data = fs::read(&backup_path)?;
if backup_data.len() as u64 != plan.partition.size {
return Err(InstallError::BackupSize(backup_path));
}
let backup_md5 = md5_hex(&backup_data);
if report.live_md5 != "unreadable" && backup_md5 != report.live_md5 {
return Err(InstallError::BackupMismatch);
}
let backup_sha256: String = Sha256::digest(&backup_data)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
write_sidecars(
&backup_path,
&backup_md5,
&backup_sha256,
&plan.partition,
&plan.expected_sha256,
epoch,
)?;
stage_and_write(plan, remote, &backup_path)?;
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(InstallOutcome::Installed(InstallReceipt {
backup_path,
backup_md5,
backup_sha256,
image_md5: plan.expected_md5.clone(),
rebooted,
}))
}
fn stage_and_write(
plan: &Cv1835Plan,
remote: &mut dyn Remote,
backup_path: &Path,
) -> Result<(), InstallError> {
let mut staged =
tempfile::NamedTempFile::new_in(backup_path.parent().unwrap_or_else(|| Path::new(".")))?;
staged.write_all(&plan.data)?;
staged.flush()?;
remote.push(staged.path(), REMOTE_STAGE, Duration::from_secs(240))?;
let staged_md5 =
remote.root_command(&format!("md5sum {REMOTE_STAGE}"), Duration::from_secs(60))?;
let staged_md5 = String::from_utf8_lossy(&staged_md5)
.split_whitespace()
.next()
.unwrap_or("")
.to_ascii_lowercase();
if staged_md5 != plan.expected_md5 {
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
return Err(InstallError::StageMismatch);
}
remote.root_command(
&format!(
"dd if={REMOTE_STAGE} of={} bs=1M conv=fsync 2>&1; sync",
plan.partition.device
),
Duration::from_secs(240),
)?;
let readback = remote.root_command(
&format!("md5sum {}", plan.partition.device),
Duration::from_secs(90),
)?;
let readback = String::from_utf8_lossy(&readback)
.split_whitespace()
.next()
.unwrap_or("")
.to_ascii_lowercase();
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
if readback != plan.expected_md5 {
return Err(InstallError::Readback(restore_command(
&plan.partition.device,
backup_path,
)));
}
Ok(())
}
#[derive(Clone, Debug)]
pub struct RestoreOptions {
pub confirm: Option<String>,
pub no_reboot: bool,
}
#[derive(Clone, Debug)]
pub struct RestoreReceipt {
pub backup_path: PathBuf,
pub image_md5: String,
pub rebooted: bool,
}
pub fn restore(
backup: &Path,
remote: &mut dyn Remote,
options: &RestoreOptions,
) -> Result<RestoreReceipt, InstallError> {
if options.confirm.as_deref() != Some("FLASH") {
return Err(InstallError::Confirm);
}
let data = fs::read(backup)?;
if data.len() != 16 * 1024 * 1024 {
return Err(InstallError::BackupSize(backup.to_path_buf()));
}
let md5 = md5_hex(&data);
let sha256: String = Sha256::digest(&data)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
if let Some(sidecar) = read_sidecar(backup) {
if sidecar != sha256 {
return Err(InstallError::BackupMismatch);
}
}
let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
if root_uid != "0" {
return Err(InstallError::Preflight(format!(
"root channel returned uid {root_uid}"
)));
}
let size = remote.user_command(
"cat /sys/class/block/mmcblk0p1/size 2>/dev/null || true",
Duration::from_secs(15),
)?;
let sectors: u64 = String::from_utf8_lossy(&size).trim().parse().unwrap_or(0);
if sectors.saturating_mul(512) != 16 * 1024 * 1024 {
return Err(InstallError::Preflight(
"the board does not expose a 16 MiB /dev/mmcblk0p1".to_owned(),
));
}
let staged = tempfile::NamedTempFile::new()?;
fs::write(staged.path(), &data)?;
remote.push(staged.path(), REMOTE_STAGE, Duration::from_secs(240))?;
let staged_md5 =
remote.root_command(&format!("md5sum {REMOTE_STAGE}"), Duration::from_secs(60))?;
let staged_md5 = String::from_utf8_lossy(&staged_md5)
.split_whitespace()
.next()
.unwrap_or("")
.to_ascii_lowercase();
if staged_md5 != md5 {
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
return Err(InstallError::StageMismatch);
}
remote.root_command(
&format!("dd if={REMOTE_STAGE} of=/dev/mmcblk0p1 bs=1M conv=fsync 2>&1; sync"),
Duration::from_secs(240),
)?;
let readback = remote.root_command("md5sum /dev/mmcblk0p1", Duration::from_secs(90))?;
let readback = String::from_utf8_lossy(&readback)
.split_whitespace()
.next()
.unwrap_or("")
.to_ascii_lowercase();
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
if readback != md5 {
return Err(InstallError::RestoreReadback);
}
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(RestoreReceipt {
backup_path: backup.to_path_buf(),
image_md5: md5,
rebooted,
})
}
fn restore_command(device: &str, backup: &Path) -> String {
format!(
"alkane-cli afw restore --host <ip> --held-backup {} --confirm FLASH (the held copy of {device} is at {})",
backup.display(),
backup.display()
)
}
fn default_backup_dir() -> PathBuf {
alkane_core::platform::config_path("backups")
}
fn write_sidecars(
path: &Path,
md5: &str,
sha256: &str,
partition: &alkane_artifacts::afw::AfwPartition,
image_sha256: &str,
epoch: u64,
) -> Result<(), InstallError> {
let file_name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "p1.img".to_owned());
fs::write(
path.with_extension("img.sha256"),
format!("{sha256} {file_name}\n"),
)?;
let metadata = serde_json::json!({
"board": "cv1835",
"partition": partition.name,
"device": partition.device,
"size": partition.size,
"md5": md5,
"sha256": sha256,
"afw_sha256": image_sha256,
"created_unix": epoch,
});
fs::write(
path.with_extension("img.json"),
serde_json::to_vec_pretty(&metadata).unwrap_or_default(),
)?;
Ok(())
}
fn read_sidecar(path: &Path) -> Option<String> {
let text = fs::read_to_string(path.with_extension("img.sha256")).ok()?;
text.split_whitespace().next().map(str::to_owned)
}
#[derive(Clone, Debug)]
pub struct LiveReport {
pub attempts: u32,
pub http: String,
pub http_ok: bool,
pub ssh: String,
pub ssh_ok: bool,
pub api: String,
pub api_ok: bool,
}
impl LiveReport {
pub fn ok(&self) -> bool {
self.http_ok && self.ssh_ok && self.api_ok
}
pub fn render(&self) -> String {
format!(
"verify-live attempts {}\n http {}: {}\n ssh {}: {}\n api {}: {}\nresult {}",
self.attempts,
if self.http_ok { "ok" } else { "FAIL" },
self.http,
if self.ssh_ok { "ok" } else { "FAIL" },
self.ssh,
if self.api_ok { "ok" } else { "FAIL" },
self.api,
if self.ok() { "PASS" } else { "FAIL" }
)
}
}
pub fn verify_live(
host: &str,
marker: &str,
kernel_version: &str,
timeout: Duration,
ssh_options: &SshOptions,
) -> LiveReport {
let deadline = Instant::now() + timeout;
let mut attempts = 0;
loop {
attempts += 1;
let (http, http_ok) = match http_get(host, "/", Duration::from_secs(5)) {
Ok(body) => {
let ok = body.contains(marker);
(
if ok {
format!("marker {marker} present")
} else {
format!("marker {marker} absent ({} bytes)", body.len())
},
ok,
)
}
Err(error) => (error, false),
};
let (ssh, ssh_ok) = match SshTransport::connect(ssh_options.clone(), false) {
Ok(mut session) => 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}{}",
if ok {
""
} else {
" (expected the installed kernel)"
}
),
ok,
)
}
Err(error) => (format!("{error}"), false),
},
Err(error) => (format!("{error}"), false),
};
let (api, api_ok) = match api_version(host, Duration::from_secs(5)) {
Ok(body) => {
let ok = body.contains("\"STATUS\"")
|| body.contains("\"VERSION\"")
|| body.to_lowercase().contains("version");
(format!("{} bytes", body.len()), ok)
}
Err(error) => (error, false),
};
if http_ok && ssh_ok && api_ok {
return LiveReport {
attempts,
http,
http_ok,
ssh,
ssh_ok,
api,
api_ok,
};
}
if Instant::now() >= deadline {
return LiveReport {
attempts,
http,
http_ok,
ssh,
ssh_ok,
api,
api_ok,
};
}
std::thread::sleep(Duration::from_secs(5));
}
}
pub(crate) fn http_get(host: &str, path: &str, timeout: Duration) -> Result<String, String> {
let address = (host, 80_u16)
.to_socket_addrs()
.map_err(|error| format!("resolve: {error}"))?
.next()
.ok_or_else(|| "no address".to_owned())?;
let mut stream = TcpStream::connect_timeout(&address, timeout)
.map_err(|error| format!("connect: {error}"))?;
stream
.set_read_timeout(Some(timeout))
.map_err(|error| error.to_string())?;
let request = format!("GET {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\n\r\n");
stream
.write_all(request.as_bytes())
.map_err(|error| error.to_string())?;
let mut data = Vec::new();
let mut buffer = [0_u8; 8192];
loop {
match stream.read(&mut buffer) {
Ok(0) => break,
Ok(read) => {
data.extend_from_slice(&buffer[..read]);
if data.len() > 512 * 1024 {
break;
}
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => break,
Err(error) => return Err(error.to_string()),
}
}
let text = String::from_utf8_lossy(&data).into_owned();
let status_ok = text
.lines()
.next()
.map(|line| line.contains(" 200 ") || line.ends_with(" 200"))
.unwrap_or(false);
if status_ok {
Ok(text)
} else {
Err(text.lines().next().unwrap_or("no HTTP response").to_owned())
}
}
pub(crate) fn api_version(host: &str, timeout: Duration) -> Result<String, String> {
let address = (host, 4028_u16)
.to_socket_addrs()
.map_err(|error| format!("resolve: {error}"))?
.next()
.ok_or_else(|| "no address".to_owned())?;
let mut stream = TcpStream::connect_timeout(&address, timeout)
.map_err(|error| format!("connect: {error}"))?;
stream
.set_read_timeout(Some(timeout))
.map_err(|error| error.to_string())?;
stream
.write_all(b"{\"command\":\"version\"}\n")
.map_err(|error| error.to_string())?;
let mut data = Vec::new();
let mut buffer = [0_u8; 4096];
loop {
match stream.read(&mut buffer) {
Ok(0) => break,
Ok(read) => {
data.extend_from_slice(&buffer[..read]);
if data.len() > 64 * 1024 {
break;
}
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => break,
Err(error) => return Err(error.to_string()),
}
}
let text = String::from_utf8_lossy(&data).trim().to_owned();
if text.is_empty() {
Err("no API response".to_owned())
} else {
Ok(text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn derives_backup_sidecar_names() {
let path = Path::new("/tmp/p1-1.img");
assert_eq!(
path.with_extension("img.sha256"),
Path::new("/tmp/p1-1.img.sha256")
);
assert_eq!(
path.with_extension("img.json"),
Path::new("/tmp/p1-1.img.json")
);
}
#[test]
fn restore_command_names_the_held_copy() {
let command = restore_command("/dev/mmcblk0p1", Path::new("/tmp/p1.img"));
assert!(command.contains("afw restore"));
assert!(command.contains("/tmp/p1.img"));
}
}
#[cfg(test)]
mod network_tests {
use super::*;
use alkane_artifacts::afw::{AfwImage, AfwManifest, AfwMember, AfwPartition, BootloaderPolicy};
use serde_json::json;
use std::collections::HashMap;
const P1: usize = 16 * 1024 * 1024;
const REV: &str = "0000000000000000000000000000000000000000";
struct MockRemote {
partition: Vec<u8>,
files: HashMap<String, Vec<u8>>,
commands: Vec<String>,
rebooted: bool,
readback_corrupt: bool,
}
impl MockRemote {
fn new(partition: Vec<u8>) -> Self {
Self {
partition,
files: HashMap::new(),
commands: Vec::new(),
rebooted: false,
readback_corrupt: false,
}
}
fn md5(&self, data: &[u8]) -> String {
md5_hex(data)
}
}
impl Remote for MockRemote {
fn channel(&self) -> &str {
"mock"
}
fn root_method(&self) -> &'static str {
"direct"
}
fn user_command(
&mut self,
command: &str,
_timeout: Duration,
) -> Result<Vec<u8>, RemoteError> {
self.commands.push(command.to_owned());
let text = if command.contains("uname -r") {
"6.18.48\n__MODEL__\nAlkane CV1835\n__RELEASE__\nalkane\n".to_owned()
} else if command.contains("test -b") {
"block".to_owned()
} else if command.contains("/sys/class/block/mmcblk0p1/size") {
"32768".to_owned()
} else if command.contains("for c in dd") {
"dd\nmd5sum\nsync\n".to_owned()
} else if command.contains("df -k") {
"Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/root 100000 1 90000 1% /tmp\n".to_owned()
} else if command.contains("mmcblk0boot0") {
"yes".to_owned()
} else {
String::new()
};
Ok(text.into_bytes())
}
fn root_command(
&mut self,
command: &str,
_timeout: Duration,
) -> Result<Vec<u8>, RemoteError> {
self.commands.push(command.to_owned());
if command.starts_with("id -u") || command == "id" {
return Ok(b"0\n".to_vec());
}
if let Some(rest) = command.strip_prefix("md5sum /dev/mmcblk0p1") {
let _ = rest;
let mut data = self.partition.clone();
if self.readback_corrupt && self.files.contains_key(REMOTE_STAGE) {
if let Some(last) = data.last_mut() {
*last ^= 0xff;
}
self.readback_corrupt = false;
}
return Ok(format!("{} /dev/mmcblk0p1\n", self.md5(&data)).into_bytes());
}
if let Some(rest) = command.strip_prefix("md5sum ") {
let path = rest.split_whitespace().next().unwrap_or("");
let data = self.files.get(path).cloned().unwrap_or_default();
return Ok(format!("{} {path}\n", self.md5(&data)).into_bytes());
}
if let Some(rest) = command.strip_prefix("dd if=") {
let mut parts = rest.splitn(2, " of=");
let source = parts.next().unwrap_or("");
let target = parts
.next()
.unwrap_or("")
.split_whitespace()
.next()
.unwrap_or("");
if source == "/dev/mmcblk0p1" {
self.files.insert(target.to_owned(), self.partition.clone());
} else if target == "/dev/mmcblk0p1" {
if let Some(data) = self.files.get(source).cloned() {
self.partition = data;
}
}
return Ok(Vec::new());
}
if command.starts_with("rm -f ") {
let path = command.trim_start_matches("rm -f ").trim();
self.files.remove(path);
return Ok(Vec::new());
}
Ok(Vec::new())
}
fn push(
&mut self,
local: &Path,
remote: &str,
_timeout: Duration,
) -> Result<(), RemoteError> {
self.files.insert(remote.to_owned(), fs::read(local)?);
Ok(())
}
fn pull(
&mut self,
remote: &str,
local: &Path,
_timeout: Duration,
) -> Result<(), RemoteError> {
let data = self
.files
.get(remote)
.cloned()
.ok_or_else(|| RemoteError::Daemon("missing file".to_owned()))?;
fs::write(local, data)?;
Ok(())
}
fn reboot(&mut self) -> Result<(), RemoteError> {
self.rebooted = true;
Ok(())
}
}
fn p1_image() -> Vec<u8> {
let mut fit = vec![0_u8; P1];
fit[..4].copy_from_slice(b"\xd0\x0d\xfe\xed");
let marker = b"config@cv1835_miner_emmc";
fit[0x100..0x100 + marker.len()].copy_from_slice(marker);
fit
}
fn verified(data: &[u8]) -> VerifiedAfw {
let manifest = AfwManifest {
schema: 2,
format: "afw".to_owned(),
board: "cv1835".to_owned(),
arch: "arm64".to_owned(),
version: "0.1.0".to_owned(),
build_date: "2026-11-04T00:00:00Z".to_owned(),
sdk_revision: REV.to_owned(),
os_revision: REV.to_owned(),
payload_type: "os".to_owned(),
bootloader_policy: BootloaderPolicy::Preserve,
signature: alkane_artifacts::afw::AfwSignature {
kind: "unsigned".to_owned(),
member: None,
public_key_hex: None,
},
partitions: vec![
AfwPartition {
name: "p1".to_owned(),
device: "/dev/mmcblk0p1".to_owned(),
offset: 0,
size: P1 as u64,
secure: false,
boot_critical: true,
write_order: 1,
image: Some("p1".to_owned()),
},
AfwPartition {
name: "boot0".to_owned(),
device: "/dev/mmcblk0boot0".to_owned(),
offset: 0,
size: 4 * 1024 * 1024,
secure: true,
boot_critical: true,
write_order: 0,
image: None,
},
],
images: vec![AfwImage {
name: "p1".to_owned(),
file: "payload/p1.fit".to_owned(),
role: "boot".to_owned(),
format: "fit".to_owned(),
size: P1 as u64,
sha256: Sha256::digest(data)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect(),
partition: Some("p1".to_owned()),
install: true,
}],
boot_switch: json!({"method": "partition-overwrite"}),
preflight: json!({"required_commands": ["dd", "md5sum", "sync"],
"source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"],
"min_free_bytes": 33554432}),
recovery: json!({"network": "afw restore", "golden_lba_bytes": 0x300000u64 * 512}),
marker: "Alkane".to_owned(),
kernel_version: "6.18.48".to_owned(),
notes: None,
};
VerifiedAfw {
manifest,
members: vec![AfwMember {
name: "payload/p1.fit".to_owned(),
data: data.to_vec(),
}],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
}
}
#[test]
fn installs_p1_holds_a_backup_and_verifies_before_reboot() {
let original = vec![0x11_u8; P1];
let new = p1_image();
let afw = verified(&new);
let plan = Cv1835Plan::from_afw(&afw).unwrap();
let mut remote = MockRemote::new(original.clone());
let temp = tempfile::tempdir().unwrap();
let options = InstallOptions {
dry_run: false,
confirm: Some("FLASH".to_owned()),
no_reboot: true,
backup_dir: temp.path().to_path_buf(),
held_backup: None,
allow_unknown_source: true,
check_golden: false,
};
let outcome = install(&afw, &plan, &mut remote, &options, "10.255.1.1").unwrap();
let InstallOutcome::Installed(receipt) = outcome else {
panic!("expected an install");
};
assert_eq!(remote.partition, new);
assert_eq!(receipt.backup_md5, md5_hex(&original));
assert!(receipt.backup_path.is_file());
assert!(!remote.rebooted);
assert!(remote
.commands
.iter()
.any(|command| command.starts_with("dd if=/tmp/.alkane-p1-stage.img")));
}
#[test]
fn dry_run_never_writes_the_partition() {
let original = vec![0x22_u8; P1];
let new = p1_image();
let afw = verified(&new);
let plan = Cv1835Plan::from_afw(&afw).unwrap();
let mut remote = MockRemote::new(original.clone());
let temp = tempfile::tempdir().unwrap();
let options = InstallOptions {
dry_run: true,
confirm: None,
no_reboot: false,
backup_dir: temp.path().to_path_buf(),
held_backup: None,
allow_unknown_source: true,
check_golden: false,
};
let outcome = install(&afw, &plan, &mut remote, &options, "10.255.1.1").unwrap();
assert!(matches!(outcome, InstallOutcome::DryRun(_)));
assert_eq!(remote.partition, original);
assert!(!remote
.commands
.iter()
.any(|command| command.starts_with("dd if=/tmp/.alkane-p1-stage.img")));
}
#[test]
fn a_readback_mismatch_stops_before_reboot() {
let original = vec![0x33_u8; P1];
let new = p1_image();
let afw = verified(&new);
let plan = Cv1835Plan::from_afw(&afw).unwrap();
let mut remote = MockRemote::new(original);
remote.readback_corrupt = true;
let temp = tempfile::tempdir().unwrap();
let options = InstallOptions {
dry_run: false,
confirm: Some("FLASH".to_owned()),
no_reboot: false,
backup_dir: temp.path().to_path_buf(),
held_backup: None,
allow_unknown_source: true,
check_golden: false,
};
let result = install(&afw, &plan, &mut remote, &options, "10.255.1.1");
assert!(matches!(result, Err(InstallError::Readback(_))));
assert!(!remote.rebooted);
}
#[test]
fn confirm_is_required_before_any_device_write() {
let original = vec![0x44_u8; P1];
let new = p1_image();
let afw = verified(&new);
let plan = Cv1835Plan::from_afw(&afw).unwrap();
let mut remote = MockRemote::new(original.clone());
let temp = tempfile::tempdir().unwrap();
let options = InstallOptions {
dry_run: false,
confirm: None,
no_reboot: false,
backup_dir: temp.path().to_path_buf(),
held_backup: None,
allow_unknown_source: true,
check_golden: false,
};
let result = install(&afw, &plan, &mut remote, &options, "10.255.1.1");
assert!(matches!(result, Err(InstallError::Confirm)));
assert_eq!(remote.partition, original);
}
}
+37 -2
View File
@@ -1,6 +1,41 @@
// SPDX-License-Identifier: MIT
//! Guarded write sequence for a verified artifact and an SDK partition plan.
//! Board transport adapters must supply serial, recovery and readback evidence.
//! Guarded writes plus the network-only CV1835 installer.
//!
//! The original guarded-write helpers remain for boards that need an attached
//! recovery channel. CV1835 uses the network modules below: a verified `.afw`,
//! 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 sd_media;
pub mod stock;
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;
use alkane_artifacts::VerifiedArtifact;
use sha2::{Digest, Sha256};
+116
View File
@@ -0,0 +1,116 @@
// SPDX-License-Identifier: MIT
//! MD5 for the CV1835 whole-partition read-back.
//!
//! The stock busybox on this board ships `md5sum` but not `sha256sum`, and the
//! proven installer gates the write on a whole-partition md5. This module is a
//! small RFC 1321 implementation so the host can compare the same digest
//! without shelling out to a tool that may not exist.
const S: [u32; 64] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9,
14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15,
21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];
const K: [u32; 64] = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
];
pub fn md5(data: &[u8]) -> [u8; 16] {
let mut state = [0x67452301_u32, 0xefcdab89, 0x98badcfe, 0x10325476];
let bit_length = (data.len() as u64).wrapping_mul(8);
let mut message = data.to_vec();
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&bit_length.to_le_bytes());
for chunk in message.chunks_exact(64) {
let mut words = [0_u32; 16];
for (index, word) in words.iter_mut().enumerate() {
let start = index * 4;
*word = u32::from_le_bytes([
chunk[start],
chunk[start + 1],
chunk[start + 2],
chunk[start + 3],
]);
}
let [mut a, mut b, mut c, mut d] = state;
for index in 0..64 {
let (f, g) = match index {
0..=15 => ((b & c) | (!b & d), index),
16..=31 => ((d & b) | (!d & c), (5 * index + 1) % 16),
32..=47 => (b ^ c ^ d, (3 * index + 5) % 16),
_ => (c ^ (b | !d), (7 * index) % 16),
};
let rotated = a
.wrapping_add(f)
.wrapping_add(K[index])
.wrapping_add(words[g])
.rotate_left(S[index]);
a = d;
d = c;
c = b;
b = b.wrapping_add(rotated);
}
state[0] = state[0].wrapping_add(a);
state[1] = state[1].wrapping_add(b);
state[2] = state[2].wrapping_add(c);
state[3] = state[3].wrapping_add(d);
}
let mut digest = [0_u8; 16];
for (index, word) in state.iter().enumerate() {
digest[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes());
}
digest
}
pub fn md5_hex(data: &[u8]) -> String {
md5(data).iter().map(|byte| format!("{byte:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc1321_vectors() {
assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
assert_eq!(md5_hex(b"a"), "0cc175b9c0f1b6a831c399e269772661");
assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
assert_eq!(
md5_hex(b"message digest"),
"f96b697d7cb7938d525a2f31aaf161d0"
);
assert_eq!(
md5_hex(b"abcdefghijklmnopqrstuvwxyz"),
"c3fcd3d76192e4007dfb496cca67e13b"
);
assert_eq!(
md5_hex(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
"d174ab98d277d9f5a5611c2c9f419d9f"
);
assert_eq!(
md5_hex(
b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
),
"57edf4a22be3c955ac49da2e2107b67a"
);
}
#[test]
fn handles_a_block_boundary() {
let data = vec![0x42_u8; 64];
assert_eq!(md5_hex(&data), "8e558437ffca99de04c18a63b55a4fad");
}
}
+420
View File
@@ -0,0 +1,420 @@
// SPDX-License-Identifier: MIT
//! Read-only CV1835 preflight: source-OS fingerprint, root channel, partition
//! identity, held/golden backup hashes, free space and secure-region refusal.
//!
//! Every check runs over the network. A failure is reported, never repaired.
use crate::boards::cv1835::{Cv1835Plan, CvPlanError};
use crate::md5::md5_hex;
use crate::transport::{Remote, RemoteError};
use sha2::{Digest, Sha256};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use thiserror::Error;
const P1_NAME: &str = "mmcblk0p1";
#[derive(Debug, Error)]
pub enum PreflightError {
#[error("preflight transport: {0}")]
Remote(#[from] RemoteError),
#[error("preflight I/O: {0}")]
Io(#[from] std::io::Error),
#[error("preflight plan: {0}")]
Plan(#[from] CvPlanError),
#[error("held backup {path} is {size} bytes, not 16 MiB")]
BackupSize { path: PathBuf, size: u64 },
#[error("held backup {0} has no readable md5")]
BackupUnreadable(PathBuf),
}
#[derive(Clone, Debug)]
pub struct Check {
pub name: &'static str,
pub ok: bool,
pub detail: String,
}
#[derive(Clone, Debug)]
pub struct BackupCheck {
pub path: PathBuf,
pub md5: String,
pub sha256: String,
pub matches_live: bool,
}
#[derive(Clone, Debug)]
pub struct PreflightReport {
pub host: String,
pub source_os: String,
pub kernel: String,
pub model: String,
pub root_method: String,
pub root_uid: String,
pub partition_device: String,
pub partition_size: u64,
pub live_md5: String,
pub held_backup: Option<BackupCheck>,
pub golden_md5: Option<String>,
pub free_bytes: u64,
pub boot0_present: bool,
pub checks: Vec<Check>,
}
impl PreflightReport {
pub fn ok(&self) -> bool {
self.checks.iter().all(|check| check.ok)
}
pub fn failures(&self) -> Vec<&Check> {
self.checks.iter().filter(|check| !check.ok).collect()
}
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str(&format!("preflight {}\n", self.host));
out.push_str(&format!(
"source-os {} (kernel {})\n",
self.source_os, self.kernel
));
if !self.model.is_empty() {
out.push_str(&format!("model {}\n", self.model));
}
out.push_str(&format!(
"root {} (uid {})\n",
self.root_method, self.root_uid
));
out.push_str(&format!(
"partition {} {} B\n",
self.partition_device, self.partition_size
));
out.push_str(&format!("live p1 md5 {}\n", self.live_md5));
match &self.held_backup {
Some(backup) => out.push_str(&format!(
"held backup {} md5 {} ({})\n",
backup.path.display(),
backup.md5,
if backup.matches_live {
"matches live p1"
} else {
"differs from live p1"
}
)),
None => out.push_str("held backup none (install will create one before writing)\n"),
}
if let Some(golden) = &self.golden_md5 {
out.push_str(&format!("golden raw p1 md5 {golden}\n"));
}
out.push_str(&format!(
"free tmp {} MiB\n",
self.free_bytes / (1024 * 1024)
));
out.push_str(&format!(
"boot0 {} (never written)\n",
if self.boot0_present {
"present"
} else {
"not present"
}
));
for check in &self.checks {
out.push_str(&format!(
"check {} {}: {}\n",
check.name,
if check.ok { "ok" } else { "FAIL" },
check.detail
));
}
out.push_str(if self.ok() {
"result PASS\n"
} else {
"result FAIL (do not write)\n"
});
out
}
}
pub struct PreflightOptions<'a> {
pub host: &'a str,
pub held_backup: Option<&'a Path>,
pub check_golden: bool,
pub allow_unknown_source: bool,
}
pub fn preflight(
plan: &Cv1835Plan,
remote: &mut dyn Remote,
options: &PreflightOptions<'_>,
) -> Result<PreflightReport, PreflightError> {
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; \
ls /etc/bos_version /etc/fw-info /etc/alkane-release /etc/ouros-release 2>/dev/null; \
test -x /nvdata/rroot && echo rroot; \
test -x /usr/sbin/update-daemon && echo update-daemon",
Duration::from_secs(20),
)?;
let text = String::from_utf8_lossy(&fingerprint).into_owned();
let mut sections = text.split("__MODEL__");
let kernel = sections.next().unwrap_or("").trim().to_owned();
let rest = sections.next().unwrap_or("");
let mut sections = rest.split("__RELEASE__");
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)
|| options.allow_unknown_source;
checks.push(Check {
name: "source-os",
ok: source_ok,
detail: format!(
"{source_os} (allowed: {})",
if plan.source_os.is_empty() {
"any".to_owned()
} else {
plan.source_os.join(", ")
}
),
});
let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(Check {
name: "root",
ok: root_uid == "0",
detail: format!("uid {root_uid}"),
});
let partition_device = plan.partition.device.clone();
let block = String::from_utf8_lossy(&remote.user_command(
&format!("test -b {partition_device} && echo block || echo missing"),
Duration::from_secs(15),
)?)
.trim()
.to_owned();
let size_out = remote.user_command(
&format!("cat /sys/class/block/{P1_NAME}/size 2>/dev/null || true"),
Duration::from_secs(15),
)?;
let sectors: u64 = String::from_utf8_lossy(&size_out)
.trim()
.parse()
.unwrap_or(0);
let partition_size = sectors.saturating_mul(512);
checks.push(Check {
name: "partition",
ok: block == "block" && partition_size == plan.partition.size,
detail: format!(
"{partition_device} {partition_size} B (plan {} B)",
plan.partition.size
),
});
let live = remote.root_command(
&format!("md5sum {partition_device}"),
Duration::from_secs(60),
)?;
let live_md5 = parse_digest(&live, 32).unwrap_or_else(|| "unreadable".to_owned());
checks.push(Check {
name: "live-p1-md5",
ok: live_md5.len() == 32,
detail: live_md5.clone(),
});
let commands = remote.user_command(
"for c in dd md5sum sync; do command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
Duration::from_secs(15),
)?;
let commands_text = String::from_utf8_lossy(&commands).into_owned();
let missing: Vec<&str> = commands_text
.lines()
.filter_map(|line| line.strip_prefix("missing:"))
.collect();
checks.push(Check {
name: "commands",
ok: missing.is_empty(),
detail: if missing.is_empty() {
"dd, md5sum, sync present".to_owned()
} else {
format!("missing {}", missing.join(", "))
},
});
let free_bytes = free_bytes(remote)?;
checks.push(Check {
name: "free-space",
ok: free_bytes >= plan.min_free_bytes,
detail: format!(
"{} MiB at /tmp (plan {} MiB)",
free_bytes / (1024 * 1024),
plan.min_free_bytes / (1024 * 1024)
),
});
let boot0 = String::from_utf8_lossy(&remote.user_command(
"test -e /dev/mmcblk0boot0 && echo yes || echo no",
Duration::from_secs(15),
)?)
.trim()
.to_owned();
let boot0_present = boot0 == "yes";
checks.push(Check {
name: "secure-regions",
ok: !plan.partition.device.contains("boot0"),
detail: format!(
"boot0 {}; the write plan targets only {}",
if boot0_present { "present" } else { "absent" },
plan.partition.device
),
});
let mut held_backup = None;
if let Some(path) = options.held_backup {
let size = fs::metadata(path)?.len();
if size != plan.partition.size {
return Err(PreflightError::BackupSize {
path: path.to_path_buf(),
size,
});
}
let data = fs::read(path)?;
let md5 = md5_hex(&data);
let sha256: String = Sha256::digest(&data)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
let matches_live = md5 == live_md5;
checks.push(Check {
name: "held-backup",
ok: true,
detail: format!(
"{} md5 {md5} ({})",
path.display(),
if matches_live {
"matches live p1"
} else {
"differs from live p1; restore will still write it"
}
),
});
held_backup = Some(BackupCheck {
path: path.to_path_buf(),
md5,
sha256,
matches_live,
});
}
let mut golden_md5 = None;
if options.check_golden {
let out = remote.root_command(
&format!(
"dd if=/dev/mmcblk0 skip={} count=32768 bs=512 2>/dev/null | md5sum",
plan.golden_lba_bytes / 512
),
Duration::from_secs(90),
)?;
if let Some(digest) = parse_digest(&out, 32) {
golden_md5 = Some(digest);
}
}
Ok(PreflightReport {
host: options.host.to_owned(),
source_os,
kernel,
model,
root_method: remote.root_method().to_owned(),
root_uid,
partition_device,
partition_size,
live_md5,
held_backup,
golden_md5,
free_bytes,
boot0_present,
checks,
})
}
pub(crate) fn classify(kernel: &str, release: &str, all: &str) -> String {
if all.contains("/etc/bos_version") || release.contains("Braiins") {
return "braiins".to_owned();
}
if all.contains("/etc/alkane-release") || kernel.starts_with("6.18") {
return "alkane".to_owned();
}
if all.contains("/etc/ouros-release") || kernel.contains("6.6.147") {
return "ouros".to_owned();
}
if all.contains("/etc/fw-info") || release.contains("Vnish") || release.contains("AnthillOS") {
return "vnish".to_owned();
}
// Stock Bitmain control boards: Amlogic stock is kernel 4.9.38; the AM335x
// (BeagleBone-class) stock is kernel 3.8.13+ with an "Antminer" model line.
if kernel.contains("4.9.38")
|| kernel.starts_with("3.8.13")
|| all.contains("update-daemon")
|| all.contains("rroot")
|| all.to_lowercase().contains("antminer")
{
return "stock-bitmain".to_owned();
}
"unknown".to_owned()
}
pub fn parse_digest(output: &[u8], length: usize) -> Option<String> {
let text = String::from_utf8_lossy(output);
text.split_whitespace()
.map(|token| token.trim().to_ascii_lowercase())
.find(|token| token.len() == length && token.bytes().all(|byte| byte.is_ascii_hexdigit()))
}
fn free_bytes(remote: &mut dyn Remote) -> Result<u64, RemoteError> {
let out = remote.user_command("df -k /tmp 2>/dev/null || df -k /", Duration::from_secs(15))?;
let text = String::from_utf8_lossy(&out);
for line in text.lines().rev() {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() >= 4 {
if let Ok(kib) = fields[3].parse::<u64>() {
return Ok(kib.saturating_mul(1024));
}
}
}
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_the_source_os() {
assert_eq!(
classify("4.9.38-tag-", "", "update-daemon\n"),
"stock-bitmain"
);
assert_eq!(
classify("4.9.38-tag-", "/etc/fw-info\n", "/etc/fw-info\n"),
"vnish"
);
assert_eq!(classify("6.6.147", "/etc/ouros-release\n", ""), "ouros");
assert_eq!(classify("6.18.48", "", ""), "alkane");
assert_eq!(classify("4.9.38", "", "/etc/bos_version\n"), "braiins");
assert_eq!(classify("5.10.0", "", ""), "unknown");
}
#[test]
fn parses_md5_from_md5sum_output() {
let output = b"3f43804f10ce256200bfc71e7fbdd9ee /dev/mmcblk0p1\n";
assert_eq!(
parse_digest(output, 32).as_deref(),
Some("3f43804f10ce256200bfc71e7fbdd9ee")
);
assert_eq!(parse_digest(b"not a digest\n", 32), None);
}
}
+968
View File
@@ -0,0 +1,968 @@
// SPDX-License-Identifier: MIT
//! Build bootable SD / removable-media card *images* for control boards that
//! boot from a card, and (separately, guarded) write a finished image to a
//! physical device.
//!
//! Everything here is **network-free and root-free up to the final device
//! write**: a card image is assembled as an ordinary file using `sfdisk`
//! (partition table), `mkfs.vfat` (FAT32 filesystem) and `mtools`
//! (`mcopy`/`mmd`, which populate a FAT image with no loopback mount and no
//! root). The resulting `.img` is byte-for-byte what lands on the card, so it
//! is fully inspectable and unit-testable without hardware. Only
//! [`write_image_to_device`] touches a real block device, and it is deliberately
//! kept apart so a caller confirms the target first.
//!
//! The card layout this produces is the one proven on a bench Antminer S17
//! (2026-11-17): a single MBR primary FAT32 partition (type 0x0c) starting at
//! LBA 2048. On the Zynq boards the stock U-Boot card-detects such a card and
//! side-loads the flasher-OS trio (`uImage` / `devicetree.dtb` /
//! `uramdisk.image.gz`) from its root -- no boot-mode strap and no `uEnv.txt`
//! required (see `alkane-sdk-construction: zynq-s17-recovery.md`).
use crate::uimage::{self, Kind};
use alkane_artifacts::afw::VerifiedAfw;
use std::fmt;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Partition starts at LBA 2048 (1 MiB) -- the conventional alignment, and what
/// the proven S17 card used.
const PART_LBA: u64 = 2048;
/// Zynq-7010 absolute NAND boot-slot offsets the installer writes (mirror of
/// `zynq_nand`; BOOT.bin at 0x0..0x1a00000 is never touched).
const ZYNQ_OFF_DTB: u64 = 0x1a00000;
const ZYNQ_OFF_KERNEL: u64 = 0x2000000;
const ZYNQ_OFF_ROOTFS: u64 = 0x2800000;
const SECTOR: u64 = 512;
const PART_OFFSET_BYTES: u64 = PART_LBA * SECTOR;
#[derive(Debug)]
pub enum MediaError {
/// A required external tool (`sfdisk` / `mkfs.vfat` / an mtools binary) was
/// not found on the system.
MissingTool(String),
/// A source file or directory the card needs is absent.
MissingSource(String),
/// A vendor package did not contain a recognisable card layout.
BadPackage(String),
/// An external command exited non-zero; carries a short diagnostic.
Command(String),
Io(std::io::Error),
}
impl fmt::Display for MediaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MediaError::MissingTool(t) => write!(f, "required tool not found: {t}"),
MediaError::MissingSource(s) => write!(f, "missing source: {s}"),
MediaError::BadPackage(s) => write!(f, "unrecognised package layout: {s}"),
MediaError::Command(s) => write!(f, "{s}"),
MediaError::Io(e) => write!(f, "io: {e}"),
}
}
}
impl std::error::Error for MediaError {}
impl From<std::io::Error> for MediaError {
fn from(e: std::io::Error) -> Self {
MediaError::Io(e)
}
}
type Result<T> = std::result::Result<T, MediaError>;
/// Find an executable by name, searching `PATH` plus the usual `sbin`
/// directories (`mkfs.vfat` / `sfdisk` live in `/sbin` or `/usr/sbin`, which are
/// often absent from a GUI process's `PATH`).
fn find_tool(name: &str) -> Result<PathBuf> {
if let Ok(path) = std::env::var("PATH") {
for dir in std::env::split_paths(&path) {
let p = dir.join(name);
if p.is_file() {
return Ok(p);
}
}
}
for dir in ["/sbin", "/usr/sbin", "/usr/local/sbin", "/bin", "/usr/bin"] {
let p = Path::new(dir).join(name);
if p.is_file() {
return Ok(p);
}
}
Err(MediaError::MissingTool(name.to_string()))
}
fn run(mut cmd: Command, what: &str) -> Result<()> {
let out = cmd
.output()
.map_err(|e| MediaError::Command(format!("{what}: failed to launch: {e}")))?;
if !out.status.success() {
let mut msg = format!("{what}: exit {:?}", out.status.code());
let err = String::from_utf8_lossy(&out.stderr);
let err = err.trim();
if !err.is_empty() {
msg.push_str(": ");
msg.push_str(err.lines().next_back().unwrap_or(err));
}
return Err(MediaError::Command(msg));
}
Ok(())
}
/// A FAT32 card image under construction: a single MBR primary partition that
/// mtools populates through a private config file (no mount, no root).
pub struct CardImage {
img: PathBuf,
mtoolsrc: PathBuf,
mcopy: PathBuf,
mmd: PathBuf,
_tmp: Option<tempdir::TempHold>,
}
impl CardImage {
/// Create a new `size_mb`-megabyte image at `img_path`, partition it with a
/// single FAT32 (type 0x0c) partition at LBA 2048, format that partition
/// FAT32 with the given volume `label` (upper-cased, <= 11 chars), and
/// prepare mtools to write into it.
pub fn create(img_path: &Path, size_mb: u64, label: &str) -> Result<CardImage> {
let sfdisk = find_tool("sfdisk")?;
let mkfs = find_tool("mkfs.vfat")?;
let mcopy = find_tool("mcopy")?;
let mmd = find_tool("mmd")?;
// 1. Zero-filled image of the requested size.
let f = fs::File::create(img_path)?;
f.set_len(size_mb.saturating_mul(1024 * 1024))?;
drop(f);
// 2. MBR: one primary FAT32 (LBA) partition from sector 2048 to the end.
{
let mut cmd = Command::new(&sfdisk);
cmd.arg(img_path).stdin(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::piped());
let mut child = cmd
.spawn()
.map_err(|e| MediaError::Command(format!("sfdisk: {e}")))?;
{
let stdin = child
.stdin
.as_mut()
.ok_or_else(|| MediaError::Command("sfdisk: no stdin".to_string()))?;
writeln!(stdin, "label: dos")?;
writeln!(stdin, "start={PART_LBA}, type=0c")?;
}
let out = child
.wait_with_output()
.map_err(|e| MediaError::Command(format!("sfdisk: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command(format!(
"sfdisk: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
}
// 3. Format the partition region (no root) via mkfs.vfat --offset.
let label = sanitize_label(label);
let mut cmd = Command::new(&mkfs);
cmd.args(["-F", "32", "-n", &label, "--offset"])
.arg(PART_LBA.to_string())
.arg(img_path)
.stdout(std::process::Stdio::null());
run(cmd, "mkfs.vfat")?;
// 4. Private mtools config mapping drive C: to the partition region.
let tmp = tempdir::TempHold::new()?;
let mtoolsrc = tmp.path().join("mtools.conf");
{
let mut mf = fs::File::create(&mtoolsrc)?;
writeln!(
mf,
"drive C: file=\"{}\" offset={}",
img_path.display(),
PART_OFFSET_BYTES
)?;
}
Ok(CardImage {
img: img_path.to_path_buf(),
mtoolsrc,
mcopy,
mmd,
_tmp: Some(tmp),
})
}
fn mtools_cmd(&self, tool: &Path) -> Command {
let mut cmd = Command::new(tool);
cmd.env("MTOOLSRC", &self.mtoolsrc);
cmd.env("MTOOLS_SKIP_CHECK", "1");
cmd
}
/// Create a directory on the card, e.g. `bin`. Tolerates "already exists".
pub fn mkdir(&self, dest: &str) -> Result<()> {
let path = format!("C:/{}", dest.trim_start_matches('/'));
let out = self
.mtools_cmd(&self.mmd)
.arg(&path)
.output()
.map_err(|e| MediaError::Command(format!("mmd: {e}")))?;
if out.status.success() {
return Ok(());
}
let err = String::from_utf8_lossy(&out.stderr);
if err.to_lowercase().contains("already exists") {
Ok(())
} else {
Err(MediaError::Command(format!("mmd {dest}: {}", err.trim())))
}
}
/// Copy a local file onto the card at `dest` (a card-relative path like
/// `uImage` or `bin/BOOT.bin`). Overwrites.
pub fn copy_file(&self, local: &Path, dest: &str) -> Result<()> {
if !local.is_file() {
return Err(MediaError::MissingSource(local.display().to_string()));
}
let mut cmd = self.mtools_cmd(&self.mcopy);
cmd.arg("-o") // overwrite without prompting
.arg(local)
.arg(format!("C:/{}", dest.trim_start_matches('/')));
run(cmd, &format!("mcopy {}", local.display()))
}
/// Copy an entire local directory's contents onto the card under `dest`
/// (created if needed). Recurses.
pub fn copy_dir(&self, local: &Path, dest: &str) -> Result<()> {
if !local.is_dir() {
return Err(MediaError::MissingSource(local.display().to_string()));
}
self.mkdir(dest)?;
for entry in fs::read_dir(local)? {
let entry = entry?;
let name = entry.file_name();
let name = name.to_string_lossy();
let child_dest = format!("{}/{}", dest.trim_end_matches('/'), name);
if entry.file_type()?.is_dir() {
self.copy_dir(&entry.path(), &child_dest)?;
} else {
self.copy_file(&entry.path(), &child_dest)?;
}
}
Ok(())
}
/// Write a byte buffer onto the card at `dest`, staging through a temp file
/// (mtools copies from the filesystem, not stdin).
pub fn write_bytes(&self, bytes: &[u8], dest: &str) -> Result<()> {
use std::sync::atomic::{AtomicU64, Ordering};
static CTR: AtomicU64 = AtomicU64::new(0);
let n = CTR.fetch_add(1, Ordering::Relaxed);
let staged = std::env::temp_dir().join(format!(
"alkane-media-stage-{}-{}.bin",
std::process::id(),
n
));
fs::write(&staged, bytes)?;
let r = self.copy_file(&staged, dest);
let _ = fs::remove_file(&staged);
r
}
/// The finished image path.
pub fn path(&self) -> &Path {
&self.img
}
}
/// Upper-case and clamp a FAT volume label to 11 chars; empty becomes `ALKANE`.
fn sanitize_label(label: &str) -> String {
let up: String = label
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
.take(11)
.collect::<String>()
.to_ascii_uppercase();
if up.is_empty() {
"ALKANE".to_string()
} else {
up
}
}
/// A located vendor SD-recovery card layout: the flasher-OS trio at the package
/// root plus the `bin/` NAND payload directory.
pub struct VendorCardLayout {
/// Directory holding `uImage`, `devicetree.dtb`, `uramdisk.image.gz` and
/// `bin/`.
pub root: PathBuf,
}
/// Locate the card layout inside an unpacked vendor SD-recovery package. Vendor
/// zips often nest the real card directory one or two levels deep (e.g.
/// `sd_set_default_password_enhanced_0527_S17/.../`). Accept the shallowest
/// directory that contains all three root-level flasher files and a `bin/`.
pub fn locate_vendor_card(unpacked_root: &Path) -> Result<VendorCardLayout> {
fn has_layout(dir: &Path) -> bool {
dir.join("uImage").is_file()
&& dir.join("devicetree.dtb").is_file()
&& dir.join("uramdisk.image.gz").is_file()
&& dir.join("bin").is_dir()
}
// Breadth-first to prefer the shallowest match.
let mut queue = vec![unpacked_root.to_path_buf()];
let mut depth_guard = 0;
while let Some(dir) = queue.first().cloned() {
queue.remove(0);
if has_layout(&dir) {
return Ok(VendorCardLayout { root: dir });
}
depth_guard += 1;
if depth_guard > 4096 {
break;
}
if let Ok(rd) = fs::read_dir(&dir) {
for e in rd.flatten() {
if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
queue.push(e.path());
}
}
}
}
Err(MediaError::BadPackage(format!(
"no flasher-OS trio (uImage/devicetree.dtb/uramdisk.image.gz) + bin/ found under {}",
unpacked_root.display()
)))
}
/// Build a genuine-vendor **stock-recovery** card image from an already-unpacked
/// vendor SD-recovery package directory. The card is a single FAT32 partition
/// carrying the vendor layout verbatim: flasher-OS trio at the root plus the
/// `bin/` NAND payload. This is the toolkit codification of the procedure proven
/// by hand on the bench S17 (2026-11-17).
///
/// `unpacked_pkg` is a directory (the caller unpacks a `.zip`/`.tar.gz` first,
/// reusing [`crate::stock_firmware`]'s extraction helpers or `unzip`). The
/// finished image is written to `out_img`.
pub fn build_stock_recovery_card(unpacked_pkg: &Path, out_img: &Path) -> Result<()> {
let layout = locate_vendor_card(unpacked_pkg)?;
let root = &layout.root;
// Size the card to comfortably hold the payload (flasher ~45 MB + bin ~34 MB)
// with slack, rounded up; a 256 MiB card is plenty and small to write/verify.
let card = CardImage::create(out_img, 256, "ANTMINER")?;
for f in ["uImage", "devicetree.dtb", "uramdisk.image.gz"] {
card.copy_file(&root.join(f), f)?;
}
// README.md is harmless vendor documentation; include it if present.
let readme = root.join("README.md");
if readme.is_file() {
card.copy_file(&readme, "README.md")?;
}
card.copy_dir(&root.join("bin"), "bin")?;
Ok(())
}
// ---------------------------------------------------------------------------
// Alkane media (Zynq-7010 first). The card is the same FAT32 side-load shape as
// the vendor recovery: the stock (or our) U-Boot card-detects it and boots the
// `uImage` / `devicetree.dtb` / `uramdisk.image.gz` trio at the card root. The
// difference is only *what* that trio is and whether an installer action runs.
// ---------------------------------------------------------------------------
/// Pull the three Zynq boot components out of a verified `.afw` (`kernel`
/// zImage, `dtb` fdt, `rootfs` cpio-gzip). Mirrors `boards::zynq`'s roles.
fn zynq_afw_parts(afw: &VerifiedAfw) -> Result<(&[u8], &[u8], &[u8])> {
let get = |role: &str| {
afw.image(role)
.map(|(_, data)| data)
.ok_or_else(|| MediaError::BadPackage(format!("afw missing {role} image")))
};
Ok((get("kernel")?, get("dtb")?, get("rootfs")?))
}
/// Wrap the raw afw components into the Zynq card side-load trio:
/// (`uImage` = legacy-uImage-wrapped kernel, raw `devicetree.dtb`,
/// `uramdisk.image.gz` = legacy-uImage-wrapped rootfs). `bootm` on the stock
/// U-Boot expects uImage-wrapped kernel and ramdisk; the dtb is raw.
fn zynq_sideload_trio(
kernel_zimage: &[u8],
fdt: &[u8],
rootfs_cpio_gz: &[u8],
time: u32,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
(
uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane"),
fdt.to_vec(),
uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs"),
)
}
/// Build an alkane **simple-boot** card for a Zynq board from raw afw parts: the
/// card runs alkane from RAM each boot (nothing is written to the board's NAND).
/// Good for a non-destructive try-out or a permanently SD-run board.
pub fn build_zynq_simpleboot_card_from_parts(
kernel_zimage: &[u8],
fdt: &[u8],
rootfs_cpio_gz: &[u8],
out_img: &Path,
time: u32,
) -> Result<()> {
let (uimg, dtb, urd) = zynq_sideload_trio(kernel_zimage, fdt, rootfs_cpio_gz, time);
let card = CardImage::create(out_img, 256, "ALKANE")?;
card.write_bytes(&uimg, "uImage")?;
card.write_bytes(&dtb, "devicetree.dtb")?;
card.write_bytes(&urd, "uramdisk.image.gz")?;
Ok(())
}
/// Build an alkane simple-boot card from a verified `.afw`.
pub fn build_zynq_simpleboot_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> {
let (k, d, r) = zynq_afw_parts(afw)?;
build_zynq_simpleboot_card_from_parts(k, d, r, out_img, time)
}
/// The install hook the Zynq installer-OS runs on boot. It writes the alkane
/// boot slots carried in the card's `bin/` to NAND -- BOOT.bin (0x0..0x1a00000)
/// is never touched -- verifies by read-back, and drives the board's red/green
/// LEDs (GPIO 941 red / 942 green, confirmed on the bench S17): a steady
/// green-on/red-off "done, safe to remove" on success, red-on on failure. The
/// script uses only tools present in the alkane rootfs (busybox, mtd-utils).
///
/// This is the board-specific part; offsets mirror `zynq_nand`. On-hardware
/// behaviour is validated on the bench S17.
fn zynq_install_script() -> String {
// LED GPIO numbers for the Zynq S17 control board (sysfs). 941 red, 942 green.
format!(
r#"#!/bin/sh
# alkane SD installer hook (Zynq-7010). Runs once on boot from the installer
# initramfs, writes the alkane boot slots from the card's bin/ to NAND, then
# signals the LEDs. BOOT.bin is never written.
set -e
LED_RED=941
LED_GRN=942
CARD=/mnt/alkane-card
MTD=/dev/mtd0 # the device covering the boot region; resolved below
OFF_DTB=0x{off_dtb:x}
OFF_KERNEL=0x{off_kernel:x}
OFF_ROOTFS=0x{off_rootfs:x}
ERASE=0x20000
led_setup() {{
for g in $LED_RED $LED_GRN; do
[ -d /sys/class/gpio/gpio$g ] || echo $g > /sys/class/gpio/export 2>/dev/null || true
echo out > /sys/class/gpio/gpio$g/direction 2>/dev/null || true
done
}}
led() {{ echo "$2" > /sys/class/gpio/gpio$1/value 2>/dev/null || true; }}
fail() {{ led_setup; led $LED_RED 1; led $LED_GRN 0; echo "alkane-sd-install FAILED: $1" >&2; exit 1; }}
led_setup; led $LED_RED 1; led $LED_GRN 1 # both on = working
mkdir -p $CARD
mount -t vfat /dev/mmcblk0p1 $CARD 2>/dev/null || mount /dev/mmcblk0p1 $CARD || fail "mount card"
# The boot region lives in mtd0 on this board; write absolute offsets with
# flash_erase + nandwrite (same physical NAND the network installer targets).
write_slot() {{ # name file abs_offset
f="$CARD/bin/$2"
[ -s "$f" ] || fail "missing $2 on card"
flash_erase $MTD $3 0 >/dev/null 2>&1 || fail "erase $1"
nandwrite -p -s $3 $MTD "$f" >/dev/null 2>&1 || fail "write $1"
}}
write_slot dtb devicetree.dtb $OFF_DTB
write_slot kernel uImage $OFF_KERNEL
write_slot rootfs uramdisk.image.gz $OFF_ROOTFS
sync
umount $CARD 2>/dev/null || true
# Success: solid green, red off -> safe to power off and remove the card.
led $LED_RED 0; led $LED_GRN 1
echo "alkane-sd-install: done -- remove the card and reboot into alkane" >&2
# Blink green to make "done" unmistakable, matching the vendor flasher's cue.
while true; do led $LED_GRN 1; sleep 1; led $LED_GRN 0; sleep 1; done
"#,
off_dtb = ZYNQ_OFF_DTB,
off_kernel = ZYNQ_OFF_KERNEL,
off_rootfs = ZYNQ_OFF_ROOTFS,
)
}
/// Build the installer initramfs by injecting the install hook into the afw
/// rootfs cpio.gz as a BusyBox-init start script (`/etc/init.d/S99alkane-sd-install`)
/// and recompressing. Uses `gzip`/`cpio` (newc format, standard initramfs).
fn build_installer_initramfs(rootfs_cpio_gz: &[u8], script: &str) -> Result<Vec<u8>> {
let gzip = find_tool("gzip")?;
let gunzip = find_tool("gunzip").or_else(|_| find_tool("gzip"))?;
let cpio = find_tool("cpio")?;
let work = tempdir::TempHold::new()?;
let root = work.path().join("root");
fs::create_dir_all(root.join("etc/init.d"))?;
// 1. Decompress + unpack the afw rootfs into `root/`.
let gz_path = work.path().join("rootfs.cpio.gz");
fs::write(&gz_path, rootfs_cpio_gz)?;
let cpio_path = work.path().join("rootfs.cpio");
{
// gunzip -c rootfs.cpio.gz > rootfs.cpio
let out = Command::new(&gunzip)
.arg("-c")
.arg(&gz_path)
.output()
.map_err(|e| MediaError::Command(format!("gunzip: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command("gunzip rootfs failed".into()));
}
fs::write(&cpio_path, &out.stdout)?;
}
{
// cd root && cpio -idm < ../rootfs.cpio
let cpio_in = fs::File::open(&cpio_path)?;
let status = Command::new(&cpio)
.args(["-i", "-d", "-m", "--no-absolute-filenames"])
.current_dir(&root)
.stdin(cpio_in)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map_err(|e| MediaError::Command(format!("cpio -i: {e}")))?;
if !status.success() {
return Err(MediaError::Command("cpio unpack failed".into()));
}
}
// 2. Inject the install hook, executable.
let hook = root.join("etc/init.d/S99alkane-sd-install");
fs::write(&hook, script.as_bytes())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&hook, fs::Permissions::from_mode(0o755))?;
}
// 3. Repack: (cd root && find . | cpio -o -H newc) | gzip
let repacked_cpio = {
let find = Command::new(find_tool("find")?)
.arg(".")
.current_dir(&root)
.output()
.map_err(|e| MediaError::Command(format!("find: {e}")))?;
if !find.status.success() {
return Err(MediaError::Command("find failed".into()));
}
let mut child = Command::new(&cpio)
.args(["-o", "-H", "newc"])
.current_dir(&root)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?;
child
.stdin
.take()
.ok_or_else(|| MediaError::Command("cpio -o: no stdin".into()))?
.write_all(&find.stdout)?;
let out = child
.wait_with_output()
.map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command("cpio repack failed".into()));
}
out.stdout
};
let gz = {
let mut child = Command::new(&gzip)
.args(["-9", "-c"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.map_err(|e| MediaError::Command(format!("gzip: {e}")))?;
child
.stdin
.take()
.ok_or_else(|| MediaError::Command("gzip: no stdin".into()))?
.write_all(&repacked_cpio)?;
let out = child
.wait_with_output()
.map_err(|e| MediaError::Command(format!("gzip: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command("gzip repack failed".into()));
}
out.stdout
};
Ok(gz)
}
/// Build an alkane **installer** card for a Zynq board from raw afw parts: it
/// boots an installer-OS (the afw rootfs + an install hook), writes alkane into
/// the board's NAND (BOOT.bin preserved), LED-signals "done", and halts so the
/// operator pulls the card and boots internal alkane. The boot trio runs the
/// installer-OS; the `bin/` payload is what the hook writes to NAND.
pub fn build_zynq_installer_card_from_parts(
kernel_zimage: &[u8],
fdt: &[u8],
rootfs_cpio_gz: &[u8],
out_img: &Path,
time: u32,
) -> Result<()> {
// Boot trio: alkane kernel + dtb + installer initramfs (rootfs + hook).
let installer_rd = build_installer_initramfs(rootfs_cpio_gz, &zynq_install_script())?;
let boot_uimage = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane-installer");
let boot_uramdisk = uimage::wrap(Kind::Ramdisk, &installer_rd, time, "alkane-installer-rd");
// NAND payload (bin/): exactly what gets written to the board's boot slots.
let nand_kernel = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane");
let nand_rootfs = uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs");
let card = CardImage::create(out_img, 256, "ALKANEINST")?;
card.write_bytes(&boot_uimage, "uImage")?;
card.write_bytes(fdt, "devicetree.dtb")?;
card.write_bytes(&boot_uramdisk, "uramdisk.image.gz")?;
card.mkdir("bin")?;
card.write_bytes(&nand_kernel, "bin/uImage")?;
card.write_bytes(fdt, "bin/devicetree.dtb")?;
card.write_bytes(&nand_rootfs, "bin/uramdisk.image.gz")?;
Ok(())
}
/// Build an alkane installer card from a verified `.afw`.
pub fn build_zynq_installer_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> {
let (k, d, r) = zynq_afw_parts(afw)?;
build_zynq_installer_card_from_parts(k, d, r, out_img, time)
}
/// Write a finished card image to a block device with `dd`. **Destructive** --
/// the caller is responsible for confirming `device` is the intended removable
/// card (never a system disk). This never runs as part of image building.
pub fn write_image_to_device(img: &Path, device: &Path) -> Result<()> {
if !img.is_file() {
return Err(MediaError::MissingSource(img.display().to_string()));
}
let dd = find_tool("dd")?;
let mut cmd = Command::new(dd);
cmd.arg(format!("if={}", img.display()))
.arg(format!("of={}", device.display()))
.arg("bs=4M")
.arg("oflag=direct")
.arg("conv=fsync");
run(cmd, &format!("dd to {}", device.display()))
}
/// A minimal owned temp directory that removes itself on drop (the crate avoids
/// pulling a tempdir dependency; this mirrors the small helper style used
/// elsewhere).
mod tempdir {
use std::path::{Path, PathBuf};
pub struct TempHold {
path: PathBuf,
}
impl TempHold {
pub fn new() -> std::io::Result<TempHold> {
let base = std::env::temp_dir();
// Unique-ish without pulling rand: pid + a monotonic counter.
use std::sync::atomic::{AtomicU64, Ordering};
static CTR: AtomicU64 = AtomicU64::new(0);
let n = CTR.fetch_add(1, Ordering::Relaxed);
let dir = base.join(format!("alkane-media-{}-{}", std::process::id(), n));
std::fs::create_dir_all(&dir)?;
Ok(TempHold { path: dir })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempHold {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn write(p: &Path, bytes: &[u8]) {
if let Some(parent) = p.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(p, bytes).unwrap();
}
/// Build a fake vendor SD-recovery package (nested like the real one) and
/// assemble a stock-recovery card image from it, then read the card back
/// with `mdir`/`mtype` and confirm the layout and content survived.
///
/// Host-tool test: unix only. On a Windows target (incl. the Wine CI run)
/// the card-building tools are unix binaries that a Windows process cannot
/// exec, and `find_tool` would see them as present in the shared container
/// filesystem, so these are cfg'd out rather than skipped at runtime.
#[cfg(unix)]
#[test]
fn builds_a_stock_recovery_card_from_a_vendor_package() {
// Skip cleanly if the host lacks the tools (keeps CI green where the
// image toolchain is unavailable; the alkane-ci image carries them).
for t in ["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"] {
if find_tool(t).is_err() {
eprintln!("skipping: {t} not available");
return;
}
}
let tmp = tempdir::TempHold::new().unwrap();
let pkg = tmp.path().join("SD_S17/inner");
// Flasher-OS trio at the card root.
write(&pkg.join("uImage"), b"FLASHER-KERNEL-xxxxxxxx");
write(&pkg.join("devicetree.dtb"), b"FLASHER-DTB");
write(&pkg.join("uramdisk.image.gz"), b"FLASHER-RAMDISK");
write(&pkg.join("README.md"), b"vendor notes");
// bin/ NAND payload.
write(&pkg.join("bin/BOOT.bin"), b"BOOTBIN-PAYLOAD");
write(&pkg.join("bin/devicetree.dtb"), b"MINER-DTB");
write(&pkg.join("bin/uImage"), b"MINER-KERNEL");
write(&pkg.join("bin/uramdisk.image.gz"), b"MINER-RAMDISK");
write(&pkg.join("bin/passwd.txt"), b"root\n");
let out = tmp.path().join("card.img");
build_stock_recovery_card(tmp.path(), &out).unwrap();
assert!(out.is_file());
// Read the card back via mtools against the partition at offset 1 MiB.
let mtoolsrc = tmp.path().join("verify.conf");
fs::write(
&mtoolsrc,
format!(
"drive C: file=\"{}\" offset={}\n",
out.display(),
PART_OFFSET_BYTES
),
)
.unwrap();
let mdir = find_tool("mdir").unwrap();
let listing = Command::new(&mdir)
.env("MTOOLSRC", &mtoolsrc)
.env("MTOOLS_SKIP_CHECK", "1")
.args(["-/", "C:/"])
.output()
.unwrap();
let text = String::from_utf8_lossy(&listing.stdout);
for name in ["UIMAGE", "DEVICETREE", "URAMDISK", "BIN", "BOOT"] {
assert!(
text.to_uppercase().contains(name),
"card listing missing {name}:\n{text}"
);
}
// Content check: bin/BOOT.bin round-trips.
let mtype = find_tool("mtype").unwrap();
let got = Command::new(&mtype)
.env("MTOOLSRC", &mtoolsrc)
.env("MTOOLS_SKIP_CHECK", "1")
.arg("C:/bin/BOOT.bin")
.output()
.unwrap();
assert_eq!(
String::from_utf8_lossy(&got.stdout).trim_end(),
"BOOTBIN-PAYLOAD"
);
}
#[test]
fn rejects_a_package_with_no_card_layout() {
let tmp = tempdir::TempHold::new().unwrap();
write(&tmp.path().join("random/file.txt"), b"nope");
let out = tmp.path().join("card.img");
let err = build_stock_recovery_card(tmp.path(), &out).unwrap_err();
assert!(matches!(err, MediaError::BadPackage(_)));
}
#[test]
fn sanitizes_volume_labels() {
assert_eq!(sanitize_label("alkane install!!"), "ALKANEINSTA");
assert_eq!(sanitize_label(""), "ALKANE");
assert_eq!(sanitize_label("ANTMINER"), "ANTMINER");
}
#[cfg(unix)]
fn have_tools(tools: &[&str]) -> bool {
tools.iter().all(|t| find_tool(t).is_ok())
}
/// A minimal gzipped newc cpio containing `etc/` + a probe file, to stand in
/// for an afw rootfs in the installer-initramfs tests.
#[cfg(unix)]
fn fake_cpio_gz(dir: &Path) -> Vec<u8> {
fs::create_dir_all(dir.join("etc/init.d")).unwrap();
fs::write(dir.join("probe"), b"hello-rootfs").unwrap();
let find = Command::new(find_tool("find").unwrap())
.arg(".")
.current_dir(dir)
.output()
.unwrap();
let mut cpio = Command::new(find_tool("cpio").unwrap())
.args(["-o", "-H", "newc"])
.current_dir(dir)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
cpio.stdin.take().unwrap().write_all(&find.stdout).unwrap();
let archive = cpio.wait_with_output().unwrap().stdout;
let mut gz = Command::new(find_tool("gzip").unwrap())
.args(["-c"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
gz.stdin.take().unwrap().write_all(&archive).unwrap();
gz.wait_with_output().unwrap().stdout
}
#[cfg(unix)]
fn uimage_magic(bytes: &[u8]) -> bool {
bytes.len() >= 4 && bytes[0..4] == [0x27, 0x05, 0x19, 0x56]
}
#[cfg(unix)]
fn mtype_bytes(img: &Path, card_path: &str) -> Vec<u8> {
let tmp = tempdir::TempHold::new().unwrap();
let rc = tmp.path().join("rc");
fs::write(
&rc,
format!(
"drive C: file=\"{}\" offset={}\n",
img.display(),
PART_OFFSET_BYTES
),
)
.unwrap();
Command::new(find_tool("mtype").unwrap())
.env("MTOOLSRC", &rc)
.env("MTOOLS_SKIP_CHECK", "1")
.arg(format!("C:/{card_path}"))
.output()
.unwrap()
.stdout
}
#[cfg(unix)]
#[test]
fn injects_install_hook_into_initramfs() {
if !have_tools(&["cpio", "gzip", "gunzip", "find"]) {
eprintln!("skipping: cpio/gzip toolchain unavailable");
return;
}
let tmp = tempdir::TempHold::new().unwrap();
let src = fake_cpio_gz(&tmp.path().join("src"));
let out =
build_installer_initramfs(&src, "#!/bin/sh\necho alkane-sd-install marker\n").unwrap();
// Unpack the result and confirm the hook landed executable with content,
// and the original rootfs file survived.
let gz = tmp.path().join("out.cpio.gz");
fs::write(&gz, &out).unwrap();
let unz = Command::new(find_tool("gunzip").unwrap())
.arg("-c")
.arg(&gz)
.output()
.unwrap();
let cpio_f = tmp.path().join("out.cpio");
fs::write(&cpio_f, &unz.stdout).unwrap();
let ex = tmp.path().join("ex");
fs::create_dir_all(&ex).unwrap();
let st = Command::new(find_tool("cpio").unwrap())
.args(["-i", "-d", "-m", "--no-absolute-filenames"])
.current_dir(&ex)
.stdin(fs::File::open(&cpio_f).unwrap())
.stderr(std::process::Stdio::null())
.status()
.unwrap();
assert!(st.success());
let hook = ex.join("etc/init.d/S99alkane-sd-install");
assert!(
hook.is_file(),
"install hook not present in repacked initramfs"
);
assert!(fs::read_to_string(&hook)
.unwrap()
.contains("alkane-sd-install marker"));
assert!(ex.join("probe").is_file(), "original rootfs content lost");
}
#[cfg(unix)]
#[test]
fn builds_a_zynq_simpleboot_card() {
if !have_tools(&["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"]) {
return;
}
let tmp = tempdir::TempHold::new().unwrap();
let out = tmp.path().join("sb.img");
build_zynq_simpleboot_card_from_parts(
b"ZIMAGE-KERNEL-BYTES",
b"ALKANE-FDT",
b"ROOTFS-CPIO-GZ",
&out,
0,
)
.unwrap();
// uImage and uramdisk are legacy-uImage wrapped; dtb is raw.
assert!(uimage_magic(&mtype_bytes(&out, "uImage")));
assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz")));
assert_eq!(mtype_bytes(&out, "devicetree.dtb"), b"ALKANE-FDT");
}
#[cfg(unix)]
#[test]
fn builds_a_zynq_installer_card() {
if !have_tools(&[
"sfdisk",
"mkfs.vfat",
"mcopy",
"mmd",
"mdir",
"mtype",
"cpio",
"gzip",
"gunzip",
"find",
]) {
return;
}
let tmp = tempdir::TempHold::new().unwrap();
let rootfs = fake_cpio_gz(&tmp.path().join("src"));
let out = tmp.path().join("inst.img");
build_zynq_installer_card_from_parts(b"ZIMAGE", b"FDT", &rootfs, &out, 0).unwrap();
// Boot trio present (uImage-wrapped kernel + installer initramfs).
assert!(uimage_magic(&mtype_bytes(&out, "uImage")));
assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz")));
// NAND payload under bin/ present and wrapped where expected.
assert!(uimage_magic(&mtype_bytes(&out, "bin/uImage")));
assert!(uimage_magic(&mtype_bytes(&out, "bin/uramdisk.image.gz")));
assert_eq!(mtype_bytes(&out, "bin/devicetree.dtb"), b"FDT");
}
#[test]
fn install_script_targets_the_boot_slots_and_preserves_bootbin() {
let s = zynq_install_script();
assert!(s.contains("OFF_DTB=0x1a00000"));
assert!(s.contains("OFF_KERNEL=0x2000000"));
assert!(s.contains("OFF_ROOTFS=0x2800000"));
// BOOT.bin region (below 0x1a00000) must never be a write target.
assert!(!s.contains("0x0 "));
assert!(s.contains("941") && s.contains("942")); // LED GPIOs
}
}
+477
View File
@@ -0,0 +1,477 @@
// SPDX-License-Identifier: MIT
//! 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
//! runtime dependency on any other tool. A user's machine needs only this
//! binary.
//!
//! 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, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StockError {
#[error("the stock method is not implemented in this build")]
NotImplemented,
#[error("could not reach the board: {0}")]
Network(String),
#[error("authentication failed: {0}")]
Auth(String),
#[error("the stock method failed: {0}")]
Method(String),
#[error("io: {0}")]
Io(String),
#[error("not applicable to this board; use the compiled-in method")]
NotApplicable,
}
/// 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
/// installed with alkane; the caller verifies liveness.
fn install_from_stock(
&self,
host: &str,
afw_path: &Path,
afw: &VerifiedAfw,
password: Option<&str>,
) -> Result<(), StockError>;
/// Return an aftermarket (alkane) board to genuine stock, over the network
/// 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.
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,
afw_path: &Path,
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) 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)]
mod tests {
use super::*;
// 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
+699
View File
@@ -0,0 +1,699 @@
// SPDX-License-Identifier: MIT
//! Network transport for the CV1835 installer.
//!
//! Two root channels are implemented, both over the network:
//!
//! * `direct`: the SSH login is already uid 0 (Braiins OS, ourOS/alkane with a
//! root key, or an operator-supplied root login).
//! * `update-daemon`: stock Bitmain (and Vnish, which runs on the stock
//! kernel) exposes an SSH login as `miner` (uid 1001). `/usr/sbin/update-daemon`
//! listens on 127.0.0.1:12887 and pipes its socket into `system()` as root.
//! We reach it through an SSH local forward, exactly as documented in the RE
//! notes (`cv-kvm-host` / `cvbuild/cvroot.py`,
//! `alkane-sdk-wiki/40-boot-os-and-build/cross-install-matrix.md`). The
//! channel is blind, so root output is redirected to a world-readable file
//! and read back over the unprivileged SSH session.
//! * `rroot`: an existing `/nvdata/rroot` setuid helper on CV stock/Vnish,
//! documented in `60-reverse-engineering-methods/rroot-setuid-escalation.md`.
//! It is a fallback because the helper is not durable across a p7 reformat.
//!
//! Credentials are never read here: a password is used only through
//! `sshpass -f <path>`, and that path comes from the operator (environment
//! variable materialized by the CLI, or a file named on the command line).
use std::fs;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use thiserror::Error;
const MAX_CAPTURE: usize = 64 * 1024 * 1024;
#[derive(Debug, Error)]
pub enum RemoteError {
#[error("remote I/O: {0}")]
Io(#[from] std::io::Error),
#[error("cannot start {0}")]
MissingTool(&'static str),
#[error("invalid target: {0}")]
InvalidTarget(String),
#[error("SSH transport: {0}")]
Ssh(String),
#[error("SSH command timed out after {0:?}")]
Timeout(Duration),
#[error("remote command failed ({status}): {stderr}")]
Command { status: String, stderr: String },
#[error("root access was not obtained: {0}")]
NotRoot(String),
#[error("no network root channel is available on this board")]
NoRootMethod,
#[error("update-daemon: {0}")]
Daemon(String),
#[error("remote output is over the {0}-byte cap")]
OutputTooLarge(usize),
}
impl RemoteError {
fn sanitize(text: &str) -> String {
let text = text.trim();
let mut shortened: String = text.chars().take(300).collect();
if shortened.len() < text.len() {
shortened.push_str("...");
}
shortened
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RootMethod {
Auto,
Direct,
UpdateDaemon,
Rroot,
}
impl RootMethod {
pub fn parse(value: &str) -> Option<Self> {
match value {
"auto" => Some(Self::Auto),
"direct" => Some(Self::Direct),
"update-daemon" => Some(Self::UpdateDaemon),
"rroot" => Some(Self::Rroot),
_ => None,
}
}
}
#[derive(Clone, Debug)]
pub struct SshOptions {
pub host: String,
pub port: u16,
pub user: String,
pub identity_file: Option<PathBuf>,
pub password_file: Option<PathBuf>,
pub known_hosts: Option<PathBuf>,
pub root_method: RootMethod,
pub update_daemon_port: Option<u16>,
}
impl Default for SshOptions {
fn default() -> Self {
Self {
host: String::new(),
port: 22,
user: "miner".to_owned(),
identity_file: None,
password_file: None,
known_hosts: None,
root_method: RootMethod::Auto,
update_daemon_port: None,
}
}
}
impl SshOptions {
fn validate(&self) -> Result<(), RemoteError> {
if self.host.is_empty()
|| self.host.len() > 253
|| self.host.starts_with('-')
|| !self.host.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b':' | b'_')
})
{
return Err(RemoteError::InvalidTarget("host".to_owned()));
}
if self.user.is_empty()
|| !self
.user
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
{
return Err(RemoteError::InvalidTarget("user".to_owned()));
}
if self.port == 0 {
return Err(RemoteError::InvalidTarget("port".to_owned()));
}
if let Some(path) = &self.password_file {
if !path.is_file() {
return Err(RemoteError::InvalidTarget(format!(
"password file not found: {}",
path.display()
)));
}
}
Ok(())
}
}
enum Strategy {
Direct,
Rroot,
UpdateDaemon {
local_port: u16,
remote_port: u16,
tunnel: Child,
},
}
impl Drop for Strategy {
fn drop(&mut self) {
if let Self::UpdateDaemon { tunnel, .. } = self {
let _ = tunnel.kill();
let _ = tunnel.wait();
}
}
}
pub struct SshTransport {
options: SshOptions,
known_hosts: PathBuf,
strategy: Strategy,
counter: u64,
}
impl SshTransport {
/// Open a session and (when `require_root`) prove a uid-0 channel.
pub fn connect(options: SshOptions, require_root: bool) -> Result<Self, RemoteError> {
options.validate()?;
let known_hosts = options
.known_hosts
.clone()
.unwrap_or_else(|| alkane_core::platform::config_path("known_hosts"));
if let Some(parent) = known_hosts.parent() {
fs::create_dir_all(parent)?;
}
if !known_hosts.exists() {
fs::write(&known_hosts, b"")?;
}
if options.password_file.is_some() {
Command::new("sshpass")
.arg("-V")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map_err(|_| RemoteError::MissingTool("sshpass"))?;
}
let mut transport = Self {
options,
known_hosts,
strategy: Strategy::Direct,
counter: 0,
};
let identity = transport.user_command("uname -r", Duration::from_secs(15))?;
let _ = identity;
if !require_root {
return Ok(transport);
}
let uid =
String::from_utf8_lossy(&transport.user_command("id -u", Duration::from_secs(15))?)
.trim()
.to_owned();
let direct = uid == "0";
let method = match transport.options.root_method {
RootMethod::Auto if direct => RootMethod::Direct,
RootMethod::Auto => {
if transport.has_update_daemon()? {
RootMethod::UpdateDaemon
} else if transport.has_rroot()? {
RootMethod::Rroot
} else {
return Err(RemoteError::NoRootMethod);
}
}
other => other,
};
match method {
RootMethod::Direct => {
if !direct {
return Err(RemoteError::NotRoot(
"the SSH login is not uid 0; use --root-method auto, update-daemon or rroot"
.to_owned(),
));
}
transport.strategy = Strategy::Direct;
}
RootMethod::Rroot => {
if !transport.has_rroot()? {
return Err(RemoteError::NotRoot(
"/nvdata/rroot is not present or not executable".to_owned(),
));
}
transport.strategy = Strategy::Rroot;
}
RootMethod::UpdateDaemon => {
if !transport.has_update_daemon()? {
return Err(RemoteError::NotRoot(
"/usr/sbin/update-daemon is not present".to_owned(),
));
}
let remote_port = transport
.options
.update_daemon_port
.unwrap_or(transport.detect_update_daemon_port()?);
let (local_port, tunnel) = transport.start_tunnel(remote_port)?;
transport.strategy = Strategy::UpdateDaemon {
local_port,
remote_port,
tunnel,
};
}
RootMethod::Auto => unreachable!(),
}
let root_output = transport.root_command("id", Duration::from_secs(20))?;
let root = String::from_utf8_lossy(&root_output);
if !root.contains("uid=0") {
return Err(RemoteError::NotRoot(
"the selected channel did not return uid=0".to_owned(),
));
}
Ok(transport)
}
pub fn channel(&self) -> String {
format!("ssh:{}@{}", self.options.user, self.options.host)
}
pub fn root_method(&self) -> &'static str {
match &self.strategy {
Strategy::Direct => "direct",
Strategy::Rroot => "rroot",
Strategy::UpdateDaemon { .. } => "update-daemon",
}
}
pub fn update_daemon_port(&self) -> Option<u16> {
match &self.strategy {
Strategy::UpdateDaemon { remote_port, .. } => Some(*remote_port),
_ => None,
}
}
fn ssh_base(&self) -> Command {
let mut command = if let Some(password) = &self.options.password_file {
let mut command = Command::new("sshpass");
command.arg("-f").arg(password).arg("ssh");
command
} else {
Command::new("ssh")
};
command
.arg("-F")
.arg("none")
.arg("-o")
.arg(if self.options.password_file.is_some() {
"BatchMode=no"
} else {
"BatchMode=yes"
})
.arg("-o")
.arg("StrictHostKeyChecking=accept-new")
.arg("-o")
.arg(format!("UserKnownHostsFile={}", self.known_hosts.display()))
.arg("-o")
.arg("GlobalKnownHostsFile=/dev/null")
.arg("-o")
.arg("ConnectTimeout=10")
.arg("-o")
.arg("ServerAliveInterval=5")
.arg("-o")
.arg("ServerAliveCountMax=3")
.arg("-o")
.arg("RequestTTY=no")
.arg("-o")
.arg("LogLevel=ERROR")
.arg("-o")
.arg("NumberOfPasswordPrompts=1")
.arg("-o")
.arg("PreferredAuthentications=publickey,password,keyboard-interactive");
if let Some(identity) = &self.options.identity_file {
command
.arg("-i")
.arg(identity)
.arg("-o")
.arg("IdentitiesOnly=yes");
}
command
}
fn ssh_command(&self, command: &str) -> Command {
let mut child = self.ssh_base();
child
.arg("-p")
.arg(self.options.port.to_string())
.arg(format!("{}@{}", self.options.user, self.options.host))
.arg(command);
child
}
fn run_user(&self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
let (stdout, stderr, status) = run_bounded(self.ssh_command(command), timeout)?;
if !status.success() {
return Err(RemoteError::Command {
status: status.to_string(),
stderr: RemoteError::sanitize(&String::from_utf8_lossy(&stderr)),
});
}
Ok(stdout)
}
fn has_rroot(&self) -> Result<bool, RemoteError> {
let out = self.run_user(
"test -x /nvdata/rroot && echo yes || echo no",
Duration::from_secs(15),
)?;
Ok(String::from_utf8_lossy(&out).contains("yes"))
}
fn has_update_daemon(&self) -> Result<bool, RemoteError> {
let out = self.run_user(
"test -x /usr/sbin/update-daemon && echo yes || echo no",
Duration::from_secs(15),
)?;
Ok(String::from_utf8_lossy(&out).contains("yes"))
}
fn detect_update_daemon_port(&self) -> Result<u16, RemoteError> {
let out = self.run_user(
"cat /proc/net/tcp /proc/net/tcp6 2>/dev/null || true",
Duration::from_secs(15),
)?;
let text = String::from_utf8_lossy(&out);
for line in text.lines() {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() < 4 || fields[3] != "0A" {
continue;
}
let local = fields[1];
let port = local.rsplit(':').next().unwrap_or("");
let port = u16::from_str_radix(port, 16).unwrap_or(0);
if port == 12887 || port == 22026 {
return Ok(port);
}
}
// The CV1835 stock build listens on 12887. The fallback keeps the
// explicit --update-daemon-port option available for other builds.
Ok(12887)
}
fn start_tunnel(&self, remote_port: u16) -> Result<(u16, Child), RemoteError> {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
let local_port = listener.local_addr()?.port();
drop(listener);
let mut command = self.ssh_base();
command
.arg("-N")
.arg("-o")
.arg("ExitOnForwardFailure=yes")
.arg("-L")
.arg(format!("127.0.0.1:{local_port}:127.0.0.1:{remote_port}"))
.arg("-p")
.arg(self.options.port.to_string())
.arg(format!("{}@{}", self.options.user, self.options.host))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
let mut tunnel = command.spawn()?;
let deadline = Instant::now() + Duration::from_secs(20);
loop {
if TcpStream::connect_timeout(
&SocketAddr::from(([127, 0, 0, 1], local_port)),
Duration::from_millis(500),
)
.is_ok()
{
return Ok((local_port, tunnel));
}
if let Some(status) = tunnel.try_wait()? {
return Err(RemoteError::Daemon(format!(
"SSH forward exited before it was ready ({status})"
)));
}
if Instant::now() >= deadline {
let _ = tunnel.kill();
return Err(RemoteError::Daemon(
"SSH forward did not become ready".to_owned(),
));
}
thread::sleep(Duration::from_millis(250));
}
}
fn daemon_send(&self, command: &str) -> Result<(), RemoteError> {
let Strategy::UpdateDaemon { local_port, .. } = &self.strategy else {
return Err(RemoteError::Daemon("not using update-daemon".to_owned()));
};
let local_port = *local_port;
if command.contains('\n') || command.contains('\r') {
return Err(RemoteError::Daemon("command contains a newline".to_owned()));
}
let mut stream = TcpStream::connect_timeout(
&SocketAddr::from(([127, 0, 0, 1], local_port)),
Duration::from_secs(10),
)?;
stream.set_write_timeout(Some(Duration::from_secs(10)))?;
stream.write_all(format!(";{command};").as_bytes())?;
stream.flush()?;
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
let mut sink = [0_u8; 256];
let _ = stream.read(&mut sink);
Ok(())
}
fn daemon_capture(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
let path = format!("/tmp/.alkane-root-{}-{}", std::process::id(), self.counter);
self.counter += 1;
let wrapped = format!("{{ {command} ; }} > {path} 2>&1; chmod 644 {path}");
self.daemon_send(&wrapped)?;
let deadline = Instant::now() + timeout;
loop {
let probe = format!("test -f {path} && echo ready || true");
let out = self.run_user(&probe, Duration::from_secs(15))?;
if String::from_utf8_lossy(&out).contains("ready") {
break;
}
if Instant::now() >= deadline {
return Err(RemoteError::Daemon(format!(
"root command produced no output file within {timeout:?}"
)));
}
thread::sleep(Duration::from_millis(200));
}
let output = self.run_user(&format!("cat {path}"), Duration::from_secs(60))?;
let _ = self.run_user(&format!("rm -f {path}"), Duration::from_secs(15));
Ok(output)
}
fn daemon_reboot(&mut self) -> Result<(), RemoteError> {
self.daemon_send("sync; echo b > /proc/sysrq-trigger")
}
}
impl Remote for SshTransport {
fn channel(&self) -> &str {
"ssh"
}
fn root_method(&self) -> &'static str {
SshTransport::root_method(self)
}
fn user_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
self.run_user(command, timeout)
}
fn root_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
match self.root_method() {
"direct" => self.run_user(command, timeout),
"rroot" => {
let wrapped = format!("/nvdata/rroot -c {}", shell_quote(command));
self.run_user(&wrapped, timeout)
}
"update-daemon" => self.daemon_capture(command, timeout),
_ => Err(RemoteError::NoRootMethod),
}
}
fn push(&mut self, local: &Path, remote: &str, timeout: Duration) -> Result<(), RemoteError> {
let remote = safe_remote_path(remote)?;
let mut command = self.ssh_command(&format!("cat > {remote}"));
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let mut stdin = child.stdin.take().expect("piped stdin");
let path = local.to_path_buf();
let writer = thread::spawn(move || -> std::io::Result<()> {
let mut source = fs::File::open(path)?;
let mut buffer = [0_u8; 64 * 1024];
loop {
let read = source.read(&mut buffer)?;
if read == 0 {
break;
}
stdin.write_all(&buffer[..read])?;
}
stdin.flush()
});
let (stdout, stderr) = read_pipes(&mut child);
let status = wait_timeout(&mut child, timeout)?;
let _ = writer.join();
let _ = stdout.join();
let stderr = stderr.join().unwrap_or_default();
if !status.success() {
return Err(RemoteError::Command {
status: status.to_string(),
stderr: RemoteError::sanitize(&String::from_utf8_lossy(&stderr)),
});
}
Ok(())
}
fn pull(&mut self, remote: &str, local: &Path, timeout: Duration) -> Result<(), RemoteError> {
let remote = safe_remote_path(remote)?;
let data = self.run_user(&format!("cat {remote}"), timeout)?;
if data.len() > MAX_CAPTURE {
return Err(RemoteError::OutputTooLarge(MAX_CAPTURE));
}
fs::write(local, data)?;
Ok(())
}
fn reboot(&mut self) -> Result<(), RemoteError> {
match self.root_method() {
"update-daemon" => self.daemon_reboot(),
_ => {
// A successful sysrq reset drops the SSH connection mid-command.
let _ = self.run_user(
"sync; echo b > /proc/sysrq-trigger",
Duration::from_secs(15),
);
Ok(())
}
}
}
}
pub trait Remote {
fn channel(&self) -> &str;
fn root_method(&self) -> &'static str {
"network"
}
fn user_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError>;
fn root_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError>;
fn push(&mut self, local: &Path, remote: &str, timeout: Duration) -> Result<(), RemoteError>;
fn pull(&mut self, remote: &str, local: &Path, timeout: Duration) -> Result<(), RemoteError>;
fn reboot(&mut self) -> Result<(), RemoteError>;
}
pub fn shell_quote(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\\''"))
}
pub fn safe_remote_path(path: &str) -> Result<&str, RemoteError> {
if !path.starts_with('/')
|| path.len() > 200
|| path.contains("..")
|| !path
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'_' | b'-'))
{
return Err(RemoteError::InvalidTarget(format!(
"unsafe remote path: {path}"
)));
}
Ok(path)
}
fn read_pipes(child: &mut Child) -> (thread::JoinHandle<Vec<u8>>, thread::JoinHandle<Vec<u8>>) {
let mut stdout = child.stdout.take().expect("piped stdout");
let mut stderr = child.stderr.take().expect("piped stderr");
let out = thread::spawn(move || {
let mut data = Vec::new();
let _ = stdout.read_to_end(&mut data);
data
});
let err = thread::spawn(move || {
let mut data = Vec::new();
let _ = stderr.read_to_end(&mut data);
data
});
(out, err)
}
fn wait_timeout(child: &mut Child, timeout: Duration) -> Result<ExitStatus, RemoteError> {
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = child.try_wait()? {
return Ok(status);
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return Err(RemoteError::Timeout(timeout));
}
thread::sleep(Duration::from_millis(20));
}
}
fn run_bounded(
mut command: Command,
timeout: Duration,
) -> Result<(Vec<u8>, Vec<u8>, ExitStatus), RemoteError> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let (stdout, stderr) = read_pipes(&mut child);
let status = wait_timeout(&mut child, timeout)?;
let stdout = stdout.join().unwrap_or_default();
let stderr = stderr.join().unwrap_or_default();
if stdout.len() > MAX_CAPTURE {
return Err(RemoteError::OutputTooLarge(MAX_CAPTURE));
}
Ok((stdout, stderr, status))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quotes_shell_arguments_for_rroot() {
assert_eq!(shell_quote("id"), "'id'");
assert_eq!(shell_quote("echo 'x'"), "'echo '\\''x'\\'''");
}
#[test]
fn rejects_option_injection_and_unsafe_paths() {
let mut options = SshOptions {
host: "-oProxyCommand=bad".to_owned(),
user: "root".to_owned(),
..SshOptions::default()
};
assert!(options.validate().is_err());
options.host = "10.255.1.167".to_owned();
options.user = "root;id".to_owned();
assert!(options.validate().is_err());
assert!(safe_remote_path("/tmp/ok.img").is_ok());
assert!(safe_remote_path("relative").is_err());
assert!(safe_remote_path("/tmp/../etc/passwd").is_err());
assert!(safe_remote_path("/tmp/a;b").is_err());
}
#[test]
fn parses_root_methods() {
assert_eq!(RootMethod::parse("auto"), Some(RootMethod::Auto));
assert_eq!(
RootMethod::parse("update-daemon"),
Some(RootMethod::UpdateDaemon)
);
assert_eq!(RootMethod::parse("serial"), None);
}
}
+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"
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><g stroke="currentColor" stroke-width="24" stroke-linecap="round" fill="none"><path d="M256 150 L256 118"/><path d="M256 118 L214 74"/><path d="M256 118 L298 74"/><path d="M168 232 L88 196"/><path d="M164 302 L78 302"/><path d="M168 372 L88 414"/><path d="M344 232 L424 196"/><path d="M348 302 L434 302"/><path d="M344 372 L424 414"/></g><ellipse cx="256" cy="300" rx="96" ry="138" fill="currentColor"/><circle cx="256" cy="162" r="56" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 526 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M448 80l0 48c0 44.2-100.3 80-224 80S0 172.2 0 128L0 80C0 35.8 100.3 0 224 0S448 35.8 448 80zM393.2 214.7c20.8-7.4 39.9-16.9 54.8-28.6L448 288c0 44.2-100.3 80-224 80S0 332.2 0 288L0 186.1c14.9 11.8 34 21.2 54.8 28.6C99.7 230.7 159.5 240 224 240s124.3-9.3 169.2-25.3zM0 346.1c14.9 11.8 34 21.2 54.8 28.6C99.7 390.7 159.5 400 224 400s124.3-9.3 169.2-25.3c20.8-7.4 39.9-16.9 54.8-28.6L448 432c0 44.2-100.3 80-224 80S0 476.2 0 432L0 346.1z"/></svg>

After

Width:  |  Height:  |  Size: 535 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M495.9 166.6c3.2 8.7 .5 18.4-6.4 24.6l-43.3 39.4c1.1 8.3 1.7 16.8 1.7 25.4s-.6 17.1-1.7 25.4l43.3 39.4c6.9 6.2 9.6 15.9 6.4 24.6c-4.4 11.9-9.7 23.3-15.8 34.3l-4.7 8.1c-6.6 11-14 21.4-22.1 31.2c-5.9 7.2-15.7 9.6-24.5 6.8l-55.7-17.7c-13.4 10.3-28.2 18.9-44 25.4l-12.5 57.1c-2 9.1-9 16.3-18.2 17.8c-13.8 2.3-28 3.5-42.5 3.5s-28.7-1.2-42.5-3.5c-9.2-1.5-16.2-8.7-18.2-17.8l-12.5-57.1c-15.8-6.5-30.6-15.1-44-25.4L83.1 425.9c-8.8 2.8-18.6 .3-24.5-6.8c-8.1-9.8-15.5-20.2-22.1-31.2l-4.7-8.1c-6.1-11-11.4-22.4-15.8-34.3c-3.2-8.7-.5-18.4 6.4-24.6l43.3-39.4C64.6 273.1 64 264.6 64 256s.6-17.1 1.7-25.4L22.4 191.2c-6.9-6.2-9.6-15.9-6.4-24.6c4.4-11.9 9.7-23.3 15.8-34.3l4.7-8.1c6.6-11 14-21.4 22.1-31.2c5.9-7.2 15.7-9.6 24.5-6.8l55.7 17.7c13.4-10.3 28.2-18.9 44-25.4l12.5-57.1c2-9.1 9-16.3 18.2-17.8C227.3 1.2 241.5 0 256 0s28.7 1.2 42.5 3.5c9.2 1.5 16.2 8.7 18.2 17.8l12.5 57.1c15.8 6.5 30.6 15.1 44 25.4l55.7-17.7c8.8-2.8 18.6-.3 24.5 6.8c8.1 9.8 15.5 20.2 22.1 31.2l4.7 8.1c6.1 11 11.4 22.4 15.8 34.3zM256 336a80 80 0 1 0 0-160 80 80 0 1 0 0 160z"/></svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M64 0C28.7 0 0 28.7 0 64L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-277.5c0-17-6.7-33.3-18.7-45.3l-90.5-90.5C262.7 6.7 246.5 0 229.5 0L64 0zM96 96c0-8.8 7.2-16 16-16s16 7.2 16 16l0 64c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64zm80 0c0-8.8 7.2-16 16-16s16 7.2 16 16l0 64c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64zm80 0c0-8.8 7.2-16 16-16s16 7.2 16 16l0 64c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64z"/></svg>

After

Width:  |  Height:  |  Size: 498 B

+444
View File
@@ -0,0 +1,444 @@
//! 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()
}
/// Read the raw HTTP response head (status line + headers) of a GET on :80.
async fn http_response_head(ip: IpAddr, path: &str) -> Option<String> {
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; 2048];
loop {
match stream.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(n) => {
raw.extend_from_slice(&chunk[..n]);
if raw.windows(4).any(|w| w == b"\r\n\r\n") || raw.len() > 8192 {
break;
}
}
}
}
})
.await;
let text = String::from_utf8_lossy(&raw);
let head = text.split("\r\n\r\n").next().unwrap_or("").to_string();
(!head.is_empty()).then_some(head)
}
/// A stock Antminer whose miner API (:4028) is down -- e.g. no hashboards, so
/// the miner software is not running -- still serves its vendor web UI on :80
/// with a `Digest realm="antMiner Configuration"` challenge. asic-rs cannot
/// identify such a board without the API, so recognise it here. The control
/// board/model are unknown from :80 alone, so the row is marked stock with an
/// unknown board; the operator picks the control board when flashing.
pub async fn detect_stock_antminer(ip: IpAddr) -> Option<MinerRow> {
let head = http_response_head(ip, "/").await?;
let lower = head.to_ascii_lowercase();
let is_stock_antminer = lower.contains("antminer configuration")
|| (lower.contains("server: lighttpd") && lower.contains(" 401 "));
if !is_stock_antminer {
return None;
}
Some(MinerRow {
ip: ip.to_string(),
brand: "Antminer".to_string(),
model: "Stock (model unknown)".to_string(),
firmware: "Stock".to_string(),
..Default::default()
})
}
/// A stock Antminer the scan could identify as such but whose control board is
/// unknown (e.g. found only by its :80 vendor web UI). Alkane can still be
/// installed once the operator picks the control board, so the install flow
/// offers it with a manual board selector.
pub fn is_unidentified_stock_antminer(row: &MinerRow) -> bool {
row.brand.to_ascii_lowercase().contains("antminer")
&& row.firmware.eq_ignore_ascii_case("Stock")
&& board_family(row).is_none()
}
/// 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, the stock Antminer Zynq-7010 (S17/T17 era,
/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control
/// board.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
// A stock A113D (Amlogic AXG) control board -- the "a113d" install target
// (board_labels maps a113d -> "AML (C76)"). Decided on the control-board
// code, not the brand: asic-rs has no make for the Antminer BHB42XXX and
// reports its brand as "Unknown" (model "Unknown: ANTMINER BHB42XXX"), so
// the generic brand guard below would otherwise reject it. The "AML" code is
// only ever derived for an Amlogic Antminer control board, so this is
// specific on its own.
if row.cpu == "AML" && row.board_code == "C76" {
return Some("a113d".to_string());
}
if !row.brand.to_ascii_lowercase().contains("antminer") {
return None;
}
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))
}
/// Control boards that can boot from removable SD media, so the toolkit can
/// build an "Installation Media" card for them. Zynq-7010 is proven
/// (stock U-Boot card-detect side-load, confirmed on the bench S17 2026-11-17);
/// the Amlogic A113D is deliberately excluded -- it is eMMC-only with no SD slot
/// (USB recovery disabled), so it stays network-only.
pub fn media_supported(row: &MinerRow) -> bool {
matches!(board_family(row).as_deref(), Some("zynq-7010"))
}
#[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
// The Amlogic A113D control board is the "a113d" install target.
assert!(install_supported(&stock("AML", "C76")));
assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d"));
assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
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: an "S17" model on an
// Amlogic A113D control board resolves to a113d (the control board),
// not zynq (the model).
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
cpu: "AML".into(),
board_code: "C76".into(),
..Default::default()
};
assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d"));
}
#[test]
fn an_unidentified_stock_antminer_is_flaggable_for_manual_board_install() {
// As detect_stock_antminer builds it: brand Antminer, Stock, no control
// board (found only by its :80 web UI).
let row = MinerRow {
brand: "Antminer".into(),
model: "Stock (model unknown)".into(),
firmware: "Stock".into(),
..Default::default()
};
assert!(is_unidentified_stock_antminer(&row));
assert!(board_family(&row).is_none());
assert!(!is_alkane(&row));
// A board with a known control board is NOT "unidentified".
let s17 = MinerRow {
brand: "Antminer".into(),
firmware: "Stock".into(),
cpu: "XIL".into(),
board_code: "C49".into(),
..Default::default()
};
assert!(!is_unidentified_stock_antminer(&s17));
// A non-Antminer is never flagged.
let wm = MinerRow {
brand: "WhatsMiner".into(),
firmware: "Stock".into(),
..Default::default()
};
assert!(!is_unidentified_stock_antminer(&wm));
}
#[test]
fn a_stock_a113d_bhb42xxx_is_an_install_target_despite_unknown_brand() {
// Exactly as the live scan reports the bench A113D at 10.255.1.18:
// asic-rs cannot pin a make, so brand is "Unknown" and the model is
// "Unknown: ANTMINER BHB42XXX", but the control board classifies as
// "AML (C76)". Install must still be offered.
let bhb = MinerRow {
brand: "Unknown".into(),
model: "Unknown: ANTMINER BHB42XXX".into(),
firmware: "Stock".into(),
cpu: "AML".into(),
board_code: "C76".into(),
..Default::default()
};
assert_eq!(board_family(&bhb).as_deref(), Some("a113d"));
assert!(install_supported(&bhb));
assert!(!is_alkane(&bhb));
}
/// Live check against a real board:
/// `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));
}
}
+462
View File
@@ -0,0 +1,462 @@
//! 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));
}
}
/// Run the real fleet scan over `range` and report how each board classifies --
/// the scan step a user performs before acting. Returns the rows found.
fn scan_report(range: &str) -> Vec<crate::model::MinerRow> {
use crate::scan::{self, ScanMsg};
println!(" [scan] scanning {range} ...");
let handle = scan::start_scan(vec![range.to_string()], 10);
let mut rows = Vec::new();
loop {
match handle.rx.recv() {
Ok(ScanMsg::Row(r)) => rows.push(r),
Ok(ScanMsg::Done(_)) | Ok(ScanMsg::Failed(_)) => break,
Ok(_) => {}
Err(_) => break,
}
}
rows.sort_by(|a, b| a.ip.cmp(&b.ip));
if rows.is_empty() {
println!(" [scan] no boards found");
}
for r in &rows {
let installable = crate::alkane_detect::install_supported(r)
|| crate::alkane_detect::is_unidentified_stock_antminer(r);
println!(
" [scan] {:<15} brand={:<10} model={:<22} fw={:<7} board={:<10} install={} alkane={}",
r.ip,
r.brand,
r.model,
r.firmware,
r.control_board,
installable,
crate::alkane_detect::is_alkane(r),
);
}
rows
}
/// A full user-flow test driven headlessly through the GUI engine, including the
/// scan step a user performs: scan -> restore to stock -> scan -> install ->
/// scan -> verify the board serves the API and shows as alkane. Spec:
/// `<host> <afw> [scan-range]`.
pub fn run_flow(spec: &str) -> i32 {
let mut it = spec.split_whitespace();
let host = it.next().unwrap_or("").to_string();
let afw = PathBuf::from(it.next().unwrap_or(""));
let range = it.next().unwrap_or("10.255.1.0/24").to_string();
if host.is_empty() || afw.as_os_str().is_empty() {
eprintln!("ALKANE_BENCH_FLOW=\"<host> <afw> [scan-range]\"");
return 2;
}
if !afw.exists() {
eprintln!("afw not found: {}", afw.display());
return 2;
}
let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p);
let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD")
.ok()
.or_else(|| Some("alkane".to_string()));
let boot_timeout = Duration::from_secs(300);
println!("== A113D full GUI-flow test (scan -> restore -> scan -> install -> scan) ==");
let mac = mac_of(&host);
println!("\n[1/6] initial scan (as a user would)");
scan_report(&range);
let (desc, is_stock) = classify(&host);
println!("\n[2/6] target {host}: {desc}");
if is_stock != Some(true) {
println!("[3/6] restore {host} -> stock (flag flip)");
if !drive(
"restore",
stock_ops::start_restore_flag(vec![host.clone()], alkane_password.clone()),
) {
println!("[3/6] restore FAILED; aborting");
return 1;
}
let (_ip, d, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
println!(
" {d} => {}",
if ok { "STOCK" } else { "NOT STOCK (fail)" }
);
if !ok {
return 1;
}
} else {
println!("[3/6] already stock; skipping restore");
}
println!("\n[4/6] scan after restore (board should appear as a stock Antminer)");
scan_report(&range);
println!("\n[5/6] install alkane from stock");
let h = stock_ops::start_install(
vec![host.clone()],
"a113d".to_string(),
AfwSource::Local(afw.clone()),
true,
stock_password.clone(),
false,
);
if !drive("install", h) {
println!("[5/6] install FAILED");
return 1;
}
let (alkane_ip, d, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
println!(
" {d} => {}",
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
);
println!("\n[6/6] scan after install (board should appear as ALKANE via the HTTP API)");
let rows = scan_report(&range);
let seen_alkane = rows
.iter()
.any(|r| crate::alkane_detect::is_alkane(r) && (r.ip == alkane_ip || r.ip == host));
println!(
"\n== FLOW RESULT: {} ==",
if ok && seen_alkane {
"PASS (installed, serves API, visible in scan)"
} else {
"INCOMPLETE (see the scan lines above)"
}
);
if ok && seen_alkane {
0
} else {
1
}
}
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
}
}
+437
View File
@@ -0,0 +1,437 @@
//! Bug reports and feature requests from the toolbar's Bug report button.
//!
//! The app posts the report to the report relay (see tools/report-relay),
//! which holds the Gitea token and files the issue in blueflare/alkane-toolkit.
//! The app itself holds no secret. A report carries its type, the user's text,
//! what the app knows about itself (version, OS, appearance, language, window
//! size) and, if the user leaves it ticked, the recent activity log with
//! credentials scrubbed. Nothing is stored locally.
use std::io::Write;
use std::process::Stdio;
use std::sync::mpsc::{channel, Receiver};
/// Where reports go. `ALKANE_REPORT_URL` overrides it (tests, staging).
pub const DEFAULT_URL: &str = "https://gitea.bluefla.re/alkane-report/v1/report";
/// Longest report text the relay accepts.
pub const MAX_TEXT_CHARS: usize = 8000;
/// Log sent with a report: at most this many of the newest lines...
const LOG_LINES: usize = 80;
/// ...cut to this many bytes on a line boundary.
const LOG_BYTES: usize = 16 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Bug,
Ui,
Feature,
}
impl Kind {
/// In the order the dialog's type choice lists them.
pub const ALL: [Kind; 3] = [Kind::Bug, Kind::Ui, Kind::Feature];
pub fn label(self) -> &'static str {
match self {
Kind::Bug => "Bug",
Kind::Ui => "UI change",
Kind::Feature => "Feature request",
}
}
/// The wire value, which is also the issue label.
pub fn as_str(self) -> &'static str {
match self {
Kind::Bug => "bug",
Kind::Ui => "ui",
Kind::Feature => "feature",
}
}
}
/// What the app knows about itself, sent with every report.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Context {
pub app_version: String,
pub platform: String,
pub os: String,
pub appearance: String,
pub language: String,
pub window: String,
}
impl Context {
/// The running app's context. `window` is the main window's size.
pub fn current(dark: bool, language: &str, window: (i32, i32)) -> Context {
Context {
app_version: env!("CARGO_PKG_VERSION").to_string(),
platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
os: os_version(),
appearance: if dark { "dark" } else { "light" }.to_string(),
language: language.to_string(),
window: format!("{}x{}", window.0, window.1),
}
}
}
/// A human-readable OS name and version, best effort.
fn os_version() -> String {
#[cfg(target_os = "linux")]
{
if let Ok(s) = std::fs::read_to_string("/etc/os-release") {
for line in s.lines() {
if let Some(v) = line.strip_prefix("PRETTY_NAME=") {
return v.trim_matches('"').to_string();
}
}
}
"Linux".to_string()
}
#[cfg(target_os = "macos")]
{
let out = alkane_core::platform::quiet_command("sw_vers")
.arg("-productVersion")
.output();
match out {
Ok(o) if o.status.success() => {
format!("macOS {}", String::from_utf8_lossy(&o.stdout).trim())
}
_ => "macOS".to_string(),
}
}
#[cfg(windows)]
{
let out = alkane_core::platform::quiet_command("cmd")
.args(["/C", "ver"])
.output();
match out {
Ok(o) if o.status.success() => {
let v = String::from_utf8_lossy(&o.stdout).trim().to_string();
if v.is_empty() {
"Windows".to_string()
} else {
v
}
}
_ => "Windows".to_string(),
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
std::env::consts::OS.to_string()
}
}
/// Names whose values are secrets: `name=value`, `name: value` and
/// `"name": "value"` have the value replaced.
const SECRET_NAMES: [&str; 12] = [
"password",
"passwd",
"pass",
"pwd",
"secret",
"token",
"apikey",
"api_key",
"authorization",
"cookie",
"psk",
"credential",
];
/// Remove credentials from log text before it leaves the machine: values of
/// secret-looking names, `user:password@` in URLs, and PEM private keys.
/// What is removed becomes `[redacted]`.
pub fn scrub(text: &str) -> String {
let mut out = Vec::new();
let mut in_pem = false;
for line in text.lines() {
if line.contains("-----BEGIN") && line.contains("PRIVATE KEY") {
in_pem = true;
out.push("[redacted]".to_string());
continue;
}
if in_pem {
if line.contains("-----END") {
in_pem = false;
}
continue;
}
out.push(scrub_line(line));
}
out.join("\n")
}
fn scrub_line(line: &str) -> String {
let mut s = scrub_url_userinfo(line);
let lower = s.to_ascii_lowercase();
// Walk every occurrence of every secret name; redact the value after the
// next `=` or `:` (quotes and spaces skipped) up to whitespace, a quote, a
// comma, `&` or `;`.
let mut cuts: Vec<(usize, usize)> = Vec::new();
for name in SECRET_NAMES {
let mut from = 0;
while let Some(pos) = lower[from..].find(name) {
let start = from + pos;
from = start + name.len();
let bytes = s.as_bytes();
let mut i = start + name.len();
// allow a closing quote and spaces between the name and the separator
while i < bytes.len() && (bytes[i] == b'"' || bytes[i] == b'\'' || bytes[i] == b' ') {
i += 1;
}
if i >= bytes.len() || (bytes[i] != b'=' && bytes[i] != b':') {
continue;
}
i += 1;
while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'"' || bytes[i] == b'\'') {
i += 1;
}
let vstart = i;
if name == "authorization" || name == "cookie" {
// "Authorization: Bearer <token>", "Cookie: a=b; c=d": the whole
// rest of the line is the secret.
i = bytes.len();
}
while i < bytes.len()
&& !matches!(bytes[i], b' ' | b'"' | b'\'' | b',' | b'&' | b';' | b'\t')
{
i += 1;
}
if i > vstart {
cuts.push((vstart, i));
}
}
}
if cuts.is_empty() {
return s;
}
cuts.sort();
let mut merged: Vec<(usize, usize)> = Vec::new();
for (a, b) in cuts {
match merged.last_mut() {
Some(last) if a <= last.1 => last.1 = last.1.max(b),
_ => merged.push((a, b)),
}
}
for (a, b) in merged.into_iter().rev() {
if s.is_char_boundary(a) && s.is_char_boundary(b) {
s.replace_range(a..b, "[redacted]");
}
}
s
}
/// `scheme://user:password@host` -> `scheme://user:[redacted]@host`.
fn scrub_url_userinfo(line: &str) -> String {
let mut s = line.to_string();
let mut from = 0;
while let Some(p) = s[from..].find("://") {
let auth_start = from + p + 3;
let rest = &s[auth_start..];
let end = rest
.find(|c: char| c == '/' || c.is_whitespace())
.unwrap_or(rest.len());
let authority = &rest[..end];
if let Some(at) = authority.rfind('@') {
if let Some(colon) = authority[..at].find(':') {
let a = auth_start + colon + 1;
let b = auth_start + at;
s.replace_range(a..b, "[redacted]");
}
}
from = auth_start;
if from >= s.len() {
break;
}
}
s
}
/// The newest activity-log lines, scrubbed and cut to the size limits.
pub fn recent_log(full_log: &str) -> String {
let lines: Vec<&str> = full_log.lines().collect();
let tail = &lines[lines.len().saturating_sub(LOG_LINES)..];
let mut text = scrub(&tail.join("\n"));
if text.len() > LOG_BYTES {
let mut cut = text.len() - LOG_BYTES;
while !text.is_char_boundary(cut) {
cut += 1;
}
text = text[cut..].to_string();
if let Some(nl) = text.find('\n') {
text = text[nl + 1..].to_string();
}
}
text
}
/// The JSON body the relay takes.
pub fn payload(kind: Kind, text: &str, ctx: &Context, log: Option<&str>) -> String {
serde_json::json!({
"kind": kind.as_str(),
"text": text,
"app_version": ctx.app_version,
"platform": ctx.platform,
"os": ctx.os,
"appearance": ctx.appearance,
"language": ctx.language,
"window": ctx.window,
"log": log.unwrap_or(""),
})
.to_string()
}
/// A filed issue: its number and web link.
#[derive(Clone, Debug, PartialEq)]
pub struct Filed {
pub number: u64,
pub url: String,
}
/// Read the relay's answer: curl's body, then the HTTP status on the last line.
pub fn parse_response(curl_stdout: &str) -> Result<Filed, String> {
let trimmed = curl_stdout.trim_end();
let (body, code) = match trimmed.rfind('\n') {
Some(i) => (&trimmed[..i], trimmed[i + 1..].trim()),
None => ("", trimmed),
};
let json: Option<serde_json::Value> = serde_json::from_str(body).ok();
if code == "201" || code == "200" {
let number = json.as_ref().and_then(|j| j["number"].as_u64());
let url = json.as_ref().and_then(|j| j["url"].as_str()).unwrap_or("");
return match number {
Some(number) => Ok(Filed {
number,
url: url.to_string(),
}),
None => Err("the report service answered without an issue number; \
check the issue list before sending again"
.into()),
};
}
let reason = json
.as_ref()
.and_then(|j| j["error"].as_str())
.map(str::to_string);
Err(match (code, reason) {
(_, Some(r)) => r,
("000", None) | ("", None) => "could not reach the report service".into(),
(c, None) => format!("the report service answered HTTP {c}"),
})
}
/// Send a report on a worker thread; the receiver gets one result.
pub fn send(body: String) -> Receiver<Result<Filed, String>> {
let url = std::env::var("ALKANE_REPORT_URL").unwrap_or_else(|_| DEFAULT_URL.to_string());
let (tx, rx) = channel();
std::thread::spawn(move || {
let result = (|| {
let mut child = alkane_core::platform::quiet_command("curl")
.args([
"-sS",
"--max-time",
"40",
"-X",
"POST",
"-H",
"Content-Type: application/json",
"--data-binary",
"@-",
"-w",
"\n%{http_code}",
&url,
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("could not run curl: {e}"))?;
if let Some(mut si) = child.stdin.take() {
let _ = si.write_all(body.as_bytes());
}
let out = child
.wait_with_output()
.map_err(|e| format!("curl failed: {e}"))?;
parse_response(&String::from_utf8_lossy(&out.stdout))
})();
let _ = tx.send(result);
});
rx
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scrub_removes_credentials_and_keeps_the_rest() {
let log = "12:00:01 set pools on 192.168.1.20: url=stratum+tcp://u:hunter2@pool:3333 password=hunter2\n\
12:00:02 login {\"user\": \"root\", \"pass\": \"s3cret\"}\n\
12:00:03 Authorization: Bearer abc.def\n\
-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----\n\
12:00:04 scan finished: 9 miners";
let s = scrub(log);
assert!(!s.contains("hunter2"), "{s}");
assert!(!s.contains("s3cret"), "{s}");
assert!(!s.contains("abc.def"), "{s}");
assert!(!s.contains("AAAA"), "{s}");
assert!(s.contains("192.168.1.20"));
assert!(s.contains("\"user\": \"root\""));
assert!(s.contains("scan finished: 9 miners"));
assert_eq!(s.matches("[redacted]").count(), 5, "{s}");
}
#[test]
fn recent_log_keeps_the_newest_lines_within_limits() {
let log: Vec<String> = (0..500)
.map(|i| format!("line {i} {}", "x".repeat(300)))
.collect();
let tail = recent_log(&log.join("\n"));
assert!(tail.len() <= LOG_BYTES);
assert!(tail.ends_with(&log[499]));
assert!(tail.starts_with("line "), "cut on a line boundary");
assert!(!tail.contains("line 400 "), "only the newest lines");
}
#[test]
fn payload_carries_kind_text_and_context() {
let ctx = Context {
app_version: "1.2.3".into(),
platform: "macos-aarch64".into(),
os: "macOS 15.1".into(),
appearance: "dark".into(),
language: "en".into(),
window: "1280x800".into(),
};
let v: serde_json::Value =
serde_json::from_str(&payload(Kind::Ui, "Text \"quoted\"", &ctx, None)).unwrap();
assert_eq!(v["kind"], "ui");
assert_eq!(v["text"], "Text \"quoted\"");
assert_eq!(v["app_version"], "1.2.3");
assert_eq!(v["log"], "");
}
#[test]
fn response_parsing() {
assert_eq!(
parse_response("{\"number\":42,\"url\":\"https://x/42\"}\n201"),
Ok(Filed {
number: 42,
url: "https://x/42".into()
})
);
assert_eq!(
parse_response("{\"error\":\"Too many reports; try again later\"}\n429"),
Err("Too many reports; try again later".into())
);
assert_eq!(
parse_response("\n000"),
Err("could not reach the report service".into())
);
assert_eq!(
parse_response("<html>\n502"),
Err("the report service answered HTTP 502".into())
);
}
}
+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)> {
+8 -1
View File
@@ -34,7 +34,7 @@ impl Lang {
Lang::Pt => "Portugu\u{ea}s",
}
}
fn code(self) -> &'static str {
pub fn code(self) -> &'static str {
match self {
Lang::En => "en",
Lang::Zh => "zh",
@@ -137,6 +137,13 @@ const TABLE: &[(&str, [&str; 6])] = &[
("Credentials", ["Credentials", "\u{51ed}\u{636e}", "\u{0423}\u{0447}\u{0451}\u{0442}\u{043d}\u{044b}\u{0435} \u{0434}\u{0430}\u{043d}\u{043d}\u{044b}\u{0435}", "Identifiants", "Credenciales", "Credenciais"]),
("Language", ["Language", "\u{8bed}\u{8a00}", "\u{042f}\u{0437}\u{044b}\u{043a}", "Langue", "Idioma", "Idioma"]),
("Logs", ["Logs", "\u{65e5}\u{5fd7}", "\u{0416}\u{0443}\u{0440}\u{043d}\u{0430}\u{043b}", "Journaux", "Registros", "Registos"]),
("Bug report", ["Bug report", "\u{95ee}\u{9898}\u{53cd}\u{9988}", "\u{421}\u{43e}\u{43e}\u{431}\u{449}\u{438}\u{442}\u{44c} \u{43e}\u{431} \u{43e}\u{448}\u{438}\u{431}\u{43a}\u{435}", "Signaler un bug", "Informar de un error", "Relatar um erro"]),
("Type", ["Type", "\u{7c7b}\u{578b}", "\u{422}\u{438}\u{43f}", "Type", "Tipo", "Tipo"]),
("Bug", ["Bug", "\u{7f3a}\u{9677}", "\u{41e}\u{448}\u{438}\u{431}\u{43a}\u{430}", "Bug", "Error", "Erro"]),
("UI change", ["UI change", "\u{754c}\u{9762}\u{4fee}\u{6539}", "\u{418}\u{437}\u{43c}\u{435}\u{43d}\u{435}\u{43d}\u{438}\u{435} \u{438}\u{43d}\u{442}\u{435}\u{440}\u{444}\u{435}\u{439}\u{441}\u{430}", "Modification de l'interface", "Cambio de interfaz", "Altera\u{e7}\u{e3}o da interface"]),
("Feature request", ["Feature request", "\u{529f}\u{80fd}\u{5efa}\u{8bae}", "\u{41f}\u{440}\u{435}\u{434}\u{43b}\u{43e}\u{436}\u{435}\u{43d}\u{438}\u{435} \u{444}\u{443}\u{43d}\u{43a}\u{446}\u{438}\u{438}", "Demande de fonctionnalit\u{e9}", "Solicitud de funci\u{f3}n", "Pedido de recurso"]),
("Send", ["Send", "\u{53d1}\u{9001}", "\u{41e}\u{442}\u{43f}\u{440}\u{430}\u{432}\u{438}\u{442}\u{44c}", "Envoyer", "Enviar", "Enviar"]),
("Open issue", ["Open issue", "\u{6253}\u{5f00}\u{95ee}\u{9898}", "\u{41e}\u{442}\u{43a}\u{440}\u{44b}\u{442}\u{44c} \u{437}\u{430}\u{434}\u{430}\u{447}\u{443}", "Ouvrir le ticket", "Abrir incidencia", "Abrir issue"]),
// KPI captions
("Total", ["Total", "\u{603b}\u{6570}", "\u{0412}\u{0441}\u{0435}\u{0433}\u{043e}", "Total", "Total", "Total"]),
("Hashing", ["Hashing", "\u{6b63}\u{5728}\u{6316}\u{77ff}", "\u{0425}\u{0435}\u{0448}\u{0438}\u{0440}\u{043e}\u{0432}\u{0430}\u{043d}\u{0438}\u{0435}", "Minage", "Minando", "Minerando"]),
+37 -3
View File
@@ -6,19 +6,24 @@
#![cfg_attr(windows, windows_subsystem = "windows")]
mod access_probe;
mod alkane_detect;
mod askpass;
mod bench_sequence;
mod bug_report;
mod credentials;
mod export;
mod fixtures;
mod i18n;
mod log_scan;
mod logs;
mod media_ops;
mod model;
mod naming;
mod pool_prefs;
mod presets;
mod restore;
mod scan;
mod stock_ops;
mod ui;
fn main() {
@@ -38,6 +43,19 @@ 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()));
}
// Full GUI-flow test (scan -> restore -> scan -> install -> scan -> verify),
// exercising the scan step a user performs. See bench_sequence::run_flow.
if let Some(spec) = std::env::var_os("ALKANE_BENCH_FLOW") {
std::process::exit(bench_sequence::run_flow(&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.
@@ -99,6 +117,17 @@ fn run_selftest() -> i32 {
let frame = wx_rs::Widget::main_frame();
let mut app = ui::build(frame);
let ok = app.run_fixture_selftest();
// ALKANE_SNAPSHOT=path (macOS): also write a PNG of the window as the app
// draws it, to check rendering without screen-recording permission.
if let Some(path) = std::env::var_os("ALKANE_SNAPSHOT") {
let path = path.to_string_lossy();
let wrote = wx_rs::snapshot_png(&frame, &path);
println!(
"SNAPSHOT {} {}",
if wrote { "wrote" } else { "unavailable" },
path
);
}
println!("SELFTEST {}", if ok { "PASS" } else { "FAIL" });
if ok {
0
@@ -109,9 +138,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
+306
View File
@@ -0,0 +1,306 @@
// SPDX-License-Identifier: MIT
//! GUI-side orchestration for the "Installation Media" feature: enumerate
//! writable removable devices safely, and drive card creation + device write on
//! a background thread, streaming progress with the same [`StockMsg`] channel
//! the install/restore flows use.
//!
//! The card *image* is built with `alkane_flash::sd_media` (root-free); only the
//! final device write touches hardware, and the UI confirms the target first.
use std::path::PathBuf;
use std::process::Command;
use std::sync::mpsc::channel;
use std::sync::Arc;
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
use alkane_flash::sd_media;
use crate::stock_ops::{StockHandle, StockMsg};
/// What kind of card to build.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum MediaKind {
/// Genuine vendor stock-recovery card (from a user-supplied vendor package).
StockRecovery,
/// Alkane that runs from the card each boot (nothing written to the board).
AlkaneSimpleBoot,
/// Alkane installer: boots, writes alkane to the board's storage, LED-signals.
AlkaneInstaller,
}
impl MediaKind {
pub fn label(self) -> &'static str {
match self {
MediaKind::StockRecovery => "Stock recovery (restore the board to genuine stock)",
MediaKind::AlkaneSimpleBoot => {
"Alkane: run from SD card (nothing written to the board)"
}
MediaKind::AlkaneInstaller => {
"Alkane: installer (writes alkane to the board, then signals done)"
}
}
}
}
/// A removable device that is a plausible SD/USB card target. Deliberately
/// conservative: only whole disks that are removable or hotplug, never a disk
/// that holds a mounted filesystem the host is using.
#[derive(Clone, Debug)]
pub struct RemovableDevice {
/// e.g. `/dev/sdc`.
pub path: String,
/// Human size, e.g. `14.6G`.
pub size: String,
/// Model string, e.g. `STORAGE DEVICE`.
pub model: String,
/// True if any partition of it is currently mounted (a caution flag the UI
/// surfaces; such a device is still selectable but clearly risky).
pub has_mounted_partition: bool,
}
impl RemovableDevice {
pub fn describe(&self) -> String {
let mut s = format!("{} ({}", self.path, self.size.trim());
if !self.model.trim().is_empty() {
s.push_str(", ");
s.push_str(self.model.trim());
}
s.push(')');
if self.has_mounted_partition {
s.push_str(" [mounted]");
}
s
}
}
/// Enumerate removable whole-disk devices via `lsblk -J`. Returns an empty list
/// if `lsblk` is unavailable or parsing fails (the UI then offers a manual
/// device entry). The root/system disk is never included (it is not removable).
pub fn list_removable_devices() -> Vec<RemovableDevice> {
let out = match Command::new("lsblk")
.args([
"-J",
"-b",
"-o",
"NAME,SIZE,RM,HOTPLUG,TYPE,MODEL,TRAN,MOUNTPOINT",
])
.output()
{
Ok(o) if o.status.success() => o.stdout,
_ => return Vec::new(),
};
let json: serde_json::Value = match serde_json::from_slice(&out) {
Ok(v) => v,
Err(_) => return Vec::new(),
};
let mut devices = Vec::new();
let blockdevices = json
.get("blockdevices")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
for dev in blockdevices {
let typ = dev.get("type").and_then(|v| v.as_str()).unwrap_or("");
if typ != "disk" {
continue;
}
let rm = dev.get("rm").and_then(|v| v.as_bool()).unwrap_or(false);
let hotplug = dev
.get("hotplug")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let tran = dev.get("tran").and_then(|v| v.as_str()).unwrap_or("");
// Removable, or a hotplug USB disk. Never an internal nvme/sata system
// disk (those are rm=false, hotplug=false).
let removable = rm || (hotplug && (tran == "usb" || tran == "mmc"));
if !removable {
continue;
}
let name = dev.get("name").and_then(|v| v.as_str()).unwrap_or("");
if name.is_empty() {
continue;
}
let size_bytes = dev.get("size").and_then(|v| v.as_u64()).unwrap_or(0);
let model = dev
.get("model")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let mounted = dev
.get("children")
.and_then(|v| v.as_array())
.map(|parts| {
parts.iter().any(|p| {
p.get("mountpoint")
.and_then(|m| m.as_str())
.map(|m| !m.is_empty())
.unwrap_or(false)
})
})
.unwrap_or(false)
|| dev
.get("mountpoint")
.and_then(|m| m.as_str())
.map(|m| !m.is_empty())
.unwrap_or(false);
devices.push(RemovableDevice {
path: format!("/dev/{name}"),
size: human_size(size_bytes),
model,
has_mounted_partition: mounted,
});
}
devices
}
fn human_size(bytes: u64) -> String {
const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"];
let mut v = bytes as f64;
let mut u = 0;
while v >= 1024.0 && u < UNITS.len() - 1 {
v /= 1024.0;
u += 1;
}
format!("{v:.1}{}", UNITS[u])
}
/// A fully-specified media-creation request.
pub struct MediaRequest {
pub kind: MediaKind,
/// The source: an `.afw` file (alkane kinds) or a vendor stock package
/// (directory or `.zip`, stock kind).
pub source: PathBuf,
/// Target device, e.g. `/dev/sdc`. When `None`, only the image is built
/// (to `image_out`) and not written.
pub device: Option<PathBuf>,
/// Where the intermediate card image is written.
pub image_out: PathBuf,
/// Allow an unsigned `.afw` (bench).
pub allow_unsigned: bool,
}
/// Build the requested card image (and write it to the device if one is set) on
/// a background thread, streaming [`StockMsg`] exactly like `start_install`.
pub fn start_make_media(req: MediaRequest) -> StockHandle {
let (tx, rx) = channel();
let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false));
let cancel_worker = cancel.clone();
let err_tx = tx.clone();
let spawned = std::thread::Builder::new()
.name("alkane-make-media".into())
.spawn(move || {
let _ = tx.send(StockMsg::Started);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as u32)
.unwrap_or(0);
let build = || -> Result<(), String> {
match req.kind {
MediaKind::StockRecovery => {
let _ = tx.send(StockMsg::Progress("preparing vendor package...".into()));
let dir = unpack_if_zip(&req.source).map_err(|e| e.to_string())?;
let _ = tx.send(StockMsg::Progress(
"assembling stock-recovery card...".into(),
));
sd_media::build_stock_recovery_card(&dir, &req.image_out)
.map_err(|e| e.to_string())?;
}
MediaKind::AlkaneSimpleBoot | MediaKind::AlkaneInstaller => {
let _ = tx.send(StockMsg::Progress("verifying .afw...".into()));
let verified = verify_afw(
&req.source,
&VerifyOptions {
allow_unsigned: req.allow_unsigned,
expect_board: Some("zynq-7010".into()),
},
)
.map_err(|e| format!(".afw: {e}"))?;
if req.kind == MediaKind::AlkaneSimpleBoot {
let _ = tx
.send(StockMsg::Progress("assembling simple-boot card...".into()));
sd_media::build_zynq_simpleboot_card(&verified, &req.image_out, now)
.map_err(|e| e.to_string())?;
} else {
let _ = tx.send(StockMsg::Progress(
"assembling installer card (injecting install hook)...".into(),
));
sd_media::build_zynq_installer_card(&verified, &req.image_out, now)
.map_err(|e| e.to_string())?;
}
}
}
if let Some(dev) = &req.device {
if cancel_worker.load(std::sync::atomic::Ordering::Relaxed) {
return Err("cancelled before device write".into());
}
let _ = tx.send(StockMsg::Progress(format!(
"writing card to {} (do not remove)...",
dev.display()
)));
sd_media::write_image_to_device(&req.image_out, dev)
.map_err(|e| e.to_string())?;
}
Ok(())
};
let (ok, detail) = match build() {
Ok(()) => {
let where_ = req
.device
.as_ref()
.map(|d| format!("written to {}", d.display()))
.unwrap_or_else(|| format!("image at {}", req.image_out.display()));
(true, format!("card ready ({where_})"))
}
Err(e) => (false, format!("media build failed: {e}")),
};
let ip = req
.device
.as_ref()
.map(|d| d.display().to_string())
.unwrap_or_else(|| "card".into());
let _ = tx.send(StockMsg::Result { ip, ok, detail });
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 media worker thread".into(),
});
let _ = err_tx.send(StockMsg::Done);
}
StockHandle::new(rx, cancel)
}
/// If `src` is a `.zip`, unpack it to an ephemeral directory and return that;
/// a directory is returned as-is.
fn unpack_if_zip(src: &std::path::Path) -> std::io::Result<PathBuf> {
if src.is_dir() {
return Ok(src.to_path_buf());
}
if src
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
{
let staged = std::env::temp_dir().join(format!("alkane-media-pkg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&staged);
std::fs::create_dir_all(&staged)?;
let status = Command::new("unzip")
.args(["-o", "-q"])
.arg(src)
.arg("-d")
.arg(&staged)
.status()?;
if !status.success() {
return Err(std::io::Error::other("unzip failed"));
}
return Ok(staged);
}
Err(std::io::Error::other(
"stock package must be a directory or a .zip",
))
}
+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/
+129 -19
View File
@@ -531,7 +531,20 @@ 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. Failing that,
// a stock Antminer whose miner API is down is still
// found by its :80 vendor web UI.
None => {
let row = match crate::alkane_detect::detect(ip).await {
Some(r) => Some(r),
None => {
crate::alkane_detect::detect_stock_antminer(ip).await
}
};
(ip, row)
}
}
}
})
@@ -671,6 +684,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 +1255,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 +1287,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 +1977,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 +2687,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),
);
}
}
}
+562
View File
@@ -0,0 +1,562 @@
//! 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::io::Read as _;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::time::{Duration, Instant};
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
use alkane_artifacts::fetch::{self, ReleaseSource};
use alkane_flash::stock::{self, RestoreImages};
/// Read the SSH identification banner (no auth) from `host:22`, 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 s = TcpStream::connect_timeout(&addr, Duration::from_secs(4)).ok()?;
s.set_read_timeout(Some(Duration::from_secs(4))).ok()?;
let mut buf = [0u8; 128];
let n = s.read(&mut buf).ok()?;
if n == 0 {
return None;
}
Some(
String::from_utf8_lossy(&buf[..n])
.lines()
.next()
.unwrap_or("")
.trim()
.to_string(),
)
}
/// Whether a just-installed board's SSH banner looks like alkane. We installed
/// alkane to this specific board, so any SSH banner that is NOT the stock
/// Antminer dropbear (2018/2019) means our image booted. Alkane images ship a
/// current dropbear regardless of whether the image also serves the HTTP API, so
/// this verify works even for minimal images that do not serve `:80` (the
/// HTTP-only scan probe cannot see those).
fn banner_is_alkane(banner: &str) -> bool {
let b = banner.to_ascii_lowercase();
if b.contains("dropbear_2018") || b.contains("dropbear_2019") {
return false;
}
b.contains("dropbear") || b.contains("openssh")
}
/// Poll a just-installed board until it comes up as alkane over SSH (not the
/// stock dropbear) or the deadline passes. Streams a progress line on success.
fn verify_alkane_live(ip: &str, tx: &Sender<StockMsg>, cancel: &AtomicBool) -> bool {
let deadline = Instant::now() + Duration::from_secs(150);
loop {
if cancel.load(Ordering::Relaxed) {
return false;
}
if let Some(b) = ssh_banner(ip) {
if banner_is_alkane(&b) {
let _ = tx.send(StockMsg::Progress(format!(
"{ip}: alkane is live (ssh \"{b}\")"
)));
return true;
}
}
if Instant::now() >= deadline {
return false;
}
std::thread::sleep(Duration::from_secs(5));
}
}
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 {
/// Construct a handle around a worker's receiver and cancel flag. Used by
/// other op modules (e.g. `media_ops`) that reuse this streaming channel.
pub fn new(rx: Receiver<StockMsg>, cancel: Arc<AtomicBool>) -> StockHandle {
StockHandle { rx, cancel }
}
#[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()));
// Token attaches only for the trusted gitea host (see
// for_asset_url); never sent to a GitHub/other fork host.
match fetch::fetch_afw_url(
&ReleaseSource::for_asset_url(&url),
&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(()) => {
// The write succeeded; now confirm the board rebooted
// into alkane. Use the SSH banner (works even for
// images that do not serve the HTTP API) rather than
// only the HTTP scan probe.
let _ = tx.send(StockMsg::Progress(format!(
"{ip}: installed; awaiting reboot into alkane (up to 150s)..."
)));
if verify_alkane_live(&ip, &tx, &tc) {
(true, "installed; alkane is live (SSH-verified)".to_string())
} else {
(
true,
"installed; alkane not confirmed over SSH within the window -- \
check the board (a minimal image without the HTTP API still \
installs and boots; it just will not show in the scan)"
.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
+176
View File
@@ -0,0 +1,176 @@
# Installing and removing alkane-os
> For building bootable **SD installation media** (stock-recovery cards and
> alkane boot/installer cards) for card-bootable boards, see
> [installation-media.md](installation-media.md). That is a separate, physical
> path alongside the network-only install described here.
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
```
alkane-cli afw compat
```
Lists the control boards alkane-os can be installed on. For now that is the
Antminer S17 (`zynq-7010`). The install/restore commands refuse any board whose
`.afw` is not one of these.
## Install
From a local bundle:
```
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --confirm FLASH
```
From the latest release (pulled from Gitea, not GitHub, which is retired):
```
alkane-cli afw install --latest --board zynq-7010 --host <miner-ip> --confirm FLASH
# or fetch only:
alkane-cli afw fetch-latest --board zynq-7010 --output ./downloads
```
A private release repo needs a token, read from `ALKANE_RELEASE_TOKEN` (else
`GITEA_TOKEN`) at run time and passed to curl through a 0600 config file - never
on the command line, never stored by the toolkit.
### A board still on stock
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 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, 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, 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> \
--stock-firmware <genuine-Bitmain-firmware> \
--password-file <alkane-root-pw> --confirm FLASH
```
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.
+70
View File
@@ -0,0 +1,70 @@
# Installation Media (bootable SD cards)
The toolkit can build a **bootable SD/removable-media card** for control boards
that boot from a card. This is a separate, sanctioned path alongside the
network-only `.afw` install: the ordinary alkane install still runs over the
network from whatever OS the board has, and SD media exists for
- recovering a board to genuine stock, and
- bootstrapping or installing alkane onto a board through a card.
It is a **physical** path (insert a card, boot, remove), by design -- unlike the
network install, which needs no physical access.
## Which boards
SD media is offered only for boards whose bootrom / stock bootloader boots from a
card. Today that is the **Antminer S17 / Zynq-7010** control board, where the
stock U-Boot card-detects a plain FAT32 card and side-loads the card's boot trio
(confirmed on hardware: no boot-mode strap and no `uEnv.txt` needed, with the
stock bootloader intact). The Amlogic **A113D is excluded** -- it is eMMC-only
with no SD slot (USB recovery disabled), so it stays network-only.
## What you can build
| Kind | What it does |
|------|--------------|
| **Stock recovery** | Replicates a genuine Bitmain vendor SD-recovery package onto a card: boot it to write genuine stock back into NAND. You supply the vendor package. |
| **Alkane: run from SD** | Boots alkane from the card each power-on; nothing is written to the board. Good for a non-destructive try-out. |
| **Alkane: installer** | Boots an installer OS from the card that writes alkane into the board's own storage, verifies, and signals the red/green LEDs when done -- then you power off, remove the card, and boot internal alkane. |
The card is always built as an **image file first** (root-free), then written to
the device. The image is identical to what lands on the card, so it can be
inspected or kept.
## GUI
Scan the fleet, right-click a card-bootable board, and choose **Installation
Media (SD card)...**. Pick the kind, Browse to the source (an `.afw` for alkane,
or a genuine vendor package `.zip` for stock recovery), choose the target SD card
(or "build an image file only"), and click **Create**. Writing to a card erases
it entirely -- confirm the target device first.
## CLI
```
# Stock recovery card from a genuine vendor package:
alkane-cli afw make-media --kind stock \
--stock-package SD_S17.zip --out card.img \
[--write /dev/sdX --confirm WRITE]
# Alkane card from an .afw (simpleboot = run from SD, installer = flash to board):
alkane-cli afw make-media --kind alkane --mode installer \
--afw alkane-os-<ver>-zynq-7010.afw --allow-unsigned --out card.img \
[--write /dev/sdX --confirm WRITE]
```
Omit `--write` to build only the image file. Writing to a real device requires
`--confirm WRITE`. `--board` defaults to `zynq-7010` (the only supported board
for now).
## Safety notes
- **Writing a card erases the whole device.** The GUI device list shows only
removable disks and never a system disk, but always confirm the target.
- Stock recovery relies on the board's **existing stock bootloader** being
intact (it recovers broken userspace/kernel). If the bootloader itself were
wiped, a full card-boot path is needed instead -- a separate case.
- The alkane installer preserves the board's boot-critical regions (on Zynq,
`BOOT.bin` at `0x0..0x1a00000` is never written), mirroring the network
installer's guarantees.
+18
View File
@@ -26,3 +26,21 @@ report them. Try **Check access** and the Credentials dialog.
**The window is too small or too large.** It opens at most as large as your
screen's work area. Use the zoom slider in the status bar to scale the table.
## Reporting a problem
**Bug report** in the toolbar, between Export and Settings, files a bug or a
feature request with the developers. Choose the type (Bug, UI change or
Feature request) and describe it; the first line becomes the title. **Send**
shows the issue number when it is filed, and **Open issue** opens it in the
browser. If it was not sent, the reason is shown and the text stays in the
box.
A report includes the app version, the operating system, the light or dark
appearance, the language and the window size. **Include the recent activity
log** adds the newest lines of the Settings > Logs page, with passwords,
tokens and similar values removed first; untick it to leave the log out.
Reports become public issues on
[gitea.bluefla.re](https://gitea.bluefla.re/blueflare/alkane-toolkit/issues),
so do not put passwords or customer details in the text. A computer can send
five reports an hour.
+1 -1
View File
@@ -17,7 +17,7 @@ PREFIX="${WX_MACOS_PREFIX:-$HOME/.cache/wx-3.3.3-macos}"
export WX_RS_WXCONFIG="$PREFIX/bin/wx-config"
export MACOSX_DEPLOYMENT_TARGET="${MACOSX_MIN:-11.0}"
for target in aarch64-apple-darwin x86_64-apple-darwin; do
cargo build --release --offline --locked -p alkane-gui --target "$target" "$@"
cargo build --release --offline -p alkane-gui --target "$target" "$@"
done
out=target/universal-apple-darwin/release
mkdir -p "$out"
+162
View File
@@ -0,0 +1,162 @@
Subject: [PATCH 0010] macOS: native alternating rows, theme text colour, self-test snapshot
--- a/build.rs
+++ b/build.rs
@@ -278,6 +278,12 @@
build.cpp(true)
.file("cpp_src/wxbridge.cpp")
.file("cpp_src/widgets_bridge.cpp");
+ if is_osx() {
+ // Cocoa calls wx does not wrap (native alternating rows, self-test
+ // snapshot); clang compiles .mm as Objective-C++.
+ println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
+ build.file("cpp_src/osx_native.mm");
+ }
let mut flags = cxxflags.split_whitespace();
while let Some(f) = flags.next() {
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -597,7 +597,11 @@
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
} else {
+#ifdef __WXOSX__
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
+#else
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
+#endif
}
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
continue;
@@ -688,6 +692,11 @@
(unsigned char)(c.blue * 255.0 + 0.5));
}
}
+#elif defined(__WXOSX__)
+ // The DC arrives with the control's foreground colour, which is not the
+ // theme-aware label colour native cells use; take the list text colour so
+ // uncoloured segments follow light/dark like the native columns.
+ return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
#endif
return wxColour();
}
@@ -1463,8 +1472,21 @@
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
+#ifdef __WXOSX__
+extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
+#endif
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
+#ifdef __WXOSX__
+ // wxOSX draws custom cells without clipping them to the cell, so the
+ // renderer's over-sized background fill (which GTK/MSW clip) painted over
+ // neighbouring cells and hid their text until a row was selected. Use the
+ // table's native alternating rows instead: AppKit paints them under every
+ // cell, in the theme's colours, and no row carries a background attribute.
+ dvlc_store(win)->zebra = wxColour();
+ wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
+#else
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
+#endif
}
// The model-row index of the first (top) visible row, or -1 if none. Used to
--- a/cpp_src/osx_native.mm
+++ b/cpp_src/osx_native.mm
@@ -0,0 +1,60 @@
+// osx_native.mm -- alkane-toolkit extension: the few wxOSX/Cocoa calls the
+// bridge needs that wx does not wrap. Compiled on macOS only (see build.rs).
+
+#include <wx/wx.h>
+#include <wx/dataview.h>
+
+#import <Cocoa/Cocoa.h>
+
+// The NSTableView (NSOutlineView) behind a wxDataViewCtrl. wx's handle is the
+// enclosing NSScrollView.
+static NSTableView* TableOf(wxWindow* win) {
+ if (!win) return nil;
+ id h = (id)win->GetHandle();
+ if ([h isKindOfClass:[NSTableView class]]) return (NSTableView*)h;
+ if ([h isKindOfClass:[NSScrollView class]]) {
+ id doc = [(NSScrollView*)h documentView];
+ if ([doc isKindOfClass:[NSTableView class]]) return (NSTableView*)doc;
+ }
+ return nil;
+}
+
+extern "C" {
+
+// Native alternating-row backgrounds. AppKit paints them under every cell,
+// custom-drawn ones included, in the theme's own colours (light and dark), so
+// custom renderers never paint row backgrounds on macOS.
+void wxbr_osx_set_alternating_rows(void* win, int on) {
+ NSTableView* tv = TableOf((wxWindow*)win);
+ if (tv) [tv setUsesAlternatingRowBackgroundColors:(on ? YES : NO)];
+}
+
+// Write a PNG of a top-level window's content, rendered by the app itself
+// (no screen-recording permission needed). Used by the self-test with
+// ALKANE_SNAPSHOT=path to check what the table really draws. Returns 1 on
+// success.
+int wxbr_osx_snapshot(void* win, const char* path) {
+ wxWindow* w = (wxWindow*)win;
+ if (!w || !path) return 0;
+ wxTopLevelWindow* tlw = wxDynamicCast(wxGetTopLevelParent(w), wxTopLevelWindow);
+ if (!tlw) return 0;
+ tlw->Show();
+ tlw->Raise();
+ // Let the window lay out and paint before capturing it.
+ for (int i = 0; i < 30; ++i) {
+ wxYield();
+ wxMilliSleep(30);
+ }
+ NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
+ NSView* view = [nsw contentView];
+ if (!view) return 0;
+ NSRect rect = [view bounds];
+ NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
+ if (!rep) return 0;
+ [view cacheDisplayInRect:rect toBitmapImageRep:rep];
+ NSData* png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
+ if (!png) return 0;
+ return [png writeToFile:[NSString stringWithUTF8String:path] atomically:YES] ? 1 : 0;
+}
+
+}
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -107,6 +107,8 @@
pub fn wxbr_launch_browser(url: *const c_char) -> c_int;
pub fn wxbr_set_appearance_system();
pub fn wxbr_is_dark() -> c_int;
+ #[cfg(target_os = "macos")]
+ pub fn wxbr_osx_snapshot(win: *mut c_void, path: *const c_char) -> c_int;
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
@@ -271,6 +273,22 @@
unsafe { notsafe::wxbr_is_dark() != 0 }
}
+/// Write a PNG of `win`'s top-level window as the app itself renders it (shows
+/// the window and lets it paint first). macOS only, for the self-test's
+/// `ALKANE_SNAPSHOT`; returns false elsewhere or on failure.
+pub fn snapshot_png(win: &Widget, path: &str) -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ let Ok(p) = CString::new(path) else { return false };
+ unsafe { notsafe::wxbr_osx_snapshot(win.0, p.as_ptr()) != 0 }
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = (win, path);
+ false
+ }
+}
+
/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight,
/// 3=button face, 4=grey text. Returns (r, g, b).
pub fn system_color(which: i32) -> (u8, u8, u8) {
+56
View File
@@ -0,0 +1,56 @@
Subject: [PATCH 0010] svg_button: clickable SVG icon button for the toolbar
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -2140,6 +2140,18 @@
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
+// Like wxbr_svg_icon, but a clickable button: render the (already-recoloured)
+// SVG into a w x h DIP bitmap bundle and wrap it in a wxBitmapButton that emits
+// WxEV_BUTTON_CLICKED with `id`. Used for the toolbar's icon buttons.
+void* wxbr_svg_button(void* parent, const char* svg, int id, int w, int h) {
+ wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
+ wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bundle);
+ btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
+ if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
+ });
+ return (void*)btn;
+}
+
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -121,6 +121,13 @@
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
+ pub fn wxbr_svg_button(
+ parent: *mut c_void,
+ svg: *const c_char,
+ id: c_int,
+ w: c_int,
+ h: c_int,
+ ) -> *mut c_void;
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
pub fn wxbr_set_light_pulse(on: c_int);
pub fn wxbr_bind_sys_colour(win: *mut c_void);
@@ -949,6 +956,16 @@
Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) })
}
+ /// A clickable icon button: render the (already-recoloured) SVG into a
+ /// `w`x`h` DIP bitmap button that emits a button click with `id`. Recolour
+ /// the SVG first (explicit fill, not `currentColor`).
+ pub fn svg_button(parent: Widget, svg: &str, id: i32, w: i32, h: i32) -> Widget {
+ let c = CString::new(svg).unwrap_or_default();
+ Widget(unsafe {
+ notsafe::wxbr_svg_button(parent.0, c.as_ptr(), id as c_int, w as c_int, h as c_int)
+ })
+ }
+
/// Listen for OS light/dark theme changes on this window (emits `SysColour`).
pub fn bind_sys_colour(&self) {
unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
@@ -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) })
}
+2
View File
@@ -28,6 +28,8 @@ later changes go in new patches.
| 0007 | `wxbridge.cpp` on wxMSW: no input-swallowing overlay, appearance before the first window, work-area sizing, executable icon, UTF-8 menu fix |
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
| 0009 | macOS: wxOSX (universal static) through `wx-config`, logical sizes on Apple, clang compiler runtime for `@available` |
| 0010 | macOS table: native alternating rows instead of the unclipped custom-cell background fill (it hid neighbouring cells' text), theme-aware text colour, `osx_native.mm`, self-test window snapshot |
| 0011 | macOS self-test snapshot captures the window's frame view, so areas the app does not paint show the real window background instead of transparency |
History: the round 19 health-tooltip fix (GTK tip area converted from
bin-window to widget coordinates) used to be a separate patch on top of an
+25
View File
@@ -278,6 +278,12 @@ fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
build.cpp(true)
.file("cpp_src/wxbridge.cpp")
.file("cpp_src/widgets_bridge.cpp");
if is_osx() {
// Cocoa calls wx does not wrap (native alternating rows, self-test
// snapshot); clang compiles .mm as Objective-C++.
println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
build.file("cpp_src/osx_native.mm");
}
let mut flags = cxxflags.split_whitespace();
while let Some(f) = flags.next() {
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
@@ -303,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
@@ -0,0 +1,64 @@
// osx_native.mm -- alkane-toolkit extension: the few wxOSX/Cocoa calls the
// bridge needs that wx does not wrap. Compiled on macOS only (see build.rs).
#include <wx/wx.h>
#include <wx/dataview.h>
#import <Cocoa/Cocoa.h>
// The NSTableView (NSOutlineView) behind a wxDataViewCtrl. wx's handle is the
// enclosing NSScrollView.
static NSTableView* TableOf(wxWindow* win) {
if (!win) return nil;
id h = (id)win->GetHandle();
if ([h isKindOfClass:[NSTableView class]]) return (NSTableView*)h;
if ([h isKindOfClass:[NSScrollView class]]) {
id doc = [(NSScrollView*)h documentView];
if ([doc isKindOfClass:[NSTableView class]]) return (NSTableView*)doc;
}
return nil;
}
extern "C" {
// Native alternating-row backgrounds. AppKit paints them under every cell,
// custom-drawn ones included, in the theme's own colours (light and dark), so
// custom renderers never paint row backgrounds on macOS.
void wxbr_osx_set_alternating_rows(void* win, int on) {
NSTableView* tv = TableOf((wxWindow*)win);
if (tv) [tv setUsesAlternatingRowBackgroundColors:(on ? YES : NO)];
}
// Write a PNG of a top-level window's content, rendered by the app itself
// (no screen-recording permission needed). Used by the self-test with
// ALKANE_SNAPSHOT=path to check what the table really draws. Returns 1 on
// success.
int wxbr_osx_snapshot(void* win, const char* path) {
wxWindow* w = (wxWindow*)win;
if (!w || !path) return 0;
wxTopLevelWindow* tlw = wxDynamicCast(wxGetTopLevelParent(w), wxTopLevelWindow);
if (!tlw) return 0;
tlw->Show();
tlw->Raise();
// Let the window lay out and paint before capturing it.
for (int i = 0; i < 30; ++i) {
wxYield();
wxMilliSleep(30);
}
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
// The content view's superview (the window's frame view) also draws the
// window background and title bar. The content view alone leaves every
// area the app's panels do not paint transparent, which read as white.
NSView* view = [[nsw contentView] superview];
if (!view) view = [nsw contentView];
if (!view) return 0;
NSRect rect = [view bounds];
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
if (!rep) return 0;
[view cacheDisplayInRect:rect toBitmapImageRep:rep];
NSData* png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
if (!png) return 0;
return [png writeToFile:[NSString stringWithUTF8String:path] atomically:YES] ? 1 : 0;
}
}
@@ -597,7 +597,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
} else {
#ifdef __WXOSX__
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
#else
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
#endif
}
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
continue;
@@ -688,6 +692,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
(unsigned char)(c.blue * 255.0 + 0.5));
}
}
#elif defined(__WXOSX__)
// The DC arrives with the control's foreground colour, which is not the
// theme-aware label colour native cells use; take the list text colour so
// uncoloured segments follow light/dark like the native columns.
return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
#endif
return wxColour();
}
@@ -881,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) {
@@ -927,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) {
@@ -1463,8 +1486,21 @@ void wxbr_dvlc_set_row_color(void* win, unsigned row, int r, int g, int b) {
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
#ifdef __WXOSX__
extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
#endif
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
#ifdef __WXOSX__
// wxOSX draws custom cells without clipping them to the cell, so the
// renderer's over-sized background fill (which GTK/MSW clip) painted over
// neighbouring cells and hid their text until a row was selected. Use the
// table's native alternating rows instead: AppKit paints them under every
// cell, in the theme's colours, and no row carries a background attribute.
dvlc_store(win)->zebra = wxColour();
wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
#else
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
#endif
}
// The model-row index of the first (top) visible row, or -1 if none. Used to
@@ -2104,6 +2140,18 @@ void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
// Like wxbr_svg_icon, but a clickable button: render the (already-recoloured)
// SVG into a w x h DIP bitmap bundle and wrap it in a wxBitmapButton that emits
// WxEV_BUTTON_CLICKED with `id`. Used for the toolbar's icon buttons.
void* wxbr_svg_button(void* parent, const char* svg, int id, int w, int h) {
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bundle);
btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
});
return (void*)btn;
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
@@ -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__
+48
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);
@@ -107,6 +109,8 @@ mod notsafe {
pub fn wxbr_launch_browser(url: *const c_char) -> c_int;
pub fn wxbr_set_appearance_system();
pub fn wxbr_is_dark() -> c_int;
#[cfg(target_os = "macos")]
pub fn wxbr_osx_snapshot(win: *mut c_void, path: *const c_char) -> c_int;
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
@@ -117,6 +121,13 @@ mod notsafe {
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
pub fn wxbr_svg_button(
parent: *mut c_void,
svg: *const c_char,
id: c_int,
w: c_int,
h: c_int,
) -> *mut c_void;
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
pub fn wxbr_set_light_pulse(on: c_int);
pub fn wxbr_bind_sys_colour(win: *mut c_void);
@@ -271,6 +282,22 @@ pub fn is_dark() -> bool {
unsafe { notsafe::wxbr_is_dark() != 0 }
}
/// Write a PNG of `win`'s top-level window as the app itself renders it (shows
/// the window and lets it paint first). macOS only, for the self-test's
/// `ALKANE_SNAPSHOT`; returns false elsewhere or on failure.
pub fn snapshot_png(win: &Widget, path: &str) -> bool {
#[cfg(target_os = "macos")]
{
let Ok(p) = CString::new(path) else { return false };
unsafe { notsafe::wxbr_osx_snapshot(win.0, p.as_ptr()) != 0 }
}
#[cfg(not(target_os = "macos"))]
{
let _ = (win, path);
false
}
}
/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight,
/// 3=button face, 4=grey text. Returns (r, g, b).
pub fn system_color(which: i32) -> (u8, u8, u8) {
@@ -445,6 +472,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) })
@@ -483,6 +516,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) })
}
@@ -918,6 +956,16 @@ impl Widget {
Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) })
}
/// A clickable icon button: render the (already-recoloured) SVG into a
/// `w`x`h` DIP bitmap button that emits a button click with `id`. Recolour
/// the SVG first (explicit fill, not `currentColor`).
pub fn svg_button(parent: Widget, svg: &str, id: i32, w: i32, h: i32) -> Widget {
let c = CString::new(svg).unwrap_or_default();
Widget(unsafe {
notsafe::wxbr_svg_button(parent.0, c.as_ptr(), id as c_int, w as c_int, h as c_int)
})
}
/// Listen for OS light/dark theme changes on this window (emits `SysColour`).
pub fn bind_sys_colour(&self) {
unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
+7
View File
@@ -0,0 +1,7 @@
# Report relay for the Alkane Toolkit's Bug report button (see README.md).
FROM python:3.13-alpine
RUN adduser -D -H -u 10001 relay
COPY relay.py /app/relay.py
USER relay
EXPOSE 8080
ENTRYPOINT ["python3", "-u", "/app/relay.py"]
+65
View File
@@ -0,0 +1,65 @@
# Report relay
Files the app's bug reports and feature requests as issues in
`blueflare/alkane-toolkit`. The app's **Bug report** button posts the report
here; the relay holds the only token, so the public app download carries no
secret.
```
app --HTTPS--> gitea.bluefla.re/alkane-report/ (nginx) --> relay --> Gitea API
```
## What it does
- `POST /v1/report` takes the JSON the app sends (`kind`, `text`, version and
OS context, optional `log`) and answers `201 {"number", "url"}` or an error
`{"error": "..."}` the app shows as is. `GET /healthz` answers `200`.
- Checks: type is `bug`, `ui` or `feature`; text 1 to 8,000 characters;
each context value at most 120 printable characters; log at most 16 KiB;
body at most 64 KiB (nginx enforces the same).
- Rate limits, in memory: 5 reports per client IP per hour and 60 in all.
Over the limit: `429` with `Retry-After`. At most 4 reports in flight.
The client IP is `X-Real-IP` from nginx. Office LAN clients reach nginx
through the router's hairpin NAT, so they share one IP and one limit.
- Scrubs the log a second time (the app scrubs first): password, token,
secret and similar values, `Authorization`/`Cookie` values, URL passwords
and PEM private keys become `[redacted]`.
- `@name` in a report cannot notify anyone (a zero-width space follows `@`).
- The issue title is the text's first line (up to 100 characters). The body
has the type, a context table, the text, and the log in a collapsed block.
Labels: the type (`bug`, `ui`, `feature`) and `from-app`.
- Nothing is stored. Each report leaves one log line: the client IP and the
outcome (`filed #N`, `refused <status>`, `rate limited`, `tracker error`),
never the report's text.
## Gitea account
Issues are filed as `alkane-reporter`, a local non-admin user with a random
password that is never used. Its only access is the org team
`alkane-reporters` (units `repo.code: read`, `repo.issues: write`) on
`alkane-toolkit`. Its token `alkane-toolkit-bug-reports` has the scopes
`write:issue` and `read:repository`. This mirrors FLARE's `flare-reporter`.
## Deployment
On the Gitea host, recorded in the `flare-deployment` repository
(`runbooks/alkane-report-relay.md`):
```sh
# in /opt/flare/deploy/alkane-report-relay, holding relay.py, Dockerfile, compose.yml
PROXY_NETWORK=flare_default docker compose -p alkane-report-relay up -d --build
```
The token file is `secrets/gitea_token` next to the compose file (directory
`0700`, never committed). nginx routes `location /alkane-report/` in the
`gitea.bluefla.re` server block to `alkane-report-relay:8080`.
## Tests
```sh
python3 tools/report-relay/test_relay.py
```
They run the real HTTP handler against a fake Gitea: filing, scrubbing,
mention handling, validation, size and rate limits, and tracker errors. CI
runs them in the `verify` workflow's unit tests.
+26
View File
@@ -0,0 +1,26 @@
# Deployed on the Gitea host next to the shared nginx (see README.md).
# The token file is created on the host and never committed.
services:
report-relay:
build: .
image: alkane-report-relay:local
container_name: alkane-report-relay
restart: unless-stopped
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
mem_limit: 128m
pids_limit: 64
environment:
GITEA_URL: http://gitea:3000
GITEA_REPO: blueflare/alkane-toolkit
GITEA_TOKEN_FILE: /run/secrets/gitea_token
RATE_PER_IP: "100"
RATE_GLOBAL: "300"
volumes:
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
networks: [proxy]
networks:
proxy:
external: true
name: ${PROXY_NETWORK:?set PROXY_NETWORK to the shared nginx network}
+321
View File
@@ -0,0 +1,321 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Report relay: files Alkane Toolkit bug reports as Gitea issues.
The app's Bug report button posts JSON here; the relay checks it, scrubs the
log again, rate-limits, and files one issue in one repository with its own
token. The app holds no secret. Nothing about a report is stored.
POST /v1/report {"kind": "bug"|"ui"|"feature", "text": "...",
"app_version", "platform", "os", "appearance",
"language", "window": "...", "log": "..."}
-> 201 {"number": N, "url": "..."}
-> 4xx/5xx {"error": "reason the app shows"}
GET /healthz -> 200 ok
Configuration (environment):
GITEA_URL API base, e.g. http://gitea:3000 (default https://gitea.bluefla.re)
GITEA_REPO owner/name the issues go to (default blueflare/alkane-toolkit)
GITEA_TOKEN_FILE file holding the token (scopes write:issue, read:repository)
LISTEN host:port (default 0.0.0.0:8080)
RATE_PER_IP reports per client IP per hour (default 5)
RATE_GLOBAL reports per hour in all (default 60)
The client IP is the X-Real-IP header the reverse proxy sets; the relay must
only be reachable through that proxy.
"""
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
import re
import sys
import threading
import time
import urllib.error
import urllib.request
KINDS = {"bug": "Bug", "ui": "UI change", "feature": "Feature request"}
CONTEXT_FIELDS = (
("app_version", "App version"),
("platform", "Platform"),
("os", "OS"),
("appearance", "Appearance"),
("language", "Language"),
("window", "Window"),
)
FROM_APP_LABEL = "from-app"
MAX_BODY = 64 * 1024
MAX_TEXT_CHARS = 8000
MAX_CONTEXT_CHARS = 120
MAX_LOG_BYTES = 16 * 1024
MAX_TITLE_CHARS = 100
MAX_IN_FLIGHT = 4
HOUR = 3600.0
SECRET_NAME = re.compile(
r"(password|passwd|pass|pwd|secret|token|apikey|api_key|psk|credential)"
r"(['\"]?\s*[:=]\s*['\"]?)([^\s'\",&;]+)",
re.IGNORECASE,
)
HEADER_SECRET = re.compile(r"((?:authorization|cookie)\s*:\s*).+", re.IGNORECASE)
URL_USERINFO = re.compile(r"(://[^/\s:@]+:)[^/\s@]+(@)")
PEM_BLOCK = re.compile(
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(-----END [A-Z ]*PRIVATE KEY-----|\Z)",
re.DOTALL,
)
def scrub(text: str) -> str:
"""Remove credentials (the app scrubs too; this is the second pass)."""
text = PEM_BLOCK.sub("[redacted]", text)
text = HEADER_SECRET.sub(r"\1[redacted]", text)
text = URL_USERINFO.sub(r"\1[redacted]\2", text)
return SECRET_NAME.sub(r"\1\2[redacted]", text)
def no_mentions(text: str) -> str:
"""Stop @name in a report from notifying Gitea users."""
return re.sub(r"@(?=[A-Za-z0-9_])", "@\u200b", text)
def fence_for(text: str) -> str:
"""A backtick fence longer than any backtick run in `text`."""
longest = max((len(m) for m in re.findall(r"`+", text)), default=0)
return "`" * max(3, longest + 1)
def cell(value: str) -> str:
return value.replace("|", "\\|").replace("\n", " ")
class BadReport(Exception):
def __init__(self, status: int, message: str):
super().__init__(message)
self.status = status
self.message = message
def validate(raw: bytes) -> dict:
try:
data = json.loads(raw)
except (ValueError, UnicodeDecodeError):
raise BadReport(400, "The report was not valid JSON")
if not isinstance(data, dict):
raise BadReport(400, "The report was not a JSON object")
kind = data.get("kind", "bug")
if kind not in KINDS:
raise BadReport(422, "Unknown report type")
text = data.get("text")
if not isinstance(text, str) or not text.strip():
raise BadReport(422, "The report is empty")
text = text.strip()
if len(text) > MAX_TEXT_CHARS:
raise BadReport(413, f"The text is longer than {MAX_TEXT_CHARS} characters")
context = {}
for key, _ in CONTEXT_FIELDS:
value = data.get(key, "")
if not isinstance(value, str) or len(value) > MAX_CONTEXT_CHARS:
raise BadReport(422, f"Bad value for {key}")
context[key] = "".join(c for c in value if c.isprintable())
log = data.get("log", "")
if not isinstance(log, str) or len(log.encode()) > MAX_LOG_BYTES:
raise BadReport(413, "The log is too large")
return {"kind": kind, "text": text, "context": context, "log": log}
def issue_title(report: dict) -> str:
first = next(line.strip() for line in report["text"].splitlines() if line.strip())
if len(first) > MAX_TITLE_CHARS:
first = first[: MAX_TITLE_CHARS - 3].rstrip() + "..."
return no_mentions(first)
def issue_body(report: dict) -> str:
ctx = report["context"]
lines = [
f"**Type:** {KINDS[report['kind']]}",
"",
"Sent from the Alkane Toolkit app's Bug report button.",
"",
"| | |",
"|---|---|",
]
for key, label in CONTEXT_FIELDS:
if ctx.get(key):
lines.append(f"| {label} | {cell(ctx[key])} |")
lines += ["", "---", "", no_mentions(report["text"])]
log = scrub(report["log"]).strip()
if log:
fence = fence_for(log)
lines += [
"",
"<details><summary>Recent activity log</summary>",
"",
fence,
no_mentions(log),
fence,
"",
"</details>",
]
return "\n".join(lines) + "\n"
class RateLimiter:
"""Sliding one-hour windows, per client IP and in all."""
def __init__(self, per_ip: int, total: int, clock=time.monotonic):
self.per_ip, self.total, self.clock = per_ip, total, clock
self.by_ip: dict[str, deque] = {}
self.all: deque = deque()
self.lock = threading.Lock()
def take(self, ip: str) -> float:
"""0 if the report may go now, else seconds until it may."""
now = self.clock()
with self.lock:
for q in [self.all, *self.by_ip.values()]:
while q and now - q[0] >= HOUR:
q.popleft()
self.by_ip = {k: q for k, q in self.by_ip.items() if q}
mine = self.by_ip.setdefault(ip, deque())
if len(mine) >= self.per_ip:
return HOUR - (now - mine[0])
if len(self.all) >= self.total:
return HOUR - (now - self.all[0])
mine.append(now)
self.all.append(now)
return 0.0
class Gitea:
def __init__(self, url: str, repo: str, token: str, timeout: float = 20):
self.api = url.rstrip("/") + "/api/v1/repos/" + repo
self.token, self.timeout = token, timeout
self.labels: dict[str, int] = {}
self.labels_at = 0.0
def _call(self, method: str, path: str, body: dict | None = None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(self.api + path, data=data, method=method)
req.add_header("Authorization", f"token {self.token}")
req.add_header("Accept", "application/json")
if data is not None:
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
return json.load(resp)
def label_ids(self, names: list[str]) -> list[int]:
"""IDs of the repository's labels by name (cached 10 minutes);
unknown names are skipped."""
if time.monotonic() - self.labels_at > 600:
try:
found = self._call("GET", "/labels?limit=50")
self.labels = {l["name"]: l["id"] for l in found}
self.labels_at = time.monotonic()
except (urllib.error.URLError, OSError, ValueError, KeyError):
pass
return [self.labels[n] for n in names if n in self.labels]
def file(self, title: str, body: str, labels: list[str]) -> tuple[int, str]:
issue = self._call("POST", "/issues", {
"title": title,
"body": body,
"labels": self.label_ids(labels),
})
return int(issue["number"]), str(issue["html_url"])
class Relay:
def __init__(self, gitea: Gitea, limiter: RateLimiter, log=print):
self.gitea, self.limiter, self.log = gitea, limiter, log
self.slots = threading.BoundedSemaphore(MAX_IN_FLIGHT)
def handle(self, ip: str, raw: bytes) -> tuple[int, dict, dict]:
"""Return (status, json body, extra headers)."""
try:
report = validate(raw)
except BadReport as bad:
self.log(f"report from {ip}: refused {bad.status} ({bad.message})")
return bad.status, {"error": bad.message}, {}
wait = self.limiter.take(ip)
if wait > 0:
self.log(f"report from {ip}: rate limited")
return 429, {"error": "Too many reports; try again later"}, {
"Retry-After": str(int(wait) + 1)}
if not self.slots.acquire(blocking=False):
return 503, {"error": "The report service is busy; try again shortly"}, {}
try:
number, url = self.gitea.file(
issue_title(report), issue_body(report), [report["kind"], FROM_APP_LABEL])
except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
self.log(f"report from {ip}: tracker error ({type(e).__name__})")
return 502, {"error": "The issue tracker did not answer; check the issue "
"list before sending again"}, {}
finally:
self.slots.release()
self.log(f"report from {ip}: filed #{number}")
return 201, {"number": number, "url": url}, {}
def make_handler(relay: Relay):
class Handler(BaseHTTPRequestHandler):
server_version = "alkane-report-relay"
sys_version = ""
def _send(self, status: int, body: dict, headers: dict | None = None):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
for k, v in (headers or {}).items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/healthz":
self._send(200, {"status": "ok"})
else:
self._send(404, {"error": "Not found"})
def do_POST(self):
if self.path != "/v1/report":
return self._send(404, {"error": "Not found"})
try:
length = int(self.headers.get("Content-Length", ""))
except ValueError:
return self._send(411, {"error": "Length required"})
if length < 0 or length > MAX_BODY:
return self._send(413, {"error": "The report is too large"})
raw = self.rfile.read(length)
ip = self.headers.get("X-Real-IP") or self.client_address[0]
status, body, headers = relay.handle(ip, raw)
self._send(status, body, headers)
def log_message(self, fmt, *args):
pass # one line per report comes from Relay.handle instead
return Handler
def main() -> None:
token_file = os.environ.get("GITEA_TOKEN_FILE", "/run/secrets/gitea_token")
with open(token_file) as fh:
token = fh.read().strip()
if not token:
sys.exit(f"empty token in {token_file}")
gitea = Gitea(os.environ.get("GITEA_URL", "https://gitea.bluefla.re"),
os.environ.get("GITEA_REPO", "blueflare/alkane-toolkit"), token)
limiter = RateLimiter(int(os.environ.get("RATE_PER_IP", "5")),
int(os.environ.get("RATE_GLOBAL", "60")))
relay = Relay(gitea, limiter, log=lambda m: print(m, flush=True))
host, _, port = os.environ.get("LISTEN", "0.0.0.0:8080").rpartition(":")
server = ThreadingHTTPServer((host or "0.0.0.0", int(port)), make_handler(relay))
print(f"report relay on {host}:{port} -> {gitea.api}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Tests for the report relay: python3 tools/report-relay/test_relay.py"""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import pathlib
import sys
import threading
import time
import unittest
import urllib.error
import urllib.request
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import relay # noqa: E402
TOKEN = "test-token-123"
# 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."""
def __init__(self, fail=False):
self.created = []
self.fail = fail
outer = self
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _json(self, status, body):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
assert self.headers["Authorization"] == f"token {TOKEN}"
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
return self._json(200, REPO_LABELS)
self._json(404, {})
def do_POST(self):
assert self.headers["Authorization"] == f"token {TOKEN}"
if outer.fail:
return self._json(500, {"message": "boom"})
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
outer.created.append((self.path, body))
n = len(outer.created)
self._json(201, {"number": n,
"html_url": f"https://gitea.example/blueflare/alkane-toolkit/issues/{n}"})
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
# 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()
self.server.server_close()
class RelayTests(unittest.TestCase):
def setUp(self):
self.gitea = FakeGitea()
self.now = [1000.0]
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
self.logs = []
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]}"
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.gitea.close()
def post(self, body, ip="198.51.100.7", path="/v1/report", raw=None):
data = raw if raw is not None else json.dumps(body).encode()
req = urllib.request.Request(self.url + path, data=data, method="POST",
headers={"Content-Type": "application/json",
"X-Real-IP": ip})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status, json.load(resp), resp.headers
except urllib.error.HTTPError as e:
return e.code, json.load(e), e.headers
def report(self, **over):
body = {"kind": "bug", "text": "Table is blank on macOS\nSteps: open the app.",
"app_version": "0.110.0", "platform": "macos-aarch64", "os": "macOS 15.1",
"appearance": "dark", "language": "en", "window": "1280x800", "log": ""}
body.update(over)
return body
def test_files_an_issue_with_title_body_and_labels(self):
status, body, _ = self.post(self.report(kind="feature", log="12:00 scan done"))
self.assertEqual(status, 201)
self.assertEqual(body["number"], 1)
self.assertTrue(body["url"].endswith("/issues/1"))
path, issue = self.gitea.created[0]
self.assertEqual(path, "/api/v1/repos/blueflare/alkane-toolkit/issues")
self.assertEqual(issue["title"], "Table is blank on macOS")
self.assertEqual(issue["labels"], [3, 9])
self.assertIn("**Type:** Feature request", issue["body"])
self.assertIn("| OS | macOS 15.1 |", issue["body"])
self.assertIn("Steps: open the app.", issue["body"])
self.assertIn("<details><summary>Recent activity log</summary>", issue["body"])
self.assertIn("filed #1", self.logs[-1])
self.assertNotIn("blank", " ".join(self.logs), "report text is never logged")
def test_scrubs_the_log_and_neutralises_mentions(self):
log = ("set pool url=stratum+tcp://w:hunter2@pool:3333 password=hunter2\n"
"Authorization: Bearer abc.def\n``` fence ```")
status, _, _ = self.post(self.report(text="@admin please look", log=log))
self.assertEqual(status, 201)
_, issue = self.gitea.created[0]
self.assertNotIn("hunter2", issue["body"])
self.assertNotIn("abc.def", issue["body"])
self.assertNotIn("@admin", issue["body"])
self.assertNotIn("@admin", issue["title"])
self.assertIn("````\n", issue["body"], "fence longer than the log's own")
def test_rejects_bad_reports(self):
cases = [
(self.report(text=" "), 422),
(self.report(kind="hack"), 422),
(self.report(text="x" * 8001), 413),
(self.report(log="y" * (16 * 1024 + 1)), 413),
(self.report(os="z" * 121), 422),
(self.report(os=5), 422),
([1, 2], 400),
]
for body, want in cases:
status, answer, _ = self.post(body)
self.assertEqual(status, want, body if not isinstance(body, dict) else answer)
self.assertIn("error", answer)
status, _, _ = self.post(None, raw=b"{not json")
self.assertEqual(status, 400)
status, _, _ = self.post(None, raw=b"x" * (relay.MAX_BODY + 1))
self.assertEqual(status, 413)
status, _, _ = self.post(self.report(), path="/v1/other")
self.assertEqual(status, 404)
self.assertEqual(self.gitea.created, [])
def test_rate_limits_per_ip_and_in_all(self):
for _ in range(2):
self.assertEqual(self.post(self.report())[0], 201)
status, body, headers = self.post(self.report())
self.assertEqual(status, 429)
self.assertGreater(int(headers["Retry-After"]), 0)
self.assertEqual(self.post(self.report(), ip="203.0.113.9")[0], 201)
self.assertEqual(self.post(self.report(), ip="203.0.113.10")[0], 429, "global cap of 3")
self.now[0] += relay.HOUR
self.assertEqual(self.post(self.report())[0], 201, "window slides")
def test_tracker_failure_is_reported(self):
self.gitea.fail = True
status, body, _ = self.post(self.report())
self.assertEqual(status, 502)
self.assertIn("check the issue list", body["error"])
def test_title_is_cut(self):
title = relay.issue_title({"text": "\n\n" + "w" * 300})
self.assertEqual(len(title), relay.MAX_TITLE_CHARS)
self.assertTrue(title.endswith("..."))
if __name__ == "__main__":
unittest.main()