Compare commits

..
13 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
20 changed files with 2515 additions and 177 deletions
+185 -22
View File
@@ -48,12 +48,33 @@ pub enum FetchError {
}
/// Where releases come from. Defaults to the alkane-os repo on the self-hosted
/// Gitea; the base URL and token are read from the environment.
/// 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 {
@@ -63,37 +84,126 @@ impl ReleaseSource {
Self::for_repo("blueflare", "alkane-os")
}
/// A release source for an arbitrary Gitea `owner`/`repo`. The base URL
/// (`ALKANE_RELEASE_BASE`, else the self-hosted Gitea) and the token
/// (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`, else the build-time embedded
/// token) are resolved exactly as for `alkane_os`.
/// 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 {
let base_url = std::env::var("ALKANE_RELEASE_BASE")
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "https://gitea.bluefla.re".to_string());
let token = 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()));
Self {
base_url,
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 {
format!(
"{}/api/v1/repos/{}/{}/releases?limit=50",
self.base_url.trim_end_matches('/'),
self.owner,
self.repo
)
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
)
}
}
}
@@ -174,7 +284,10 @@ fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
let config = TokenConfig::new(&src.token)?;
let mut cmd = Command::new("curl");
cmd.arg("-fsSL").arg("--max-time").arg("120");
// 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()))?;
@@ -192,6 +305,8 @@ fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), Fetc
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")
@@ -380,6 +495,54 @@ pub fn fetch_afw_url(
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");
+111 -1
View File
@@ -1388,9 +1388,118 @@ fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>
Ok(())
}
/// Build a bootable SD installation-media card image (and optionally write it to
/// a device). Zynq-7010 only for now.
///
/// afw make-media --kind stock --stock-package <zip|dir> --out card.img
/// afw make-media --kind alkane --mode simpleboot|installer --afw <f.afw> --out card.img
/// [--allow-unsigned] [--write /dev/sdX --confirm WRITE]
fn run_make_media(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
use alkane_flash::sd_media;
let opts = parse_args(
args,
&[
"kind",
"mode",
"afw",
"stock-package",
"board",
"out",
"write",
"confirm",
"expect-board",
],
&["allow-unsigned"],
)?;
let kind = opts
.value("kind")
.ok_or("usage: alkane-cli afw make-media --kind <stock|alkane> ... --out <card.img>")?;
let board = opts.value("board").unwrap_or("zynq-7010");
if board != "zynq-7010" {
return Err(format!("make-media supports --board zynq-7010 only (got {board})").into());
}
let out = opts
.value("out")
.map(PathBuf::from)
.or_else(|| opts.positionals.first().map(PathBuf::from))
.ok_or("make-media: --out <card.img> required")?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as u32)
.unwrap_or(0);
match kind {
"stock" => {
let pkg = opts
.value("stock-package")
.ok_or("make-media --kind stock needs --stock-package <zip|dir>")?;
let pkg_path = Path::new(pkg);
// Unpack a .zip to an ephemeral dir; use a directory as-is.
let staged;
let dir: PathBuf = if pkg_path.is_dir() {
pkg_path.to_path_buf()
} else if pkg_path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
{
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 = std::process::Command::new("unzip")
.args(["-o", "-q"])
.arg(pkg_path)
.arg("-d")
.arg(&staged)
.status()?;
if !status.success() {
return Err(format!("unzip {pkg} failed").into());
}
staged
} else {
return Err(
format!("--stock-package must be a directory or a .zip (got {pkg})").into(),
);
};
sd_media::build_stock_recovery_card(&dir, &out)?;
}
"alkane" => {
let afw_path = opts
.value("afw")
.ok_or("make-media --kind alkane needs --afw <file.afw>")?;
let verified = load_afw(afw_path, &opts)?;
match opts.value("mode").unwrap_or("simpleboot") {
"simpleboot" | "simple-boot" => {
sd_media::build_zynq_simpleboot_card(&verified, &out, now)?
}
"installer" => sd_media::build_zynq_installer_card(&verified, &out, now)?,
other => {
return Err(format!("--mode must be simpleboot|installer (got {other})").into())
}
}
}
other => return Err(format!("--kind must be stock|alkane (got {other})").into()),
}
println!("wrote card image: {}", out.display());
if let Some(dev) = opts.value("write") {
if opts.value("confirm") != Some("WRITE") {
return Err(format!(
"refusing to write to {dev} without --confirm WRITE (card image is at {})",
out.display()
)
.into());
}
eprintln!("writing {} to {dev} ...", out.display());
sd_media::write_image_to_device(&out, Path::new(dev))?;
println!("written to {dev}; sync complete");
}
Ok(())
}
fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let subcommand = args.first().ok_or(
"usage: alkane-cli afw <compat|fetch-latest|verify|inspect|plan|preflight|install|verify-live|restore|restore-stock|backup-check|restore-onboard>",
"usage: alkane-cli afw <compat|fetch-latest|verify|inspect|plan|preflight|install|verify-live|restore|restore-stock|backup-check|restore-onboard|make-media>",
)?;
let rest = &args[1..];
match subcommand.as_str() {
@@ -1413,6 +1522,7 @@ fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
"nand-restore-stock" => run_nand_restore_stock(rest),
"nand-backup-check" => run_nand_backup_check(rest),
"nand-restore-onboard" => run_nand_restore_onboard(rest),
"make-media" => run_make_media(rest),
other => Err(format!("unknown afw subcommand {other}").into()),
}
}
+1
View File
@@ -16,6 +16,7 @@ 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;
+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
}
}
+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

+144 -5
View File
@@ -137,18 +137,93 @@ fn parse_http_json(raw: &[u8]) -> Option<Value> {
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, or for a stock Antminer the Zynq-7010 (S17/T17
/// era, "XIL (C49)") control board.
/// what an Alkane board reports, the stock Antminer Zynq-7010 (S17/T17 era,
/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control
/// board.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
// A stock A113D (Amlogic AXG) control board -- the "a113d" install target
// (board_labels maps a113d -> "AML (C76)"). Decided on the control-board
// code, not the brand: asic-rs has no make for the Antminer BHB42XXX and
// reports its brand as "Unknown" (model "Unknown: ANTMINER BHB42XXX"), so
// the generic brand guard below would otherwise reject it. The "AML" code is
// only ever derived for an Amlogic Antminer control board, so this is
// specific on its own.
if row.cpu == "AML" && row.board_code == "C76" {
return Some("a113d".to_string());
}
if !row.brand.to_ascii_lowercase().contains("antminer") {
return None;
}
@@ -175,6 +250,15 @@ 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::*;
@@ -243,7 +327,10 @@ mod tests {
assert!(install_supported(&s17));
assert!(!is_alkane(&s17));
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
assert!(!install_supported(&stock("AML", "C76")));
// The Amlogic A113D control board is the "a113d" install target.
assert!(install_supported(&stock("AML", "C76")));
assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d"));
assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
@@ -274,7 +361,9 @@ mod tests {
assert!(!install_supported(&other("S19")));
assert!(!install_supported(&other("S17+")));
assert!(!install_supported(&other("")));
// A reported control board overrides the model.
// A reported control board overrides the model: an "S17" model on an
// Amlogic A113D control board resolves to a113d (the control board),
// not zynq (the model).
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
@@ -282,7 +371,57 @@ mod tests {
board_code: "C76".into(),
..Default::default()
};
assert!(!install_supported(&s17_on_aml));
assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d"));
}
#[test]
fn 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:
+130
View File
@@ -216,6 +216,136 @@ fn wait_for(
}
}
/// 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() {
+7
View File
@@ -16,6 +16,7 @@ mod fixtures;
mod i18n;
mod log_scan;
mod logs;
mod media_ops;
mod model;
mod naming;
mod pool_prefs;
@@ -49,6 +50,12 @@ fn main() {
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.
+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",
))
}
+12 -2
View File
@@ -533,8 +533,18 @@ pub fn start_scan(lines: Vec<String>, timeout_secs: u64) -> ScanHandle {
}
// asic-rs does not recognise a board running Alkane
// OS (no cgminer socket or vendor web UI exposed);
// the toolkit's own probe finds it.
None => (ip, crate::alkane_detect::detect(ip).await),
// 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)
}
}
}
})
+91 -6
View File
@@ -10,14 +10,75 @@
//! 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};
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;
@@ -83,6 +144,12 @@ pub struct StockHandle {
}
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);
@@ -154,8 +221,10 @@ pub fn start_install(
}
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::alkane_os(),
&ReleaseSource::for_asset_url(&url),
&name,
&url,
&download_dir(),
@@ -242,10 +311,26 @@ pub fn start_install(
let (ok, detail) =
match stock::install_from_stock(&ip, &afw_path, &verified, password.as_deref())
{
Ok(()) => (
true,
"installed alkane-os (verify liveness over the network)".to_string(),
),
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() {
+396 -141
View File
@@ -3,6 +3,7 @@
use crate::alkane_detect;
use crate::credentials;
use crate::media_ops;
use crate::model::*;
use crate::restore;
use crate::scan::{self, ScanMsg};
@@ -27,6 +28,11 @@ pub const ID_EXPORT: i32 = 109;
pub const ID_SETTINGS: i32 = 110;
// Bug report / feature request dialog (toolbar, between Export and Settings).
pub const ID_BUG_REPORT: i32 = 111;
// Unified "Data" toolbar icon button: a dropdown of Presets/Filter/Columns/Export.
pub const ID_DATA: i32 = 112;
// "Installation Media" toolbar icon button: opens the SD-card build dialog
// without needing to right-click a miner.
pub const ID_MEDIA_TOOLBAR: i32 = 113;
const ID_REPORT_SEND: i32 = 240;
const ID_REPORT_CLOSE: i32 = 241;
const ID_REPORT_OPEN: i32 = 242;
@@ -105,6 +111,18 @@ const ID_POOLS_CANCEL: i32 = 789;
const ID_CTX_INSTALL_ALKANE: i32 = 770;
const ID_CTX_UNINSTALL_ALKANE: i32 = 771;
const ID_CTX_UPDATE_ALKANE: i32 = 772;
// "Installation Media..." context item (build a bootable SD card).
const ID_CTX_INSTALL_MEDIA: i32 = 773;
// Installation-Media dialog controls (free id block above the install dialog's).
const ID_MEDIA_OK: i32 = 1015;
const ID_MEDIA_CANCEL: i32 = 1016;
const ID_MEDIA_KIND_CHOICE: i32 = 1017;
const ID_MEDIA_DEVICE_CHOICE: i32 = 1019;
const ID_MEDIA_BROWSE: i32 = 1020;
const ID_MEDIA_RELOAD_DEVS: i32 = 1022;
// Install dialog control-board selector (lets the operator pick/override the
// control board, needed when the scan could not determine it).
const ID_INSTALL_BOARD_CHOICE: i32 = 1023;
const ID_INSTALL_OK: i32 = 1006;
const ID_INSTALL_CANCEL: i32 = 1007;
const ID_INSTALL_RELEASE_CHOICE: i32 = 1008;
@@ -541,41 +559,6 @@ fn ascii_bar(pct: u8) -> String {
format!("[{}{}]", "#".repeat(filled), "-".repeat(width - filled))
}
/// A read-only flash-plan summary for a local `.afw`: its tier and which regions
/// it overwrites (U-Boot / Kernel / Userspace), from the bundle's own manifest.
/// Shown in the install dialog when a file is picked so the operator sees exactly
/// what the flash touches before starting.
fn afw_plan_text(path: &str, expect_board: &str) -> String {
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
// Verify against the install target's board (review #6): a file for another
// board then surfaces as an error here instead of showing a plausible plan
// that start_install would later reject.
let opts = VerifyOptions {
allow_unsigned: true,
expect_board: Some(expect_board.to_string()),
};
match verify_afw(std::path::Path::new(path), &opts) {
Ok(v) => {
let p = v.manifest.flash_plan();
let mark = |b: bool| if b { "[x]" } else { "[ ]" };
format!(
"Flash plan: tier {} (board {}). Overwrites:\n {} U-Boot{}\n {} Kernel\n {} Userspace (rootfs)",
p.tier,
v.manifest.board,
mark(p.writes_uboot),
if p.writes_uboot {
""
} else {
" -- preserved"
},
mark(p.writes_kernel),
mark(p.writes_userspace),
)
}
Err(e) => format!("Could not read flash plan from this file: {e}"),
}
}
/// The colour a component-health state renders in (round 13 #3): grey =
/// unreachable, red = detected but down, yellow = sub-optimal, green = healthy.
fn health_color(pal: &Palette, h: crate::model::CompHealth) -> (u8, u8, u8) {
@@ -673,6 +656,12 @@ const SVG_BOLT_FULL: &str = include_str!("../assets/icons/bolt-solid-full.svg");
const SVG_BRAIN_FULL: &str = include_str!("../assets/icons/brain-solid-full.svg");
const SVG_FAN_FULL: &str = include_str!("../assets/icons/fan-solid-full.svg");
const SVG_CHIP_FULL: &str = include_str!("../assets/icons/microchip-solid-full.svg");
// Toolbar icon buttons (round 19): gear (Settings), bug (report), database
// (Data dropdown), sd-card (Installation Media).
const SVG_GEAR: &str = include_str!("../assets/icons/gear.svg");
const SVG_BUG: &str = include_str!("../assets/icons/bug.svg");
const SVG_DATA: &str = include_str!("../assets/icons/database.svg");
const SVG_SDCARD: &str = include_str!("../assets/icons/sd-card.svg");
/// KPI card minimum widths. The count cards (Total/Hashing/...) are narrow; the
/// two wide cards (SHA-256 Hashrate, Est. power) need more room so their
@@ -990,6 +979,7 @@ pub struct App {
stock_op: Option<stock_ops::StockHandle>,
install_dialog: Widget,
install_release_choice: Widget,
install_board_choice: Widget,
install_unsigned_check: Widget,
install_releases: Vec<ReleaseInfo>,
install_ips: Vec<String>,
@@ -1005,10 +995,24 @@ pub struct App {
install_local_label: Widget,
// A read-only flash-plan checklist (tier + which regions are overwritten),
// filled from a picked local .afw's manifest.
install_plan_label: Widget,
// The release repo (owner/repo) the picker scans; defaults to
// blueflare/alkane-os, editable + reloadable to any compatible repo.
install_repo_input: Widget,
// Installation-Media dialog (sd_media / media_ops): build a bootable SD card
// for a card-bootable board (Zynq first). One background job, reusing
// `stock_op`. The widgets + the state captured when the dialog opens.
media_dialog: Widget,
media_kind_choice: Widget,
media_device_choice: Widget,
media_unsigned_check: Widget,
media_source_label: Widget,
// The browsed source: an .afw (alkane kinds) or a vendor package (stock).
media_source_path: Option<String>,
// Removable devices behind the device choice, by item index (index 0 is the
// "build image only, do not write" option, so devices start at index 1).
media_devices: Vec<media_ops::RemovableDevice>,
// The board family the card targets (e.g. "zynq-7010").
media_board: String,
uninstall_dialog: Widget,
uninstall_firmware_input: Widget,
// Restore-to-stock source: the board's on-board stock backup (checkbox,
@@ -1244,21 +1248,36 @@ pub fn build(frame: Widget) -> App {
// when the language changes (round 15 #13).
let mut l10n_labels: Vec<(Widget, &'static str)> = Vec::new();
l10n_labels.push((ranges_btn, "Scan ranges"));
let mut tbtn = |label: &'static str, id: i32| -> Widget {
let b = Widget::button(panel, &crate::i18n::t(label), id);
ctl.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
l10n_labels.push((b, label));
// Compact icon toolbar (round 19): a unified "Data" dropdown (presets /
// filter / columns / export), an Installation-Media (SD card) button, Bug
// report, and Settings. Logs moved into the Settings dropdown
// (ID_LOGS_OPEN), so the old standalone Log button is gone. Icon buttons
// carry no text label, so they are not tracked for localization; their
// tooltips name them.
let icon_fg = if wx_rs::is_dark() {
(0xDD, 0xDD, 0xDD)
} else {
(0x33, 0x33, 0x33)
};
let icon_btn = |svg: &str, id: i32, tip: &str| -> Widget {
let b = Widget::svg_button(panel, &svg_recolored(svg, icon_fg), id, 16, 16);
b.set_tool_tip(&crate::i18n::t(tip));
ctl.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
b
};
let _presets_btn = tbtn("Presets", ID_PRESETS);
let _filter_btn = tbtn("Filter", ID_FILTER);
let _columns_btn = tbtn("Columns", ID_COLUMNS);
let _export_btn = tbtn("Export", ID_EXPORT);
let _report_btn = tbtn("Bug report", ID_BUG_REPORT);
// The old Credentials button is now a Settings menu (round 15 #13).
let _creds_btn = tbtn("Settings", ID_SETTINGS);
// Toggle between the fleet table and the live activity log.
let log_toggle_btn = tbtn("Log", ID_LOG_TOGGLE);
let _data_btn = icon_btn(SVG_DATA, ID_DATA, "Data: presets, filter, columns, export");
let _media_btn = icon_btn(
SVG_SDCARD,
ID_MEDIA_TOOLBAR,
"Create installation media (SD card)",
);
let _report_btn = icon_btn(SVG_BUG, ID_BUG_REPORT, "Report a bug or request a feature");
let _settings_btn = icon_btn(SVG_GEAR, ID_SETTINGS, "Settings, language, and logs");
// The inline table/log view toggle is kept (toggle_log_view / log_view) but
// no longer surfaced as a toolbar button; logs are reached from Settings.
// Created hidden so the field and toggle_log_view stay valid.
let log_toggle_btn = Widget::button(panel, "Log", ID_LOG_TOGGLE);
log_toggle_btn.show(false);
root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
// Track the KPI captions for live re-localization (index 5, the hashrate
// caption, is dynamic per-algorithm so it is refreshed by refresh_kpis).
@@ -1410,6 +1429,7 @@ pub fn build(frame: Widget) -> App {
stock_op: None,
install_dialog: frame,
install_release_choice: frame,
install_board_choice: frame,
install_unsigned_check: frame,
install_releases: Vec::new(),
install_ips: Vec::new(),
@@ -1417,8 +1437,15 @@ pub fn build(frame: Widget) -> App {
install_is_update: false,
install_local_path: None,
install_local_label: frame,
install_plan_label: frame,
install_repo_input: frame,
media_dialog: frame,
media_kind_choice: frame,
media_device_choice: frame,
media_unsigned_check: frame,
media_source_label: frame,
media_source_path: None,
media_devices: Vec::new(),
media_board: stock_ops::DEFAULT_BOARD.to_string(),
uninstall_dialog: frame,
uninstall_firmware_input: frame,
uninstall_onboard_check: frame,
@@ -2025,13 +2052,23 @@ impl App {
// - Uninstall: a board running Alkane OS (restored to stock).
// A mixed stock/Alkane selection gets neither Install nor Update. The
// engine still gates on compatibility.
let supported = selected.iter().all(|r| alkane_detect::install_supported(r));
// Offer install when every selected board is either a known supported
// control board, or a stock Antminer whose control board is unknown
// (found by its :80 web UI) -- the latter installs with a manually
// chosen control board in the dialog.
let supported = selected.iter().all(|r| {
alkane_detect::install_supported(r) || alkane_detect::is_unidentified_stock_antminer(r)
});
let all_alkane = selected.iter().all(|r| alkane_detect::is_alkane(r));
let none_alkane = selected.iter().all(|r| !alkane_detect::is_alkane(r));
let install = supported && none_alkane;
let update = supported && all_alkane;
let uninstall = all_alkane;
if install || update || uninstall {
// "Installation Media" applies to card-bootable boards (Zynq); it builds
// an SD card and does not need the board to be reachable now.
let media =
!selected.is_empty() && selected.iter().all(|r| alkane_detect::media_supported(r));
if install || update || uninstall || media {
menu.menu_append_separator();
}
if install {
@@ -2046,6 +2083,9 @@ impl App {
"Uninstall alkane OS (restore to stock)...",
);
}
if media {
menu.menu_append(ID_CTX_INSTALL_MEDIA, "Installation Media (SD card)...");
}
self.pending_popup = Some((t, menu));
}
@@ -2773,27 +2813,25 @@ impl App {
/// that carry an .afw compatible with the target board (newest first). Called
/// when the dialog opens and from the Reload button. Requires
/// `install_release_choice` to already exist.
fn populate_install_releases(&mut self, owner: &str, repo: &str) {
fn populate_install_releases(&mut self, src: &ReleaseSource) {
let board = self.install_board.clone();
wx_rs::set_status_text(&format!("scanning {owner}/{repo} releases..."));
let releases: Vec<ReleaseInfo> =
match fetch::list_releases(&ReleaseSource::for_repo(owner, repo)) {
Ok(list) => list
.into_iter()
.filter(|r| !r.draft && r.is_compatible_with(&board))
.collect(),
Err(e) => {
wx_rs::set_status_text(&format!("could not list {owner}/{repo} releases: {e}"));
Vec::new()
}
};
let label = format!("{}/{}", src.owner, src.repo);
wx_rs::set_status_text(&format!("scanning {label} releases..."));
let releases: Vec<ReleaseInfo> = match fetch::list_releases(src) {
Ok(list) => list
.into_iter()
.filter(|r| !r.draft && r.is_compatible_with(&board))
.collect(),
Err(e) => {
wx_rs::set_status_text(&format!("could not list {label} releases: {e}"));
Vec::new()
}
};
self.install_releases = releases;
let choice = self.install_release_choice;
choice.choice_clear();
if self.install_releases.is_empty() {
choice.choice_append(&format!(
"(no release with an .afw for {board} in {owner}/{repo})"
));
choice.choice_append(&format!("(no release with an .afw for {board} in {label})"));
} else {
for (i, r) in self.install_releases.iter().enumerate() {
let tag = if r.tag.is_empty() {
@@ -2809,24 +2847,18 @@ impl App {
choice.choice_set_selection(0);
}
wx_rs::set_status_text(&format!(
"{} release(s) for {board} in {owner}/{repo}",
"{} release(s) for {board} in {label}",
self.install_releases.len()
));
}
/// Reload the install picker from the owner/repo currently typed in the
/// dialog's repo field (default blueflare/alkane-os if blank/malformed).
/// Reload the install picker from the repo URL currently typed in the
/// dialog's repo field. Accepts a full Gitea or GitHub repo URL (or a bare
/// `owner/repo` on the default Gitea); falls back to blueflare/alkane-os.
fn reload_install_repo(&mut self) {
let raw = self.install_repo_input.get_value();
let raw = raw.trim();
let (owner, repo) = raw.split_once('/').unwrap_or(("blueflare", "alkane-os"));
let owner = owner.trim();
let repo = repo.trim();
if owner.is_empty() || repo.is_empty() {
self.populate_install_releases("blueflare", "alkane-os");
} else {
self.populate_install_releases(owner, repo);
}
let src = ReleaseSource::from_url(raw.trim()).unwrap_or_else(ReleaseSource::alkane_os);
self.populate_install_releases(&src);
self.install_dialog.layout();
}
@@ -2872,36 +2904,46 @@ impl App {
Widget::static_text(
dlg,
&if update {
format!(
"Update alkane OS on {n} board(s) already running it (updated in place; BOOT.bin is never written):\n{}",
ips.join(", ")
)
format!("Update {n} board(s):\n{}", ips.join(", "))
} else {
format!(
"Install alkane OS onto {n} board(s) currently on stock:\n{}",
ips.join(", ")
)
format!("Install onto {n} board(s):\n{}", ips.join(", "))
},
),
0,
sf::BORDER_ALL,
12,
);
// Control-board selector: defaults to the detected board, but the
// operator can override it -- required when the scan could not determine
// the control board (a stock Antminer found only by its :80 web UI).
root.add(
Widget::static_text(dlg, &format!("Target board: {board}")),
Widget::static_text(dlg, "Control board:"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let board_choice = Widget::choice(dlg, ID_INSTALL_BOARD_CHOICE);
let mut board_sel = 0;
for (i, (id, desc)) in stock_ops::SUPPORTED_BOARDS.iter().enumerate() {
board_choice.choice_append(&format!("{id} -- {desc}"));
if *id == board {
board_sel = i as i32;
}
}
board_choice.choice_set_selection(board_sel);
root.add(
Widget::static_text(
dlg,
if update {
"Release to update to (newest first):"
} else {
"Release to install (newest first):"
},
),
board_choice,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
self.install_board_choice = board_choice;
// Keep install_board consistent with the selector's initial choice.
if let Some((id, _)) = stock_ops::SUPPORTED_BOARDS.get(board_sel as usize) {
self.install_board = id.to_string();
}
root.add(
Widget::static_text(dlg, "Release"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
@@ -2919,14 +2961,15 @@ impl App {
// format; defaults to blueflare/alkane-os. Reload re-scans it and keeps
// only the releases compatible with this board.
root.add(
Widget::static_text(dlg, "Release repo (owner/repo), then Reload:"),
Widget::static_text(dlg, "Release repo"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let repo_row = Widget::box_sizer(false);
let repo_input = Widget::text_ctrl(dlg, false);
repo_input.set_value("blueflare/alkane-os");
repo_input.set_value("https://gitea.bluefla.re/blueflare/alkane-os");
repo_input.set_tool_tip("A Gitea or GitHub repo URL, or owner/repo. Reload to re-scan.");
repo_row.add(
repo_input,
1,
@@ -2942,25 +2985,22 @@ impl App {
12,
);
// Initial population from the default repo.
self.populate_install_releases("blueflare", "alkane-os");
self.populate_install_releases(&ReleaseSource::alkane_os());
// Or install from a local .afw the operator picks (the CLI's local-file
// install, now in the GUI). When a file is chosen it takes precedence
// over the release selected above; the label shows the current choice.
root.add(
Widget::static_text(dlg, "Or install from a local .afw file:"),
Widget::static_text(dlg, "Local .afw"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let browse_row = Widget::box_sizer(false);
browse_row.add(
Widget::button(dlg, "Browse local .afw...", ID_INSTALL_BROWSE),
0,
sf::BORDER_RIGHT,
6,
);
let local_label = Widget::static_text(dlg, "(none; using the selected release above)");
let browse_btn = Widget::button(dlg, "Browse...", ID_INSTALL_BROWSE);
browse_btn.set_tool_tip("Install a local .afw instead of the selected release.");
browse_row.add(browse_btn, 0, sf::BORDER_RIGHT, 6);
let local_label = Widget::static_text(dlg, "(using selected release)");
browse_row.add(local_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0);
self.install_local_label = local_label;
root.add_sizer(
@@ -2970,36 +3010,17 @@ impl App {
12,
);
// Flash-plan checklist: detects the tier and which regions a picked local
// .afw overwrites (U-Boot / Kernel / Userspace).
let plan = Widget::static_text(
dlg,
"Flash plan: pick a local .afw above to see its tier and what it overwrites.",
);
root.add(plan, 0, sf::BORDER_ALL, 12);
self.install_plan_label = plan;
// No password field (issue #46): the board login comes from Settings (or
// the firmware's shipped default when unset).
// Current bench .afw files are unsigned (SHA-256 integrity, no Ed25519).
let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)");
unsigned.set_checked(true);
unsigned
.set_tool_tip("Bench images are unsigned: SHA-256 proves integrity, not authenticity.");
root.add(unsigned, 0, sf::BORDER_ALL, 12);
self.install_unsigned_check = unsigned;
// No typed-FLASH step (issue #41): the dialog, the board list and the
// Install button are the confirmation. The warning stays visible.
root.add(
Widget::static_text(
dlg,
"This reflashes the control board. Click Install to start.",
),
0,
sf::BORDER_ALL,
12,
);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(
@@ -3026,6 +3047,186 @@ impl App {
Some(dlg)
}
/// Build the "Installation Media" dialog: choose a card kind, an image
/// source, and a target SD device, then build (and optionally write) a
/// bootable card for a card-bootable board (Zynq first).
fn build_install_media_dialog(&mut self) -> Option<Widget> {
if self.flash_busy() {
wx_rs::set_status_text("busy -- try again once the current operation finishes");
return None;
}
let board = self
.selected_rows()
.into_iter()
.find_map(crate::alkane_detect::board_family)
.unwrap_or_else(|| stock_ops::DEFAULT_BOARD.to_string());
self.media_board = board.clone();
self.media_source_path = None;
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Installation Media");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(dlg, &format!("Control board: {board}")),
0,
sf::BORDER_ALL,
12,
);
root.add(
Widget::static_text(dlg, "Media type"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let kind = Widget::choice(dlg, ID_MEDIA_KIND_CHOICE);
for k in [
media_ops::MediaKind::StockRecovery,
media_ops::MediaKind::AlkaneSimpleBoot,
media_ops::MediaKind::AlkaneInstaller,
] {
kind.choice_append(k.label());
}
kind.choice_set_selection(2); // default: alkane installer
root.add(kind, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
self.media_kind_choice = kind;
root.add(
Widget::static_text(dlg, "Source"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let browse_row = Widget::box_sizer(false);
let src_browse = Widget::button(dlg, "Browse...", ID_MEDIA_BROWSE);
src_browse.set_tool_tip(
"An .afw for alkane media, or a genuine vendor package (.zip) for stock recovery.",
);
browse_row.add(src_browse, 0, sf::BORDER_RIGHT, 6);
let src_label = Widget::static_text(dlg, "(none selected)");
browse_row.add(src_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0);
self.media_source_label = src_label;
root.add_sizer(
browse_row,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)");
unsigned.set_checked(true);
unsigned
.set_tool_tip("Bench images are unsigned: SHA-256 proves integrity, not authenticity.");
root.add(unsigned, 0, sf::BORDER_ALL, 12);
self.media_unsigned_check = unsigned;
let target = Widget::static_text(dlg, "Target card");
target.set_tool_tip("Writing a card erases it entirely. Confirm the device first.");
root.add(
target,
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let dev_row = Widget::box_sizer(false);
let dev = Widget::choice(dlg, ID_MEDIA_DEVICE_CHOICE);
dev_row.add(dev, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT, 6);
dev_row.add(Widget::button(dlg, "Rescan", ID_MEDIA_RELOAD_DEVS), 0, 0, 0);
self.media_device_choice = dev;
root.add_sizer(
dev_row,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
self.populate_media_devices();
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(
Widget::button(dlg, "Create", ID_MEDIA_OK),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, "Cancel", ID_MEDIA_CANCEL),
0,
sf::BORDER_ALL,
6,
);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(580, 480);
dlg.fit(dlg);
self.media_dialog = dlg;
Some(dlg)
}
/// Fill the media device choice from a fresh removable-device scan. Index 0
/// is "build an image file only" (no card write); real devices follow.
fn populate_media_devices(&mut self) {
self.media_devices = media_ops::list_removable_devices();
let c = self.media_device_choice;
c.choice_clear();
c.choice_append("Build an image file only (do not write a card)");
for d in &self.media_devices {
c.choice_append(&d.describe());
}
c.choice_set_selection(if self.media_devices.is_empty() { 0 } else { 1 });
}
/// Start building the requested card (and writing it, if a device is chosen)
/// on the shared background worker. Reuses `stock_op` and its drain.
fn apply_make_media_confirm(&mut self) {
if self.flash_busy() {
return;
}
let kind = match self.media_kind_choice.choice_get_selection() {
0 => media_ops::MediaKind::StockRecovery,
1 => media_ops::MediaKind::AlkaneSimpleBoot,
_ => media_ops::MediaKind::AlkaneInstaller,
};
let source = match &self.media_source_path {
Some(p) => std::path::PathBuf::from(p),
None => {
wx_rs::set_status_text("pick an image source (.afw or a stock package) first");
return;
}
};
let dev_sel = self.media_device_choice.choice_get_selection();
let device = if dev_sel <= 0 {
None
} else {
self.media_devices
.get((dev_sel - 1) as usize)
.map(|d| std::path::PathBuf::from(&d.path))
};
let allow_unsigned = self.media_unsigned_check.is_checked();
let image_out = alkane_core::platform::config_path("media")
.join(format!("{}-card.img", self.media_board));
if let Some(parent) = image_out.parent() {
let _ = std::fs::create_dir_all(parent);
}
self.media_dialog.close(1);
let target = device
.as_ref()
.map(|d| d.display().to_string())
.unwrap_or_else(|| "image file".into());
wx_rs::set_status_text(&format!(
"building {} card -> {target}...",
self.media_board
));
self.stock_op = Some(media_ops::start_make_media(media_ops::MediaRequest {
kind,
source,
device,
image_out,
allow_unsigned,
}));
}
/// Apply the install confirmation: validate the typed keyword, resolve the
/// chosen release asset, and start the network-only from-stock install.
fn apply_install_confirm(&mut self) {
@@ -3034,7 +3235,13 @@ impl App {
self.install_dialog.close(0);
return;
}
let board = self.install_board.clone();
// Take the control board from the selector (the operator may have picked
// or overridden it, e.g. for a stock Antminer the scan could not identify).
let board = stock_ops::SUPPORTED_BOARDS
.get(self.install_board_choice.choice_get_selection().max(0) as usize)
.map(|(id, _)| id.to_string())
.unwrap_or_else(|| self.install_board.clone());
self.install_board = board.clone();
// Source: a local .afw the operator picked takes precedence; otherwise
// the selected Gitea release's asset for this board.
let (source, source_name) = if let Some(path) = self.install_local_path.clone() {
@@ -3528,6 +3735,12 @@ impl App {
// Settings menu items (round 15 #13).
ID_SCAN_CREDS => return Some(self.build_firmware_creds_dialog()),
ID_LOGS_OPEN => return Some(self.build_logs_dialog()),
// "Data" dropdown items (round 19): the former standalone toolbar
// buttons, now entries in one icon button's menu.
ID_PRESETS => return Some(self.build_presets_dialog()),
ID_FILTER => return Some(self.build_filter_dialog()),
ID_COLUMNS => return Some(self.build_columns_dialog()),
ID_EXPORT => return self.open_export_dialog(),
ID_HDR_SORT_ASC | ID_HDR_SORT_DESC | ID_HDR_SORT_REL_ASC | ID_HDR_SORT_REL_DESC
| ID_HDR_HIDE | ID_HDR_AUTOSIZE | ID_HDR_AUTOSIZE_ALL | ID_HDR_COLUMNS => {
return self.on_header_menu(id)
@@ -3544,6 +3757,7 @@ impl App {
ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(false),
ID_CTX_UPDATE_ALKANE => return self.build_install_dialog(true),
ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_dialog(),
ID_CTX_INSTALL_MEDIA => return self.build_install_media_dialog(),
ID_CTX_POOLS => return self.build_pools_dialog(),
ID_CTX_FLASH => {
// A flash needs exclusive hardware access; don't even prompt if
@@ -4542,8 +4756,14 @@ impl App {
for ip in expired {
awaiting.remove(&ip);
op_status.remove(&ip);
// The install worker already verifies liveness over SSH; this only
// means the HTTP scan probe did not pick the board up, so its row
// will not auto-refresh to the alkane entry. Common for a minimal
// image that serves SSH but not the HTTP API -- not an install
// failure.
crate::logs::log(format!(
"{ip}: installed, but did not answer as alkane within the verify window"
"{ip}: not answering the alkane HTTP API; its row will not auto-update \
(the image may serve only SSH). See the install result above."
));
}
}
@@ -5441,6 +5661,20 @@ impl App {
/// Build + queue the Settings popup menu (round 15 #13): Credentials, a
/// Language submenu, and the Logs page.
/// The unified "Data" toolbar dropdown: presets, filter, columns, export.
/// The items reuse the existing action ids and are dispatched by
/// `on_menu_item` (same as any popped menu).
fn open_data_menu(&mut self) {
let t = crate::i18n::t;
let menu = Widget::menu_new();
menu.menu_append(ID_PRESETS, &t("Presets..."));
menu.menu_append(ID_FILTER, &t("Filter..."));
menu.menu_append(ID_COLUMNS, &t("Columns..."));
menu.menu_append_separator();
menu.menu_append(ID_EXPORT, &t("Export..."));
self.pending_popup = Some((Widget::main_frame(), menu));
}
fn open_settings_menu(&mut self) {
let menu = Widget::menu_new();
menu.menu_append(ID_SCAN_CREDS, &crate::i18n::t("Credentials"));
@@ -6179,6 +6413,14 @@ impl App {
self.filter_pending_op = Some(sel);
wx_rs::call_after(DEFER_FILTER);
}
ID_INSTALL_BOARD_CHOICE => {
// The operator changed the target control board: re-filter the
// release picker for the new board.
if let Some((board, _)) = stock_ops::SUPPORTED_BOARDS.get(sel.max(0) as usize) {
self.install_board = board.to_string();
self.reload_install_repo();
}
}
_ => {}
}
}
@@ -6229,6 +6471,8 @@ impl App {
ID_EXPORT_ALL => self.export_check_all(true),
ID_EXPORT_NONE => self.export_check_all(false),
ID_SETTINGS => self.open_settings_menu(),
ID_DATA => self.open_data_menu(),
ID_MEDIA_TOOLBAR => return self.build_install_media_dialog(),
ID_LOG_TOGGLE => self.toggle_log_view(),
ID_BUG_REPORT => return Some(self.build_report_dialog()),
ID_REPORT_SEND => self.send_report(),
@@ -6299,19 +6543,12 @@ impl App {
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.clone());
self.install_local_label
.set_label(&format!("Using local file: {name}"));
let board = self.install_board.clone();
self.install_plan_label
.set_label(&afw_plan_text(&path, &board));
self.install_local_label.set_label(&name);
self.install_local_path = Some(path);
self.install_dialog.layout();
} else {
self.install_local_label
.set_label("(none; using the selected release above)");
self.install_plan_label.set_label(
"Flash plan: pick a local .afw above to see its tier and what it overwrites.",
);
.set_label("(using selected release)");
self.install_local_path = None;
}
}
@@ -6335,6 +6572,24 @@ impl App {
self.uninstall_ips.clear();
self.uninstall_dialog.close(0);
}
ID_MEDIA_OK => self.apply_make_media_confirm(),
ID_MEDIA_CANCEL => self.media_dialog.close(0),
ID_MEDIA_RELOAD_DEVS => self.populate_media_devices(),
ID_MEDIA_BROWSE => {
if let Some(path) = Widget::file_dialog(
self.media_dialog,
"Choose an .afw (alkane) or a stock vendor package (.zip)",
) {
let name = std::path::Path::new(&path)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.clone());
self.media_source_label
.set_label(&format!("Source: {name}"));
self.media_source_path = Some(path);
self.media_dialog.layout();
}
}
ID_POOLS_OK => self.apply_pools(),
ID_POOLS_CANCEL => self.pools_dialog.close(0),
// Pool-preset manager buttons (round 18 #8b).
+5
View File
@@ -1,5 +1,10 @@
# 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.
+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.
+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) }
@@ -2140,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
+17
View File
@@ -121,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);
@@ -949,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) }