Compare commits

...
Author SHA1 Message Date
noahandClaude Opus 4.8 d2d4c085ae fix(gui): per-target credentials for install and restore (#46, #51)
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 31m29s
"Install failed due to credentials" was the #46 change pulling one generic
saved SSH login for both directions. Install targets a stock board and restore
targets an alkane board, which need different logins. Add the alkane
control-board login to the shipped defaults ("Alkane" root/alkane) and a
`cred_for(firmware)` helper (saved per-firmware override, else shipped default).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 09:45:46 -06:00
noah 224b3b37e8 Merge pull request 'main: find Alkane OS boards in the scan; install/update/uninstall only where they apply' (#36) from next into main
build-test-release / release (push) Successful in 21m54s
build-test-release / windows (push) Successful in 32m55s
2026-11-12 15:42:14 -07:00
16 changed files with 2235 additions and 299 deletions
+5 -70
View File
@@ -195,73 +195,8 @@ jobs:
if: always()
run: python3 ci/cleanup-generated.py
# The Windows build of the same change (main's release gate, run on the PR):
# clippy for the Windows target, the release .exe, every unit test under
# Wine, and the headless UI self-test under Wine. Only for changes that can
# affect the binary (the "full" surface).
verify-windows:
needs: verify
if: needs.verify.outputs.surface == 'full'
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Windows toolchain
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- name: Cache vendored wxMSW build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (Windows target, warnings are errors)
run: bash ci/windows-ci.sh clippy
- name: Build (Windows)
run: bash ci/windows-ci.sh build
- name: Unit tests (Windows build, under Wine)
run: bash ci/windows-ci.sh test
- name: Headless UI self-test (Windows build, under Wine)
run: bash ci/windows-ci.sh selftest
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
# The Windows build of each change is validated on the main release run
# (build-test-release / windows-native), not on the PR gate: it is a full
# mingw + Wine cross-build that roughly doubled PR wall-clock. PRs verify Linux
# (clippy, build, tests, self-test) fast; Windows is still built and shipped at
# release, so a Windows-only break surfaces on the merge to main.
+148
View File
@@ -155,6 +155,54 @@ pub struct AfwManifest {
pub notes: Option<String>,
}
/// What an `.afw` bundle overwrites on the target, derived from its manifest.
///
/// Tiers mirror the flash tiers: 1 = update (userspace / HAL only, no kernel or
/// bootloader write), 2 = kernel (kernel, dtb and boot images; bootloader
/// preserved), 3 = bootloader (U-Boot/SPL is rewritten as well).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FlashPlan {
pub tier: u8,
pub writes_uboot: bool,
pub writes_kernel: bool,
pub writes_userspace: bool,
}
impl AfwManifest {
/// Compute the flash tier and the regions this bundle overwrites. Pure
/// computation over the parsed manifest; no device or file access.
///
/// - `writes_uboot`: `bootloader_policy` is [`BootloaderPolicy::Include`]
/// (anything but `Preserve`), or an image with role `bootloader` exists.
/// - `writes_kernel`: an image with role `kernel`, `dtb` or `boot` exists.
/// - `writes_userspace`: an image with role `rootfs` exists.
/// - `tier`: 3 if `writes_uboot`, else 2 if `writes_kernel`, else 1.
pub fn flash_plan(&self) -> FlashPlan {
let has_role = |roles: &[&str]| {
self.images
.iter()
.any(|image| roles.contains(&image.role.as_str()))
};
let writes_uboot =
self.bootloader_policy != BootloaderPolicy::Preserve || has_role(&["bootloader"]);
let writes_kernel = has_role(&["kernel", "dtb", "boot"]);
let writes_userspace = has_role(&["rootfs"]);
let tier = if writes_uboot {
3
} else if writes_kernel {
2
} else {
1
};
FlashPlan {
tier,
writes_uboot,
writes_kernel,
writes_userspace,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AfwMember {
pub name: String,
@@ -1080,6 +1128,106 @@ mod tests {
));
}
/// Build a parsed manifest with the given bootloader policy and one image
/// per listed role (payload bytes are irrelevant to `flash_plan`).
fn plan_manifest(policy: &str, roles: &[&str]) -> AfwManifest {
let mut value = manifest(&[0_u8; 4]);
value["bootloader_policy"] = json!(policy);
value["images"] = json!(roles
.iter()
.enumerate()
.map(|(i, role)| json!({
"name": format!("img{i}"), "file": format!("payload/img{i}"),
"role": role, "format": "raw", "size": 4, "sha256": "0".repeat(64),
"partition": null, "install": false
}))
.collect::<Vec<_>>());
serde_json::from_value(value).unwrap()
}
#[test]
fn flash_plan_tier2_preserve_kernel_and_rootfs() {
let plan = plan_manifest("preserve", &["kernel", "dtb", "rootfs"]).flash_plan();
assert_eq!(plan.tier, 2);
assert!(plan.writes_kernel);
assert!(plan.writes_userspace);
assert!(!plan.writes_uboot);
}
#[test]
fn flash_plan_tier3_include_with_bootloader_image() {
let plan =
plan_manifest("include", &["bootloader", "kernel", "dtb", "rootfs"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot);
assert!(plan.writes_kernel);
assert!(plan.writes_userspace);
}
#[test]
fn flash_plan_tier3_from_bootloader_image_alone() {
// A bootloader image forces tier 3 even if the policy says preserve
// (verification rejects that combination, but the plan stays safe).
let plan = plan_manifest("preserve", &["bootloader"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot);
assert!(!plan.writes_kernel);
assert!(!plan.writes_userspace);
}
#[test]
fn flash_plan_tier3_from_include_policy_alone() {
let plan = plan_manifest("include", &["rootfs"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot);
assert!(!plan.writes_kernel);
assert!(plan.writes_userspace);
}
#[test]
fn flash_plan_tier1_rootfs_only() {
let plan = plan_manifest("preserve", &["rootfs"]).flash_plan();
assert_eq!(plan.tier, 1);
assert!(plan.writes_userspace);
assert!(!plan.writes_kernel);
assert!(!plan.writes_uboot);
}
#[test]
fn flash_plan_boot_role_counts_as_kernel() {
let plan = plan_manifest("preserve", &["boot"]).flash_plan();
assert_eq!(plan.tier, 2);
assert!(plan.writes_kernel);
assert!(!plan.writes_userspace);
assert!(!plan.writes_uboot);
// The shared cv1835 fixture is a single "boot" FIT under preserve.
let fixture: AfwManifest = serde_json::from_value(manifest(&[0_u8; 4])).unwrap();
assert_eq!(fixture.flash_plan().tier, 2);
}
#[test]
fn flash_plan_component_only_is_tier1_with_no_regions() {
let plan = plan_manifest("preserve", &["component"]).flash_plan();
assert_eq!(plan.tier, 1);
assert!(!plan.writes_uboot);
assert!(!plan.writes_kernel);
assert!(!plan.writes_userspace);
}
#[test]
fn flash_plan_empty_images_preserve_is_tier1() {
let plan = plan_manifest("preserve", &[]).flash_plan();
assert_eq!(plan.tier, 1);
assert!(!plan.writes_uboot && !plan.writes_kernel && !plan.writes_userspace);
}
#[test]
fn flash_plan_tier3_dominates_kernel() {
let plan = plan_manifest("include", &["bootloader", "kernel"]).flash_plan();
assert_eq!(plan.tier, 3);
assert!(plan.writes_uboot && plan.writes_kernel);
}
#[test]
fn refuses_a_hash_mismatch() {
let p1 = p1_image(P1);
+126 -2
View File
@@ -60,6 +60,14 @@ impl ReleaseSource {
/// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token
/// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`.
pub fn alkane_os() -> Self {
Self::for_repo("blueflare", "alkane-os")
}
/// A release source for an arbitrary Gitea `owner`/`repo`. The base URL
/// (`ALKANE_RELEASE_BASE`, else the self-hosted Gitea) and the token
/// (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`, else the build-time embedded
/// token) are resolved exactly as for `alkane_os`.
pub fn for_repo(owner: &str, repo: &str) -> Self {
let base_url = std::env::var("ALKANE_RELEASE_BASE")
.ok()
.filter(|s| !s.is_empty())
@@ -71,8 +79,8 @@ impl ReleaseSource {
.or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty()));
Self {
base_url,
owner: "blueflare".to_string(),
repo: "alkane-os".to_string(),
owner: owner.to_string(),
repo: repo.to_string(),
token,
}
}
@@ -223,6 +231,18 @@ pub fn fetch_latest_afw(
Ok(dest)
}
/// Board tokens recognised in `.afw` asset names (the `-<board>-` filename
/// segment). Used by `ReleaseInfo::compatible_boards`.
pub const KNOWN_BOARDS: &[&str] = &[
"zynq-7010",
"am335x",
"cv1835",
"a113d",
"allwinner-h3",
"allwinner-h6",
"allwinner-h616",
];
/// One `.afw` asset in a release.
#[derive(Debug, Clone)]
pub struct AfwAsset {
@@ -249,6 +269,30 @@ impl ReleaseInfo {
let needle = format!("-{board}-");
self.afw_assets.iter().find(|a| a.name.contains(&needle))
}
/// The distinct board tokens (from `KNOWN_BOARDS`) this release carries an
/// `.afw` for, detected from the asset filenames (`-<board>-` segment, e.g.
/// `alkane-os-0.1.2-zynq-7010-armv7.afw` -> `zynq-7010`). Ordered by first
/// appearance across the assets; a release with no recognised board yields an
/// empty list.
pub fn compatible_boards(&self) -> Vec<String> {
let mut boards: Vec<String> = Vec::new();
for asset in &self.afw_assets {
for board in KNOWN_BOARDS {
let needle = format!("-{board}-");
if asset.name.contains(&needle) && !boards.iter().any(|b| b == board) {
boards.push((*board).to_string());
}
}
}
boards
}
/// Whether this release has an `.afw` for `board` (same match as
/// `asset_for_board`).
pub fn is_compatible_with(&self, board: &str) -> bool {
self.asset_for_board(board).is_some()
}
}
/// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only
@@ -401,4 +445,84 @@ mod tests {
);
assert!(parsed[1].asset_for_board("zynq-7010").is_none());
}
#[test]
fn for_repo_builds_the_api_url_for_a_custom_repo() {
std::env::remove_var("ALKANE_RELEASE_BASE");
let src = ReleaseSource::for_repo("someorg", "some-firmware");
assert_eq!(src.owner, "someorg");
assert_eq!(src.repo, "some-firmware");
assert_eq!(
src.api_list(),
"https://gitea.bluefla.re/api/v1/repos/someorg/some-firmware/releases?limit=50"
);
// alkane_os() is for_repo("blueflare", "alkane-os").
let os = ReleaseSource::alkane_os();
assert_eq!(
(os.owner.as_str(), os.repo.as_str()),
("blueflare", "alkane-os")
);
}
fn release_with(names: &[&str]) -> ReleaseInfo {
ReleaseInfo {
tag: "v0.1.2".into(),
name: String::new(),
prerelease: false,
draft: false,
published_at: String::new(),
afw_assets: names
.iter()
.map(|n| AfwAsset {
name: (*n).to_string(),
url: format!("https://example.invalid/{n}"),
})
.collect(),
}
}
#[test]
fn compatible_boards_extracts_board_tokens_from_asset_names() {
let single = release_with(&["alkane-os-0.1.2-zynq-7010-armv7.afw"]);
assert_eq!(single.compatible_boards(), vec!["zynq-7010"]);
// Multi-board release: distinct boards in first-appearance order,
// duplicates (a second arch build of one board) collapse.
let multi = release_with(&[
"alkane-os-0.1.2-am335x-armv7.afw",
"alkane-os-0.1.2-zynq-7010-armv7.afw",
"alkane-os-0.1.2-allwinner-h616-aarch64.afw",
"alkane-os-0.1.2-am335x-arm.afw",
"alkane-os-0.1.2-cv1835-riscv64.afw",
]);
assert_eq!(
multi.compatible_boards(),
vec!["am335x", "zynq-7010", "allwinner-h616", "cv1835"]
);
// allwinner-h6 must not match an allwinner-h616 asset (and vice versa).
let h616 = release_with(&["alkane-os-0.1.2-allwinner-h616-aarch64.afw"]);
assert_eq!(h616.compatible_boards(), vec!["allwinner-h616"]);
let h6 = release_with(&["alkane-os-0.1.2-allwinner-h6-aarch64.afw"]);
assert_eq!(h6.compatible_boards(), vec!["allwinner-h6"]);
// No .afw assets, or an unrecognised board, yields nothing.
assert!(release_with(&[]).compatible_boards().is_empty());
assert!(release_with(&["alkane-os-0.1.2-mystery-board-arm.afw"])
.compatible_boards()
.is_empty());
}
#[test]
fn is_compatible_with_matches_asset_for_board() {
let rel = release_with(&[
"alkane-os-0.1.2-zynq-7010-armv7.afw",
"alkane-os-0.1.2-a113d-aarch64.afw",
]);
assert!(rel.is_compatible_with("zynq-7010"));
assert!(rel.is_compatible_with("a113d"));
assert!(!rel.is_compatible_with("am335x"));
assert!(!rel.is_compatible_with("allwinner-h6"));
assert!(!release_with(&[]).is_compatible_with("zynq-7010"));
}
}
+130
View File
@@ -12,6 +12,11 @@
//! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and
//! verification around the method. The method is plain Rust and must be
//! network-only.
//!
//! A from-stock install also leaves a complete genuine-stock backup on the
//! board: the stock device tree, kernel and ramdisk, in the reserved NAND
//! region after the alkane MAC area. The two on-board backup calls below check
//! and restore that copy over the network, with no vendor firmware file.
use alkane_artifacts::afw::VerifiedAfw;
use std::path::{Path, PathBuf};
@@ -157,6 +162,26 @@ pub trait StockMethod {
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError>;
/// Report, over the network only, whether the board holds a complete
/// on-board stock backup that can be restored without a vendor firmware
/// file. False means absent or incomplete; it is not an error.
fn onboard_stock_backup_present(
&self,
host: &str,
password: Option<&str>,
) -> Result<bool, StockError>;
/// Return an alkane board to genuine stock, over the network only, using
/// the on-board stock backup. The backup must be present and complete; call
/// `onboard_stock_backup_present` first. `timeout` bounds the wait for the
/// restored board to answer as stock after the reboot.
fn restore_from_onboard_backup(
&self,
host: &str,
password: Option<&str>,
timeout: std::time::Duration,
) -> Result<(), StockError>;
}
/// The compiled-in method implementation.
@@ -164,6 +189,26 @@ pub fn method() -> &'static dyn StockMethod {
crate::stock_method::method()
}
/// Report, over the network only, whether the board holds a complete on-board
/// stock backup that can be restored without a vendor firmware file.
pub fn onboard_stock_backup_present(
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
method().onboard_stock_backup_present(host, password)
}
/// Return an alkane board to genuine stock (network-only) using its on-board
/// stock backup, via the compiled-in method. The backup must be present and
/// complete; check it first with [`onboard_stock_backup_present`].
pub fn restore_from_onboard_backup(
host: &str,
password: Option<&str>,
timeout: std::time::Duration,
) -> Result<(), StockError> {
method().restore_from_onboard_backup(host, password, timeout)
}
/// Install alkane onto a board on stock (network-only), via the compiled-in method.
pub fn install_from_stock(
host: &str,
@@ -215,8 +260,93 @@ mod tests {
// The interface is exercised against whatever `stock_method` provides. We
// only assert the toolkit wires a method object in; its behaviour is the
// method module's own tests.
#[test]
fn public_signatures_are_wired() {
let _: fn(&str, Option<&str>) -> Result<bool, StockError> = onboard_stock_backup_present;
let _: fn(&str, Option<&str>, std::time::Duration) -> Result<(), StockError> =
restore_from_onboard_backup;
}
struct FakeMethod {
present: bool,
}
impl StockMethod for FakeMethod {
fn install_from_stock(
&self,
_: &str,
_: &Path,
_: &VerifiedAfw,
_: Option<&str>,
) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn restore_to_stock(
&self,
_: &str,
_: &RestoreImages,
_: Option<&str>,
) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn update_in_place(
&self,
_: &str,
_: &VerifiedAfw,
_: Option<&str>,
_: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
Err(StockError::NotImplemented)
}
fn onboard_stock_backup_present(
&self,
_: &str,
_: Option<&str>,
) -> Result<bool, StockError> {
Ok(self.present)
}
fn restore_from_onboard_backup(
&self,
_: &str,
_: Option<&str>,
_: std::time::Duration,
) -> Result<(), StockError> {
if self.present {
Ok(())
} else {
Err(StockError::Method(
"no complete on-board stock backup".into(),
))
}
}
}
#[test]
fn a_method_is_compiled_in() {
let _m: &dyn StockMethod = method();
}
#[test]
fn onboard_backup_methods_report_present_or_absent() {
let present = FakeMethod { present: true };
assert!(present
.onboard_stock_backup_present("192.0.2.10", Some("secret"))
.unwrap());
assert!(present
.restore_from_onboard_backup("192.0.2.10", Some("secret"), std::time::Duration::ZERO)
.is_ok());
let absent = FakeMethod { present: false };
assert!(!absent
.onboard_stock_backup_present("192.0.2.10", None)
.unwrap());
assert!(matches!(
absent.restore_from_onboard_backup("192.0.2.10", None, std::time::Duration::ZERO),
Err(StockError::Method(_))
));
}
}
+696 -12
View File
@@ -40,6 +40,14 @@ const DTB_SLOT: u64 = 0x20000;
const KERNEL_SLOT: u64 = 0x800000;
const ROOTFS_SLOT: u64 = 0x2000000;
// A complete genuine-stock backup kept on the board by a from-stock install.
// The area sits in the vendor `reserve` partition after the alkane MAC region,
// clear of the stock `configs` UBI, the alkane boot slots and BOOT.bin.
const STOCK_BACKUP_BASE: u64 = 0x5200000;
const STOCK_BACKUP_END: u64 = 0x6000000;
const STOCK_BACKUP_HEADER: u64 = 0x20000;
const STOCK_BACKUP_MAGIC: &str = "ALKANE-STOCK-BACKUP 1";
// ---------------------------------------------------------------- stock assets
//
// The stock payloads are not compiled into the toolkit. They are fetched over
@@ -1479,12 +1487,7 @@ fn map_covers_boot_regions(map: &[Mtd]) -> bool {
.all(|absolute| locate_mtd(map, *absolute).is_some())
}
fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) {
return Ok(map);
}
fn apply_mtd_patch(host: &str, password: Option<&str>) -> Result<(), StockError> {
let mtd_patch = stock_asset(&ASSET_MTD_PATCH)?;
ssh_push(
host,
@@ -1510,6 +1513,15 @@ fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockErro
"target storage layout unsupported".into(),
));
}
Ok(())
}
fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) {
return Ok(map);
}
apply_mtd_patch(host, password)?;
let map = read_mtd_map(host, password)?;
if !map_covers_boot_regions(&map) {
return Err(StockError::Method(
@@ -1519,6 +1531,28 @@ fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockErro
Ok(map)
}
/// Like `get_mtd_map`, but also requires `absolute` to be reachable. The
/// per-board storage helper re-registers the boot regions; on alkane that same
/// view includes the reserve area used for the on-board stock backup.
fn get_mtd_map_for_backup(
host: &str,
password: Option<&str>,
absolute: u64,
) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) && locate_mtd(&map, absolute).is_some() {
return Ok(map);
}
apply_mtd_patch(host, password)?;
let map = read_mtd_map(host, password)?;
if !map_covers_boot_regions(&map) || locate_mtd(&map, absolute).is_none() {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(map)
}
fn locate_mtd(map: &[Mtd], absolute: u64) -> Option<(&Mtd, u64)> {
for mtd in map {
if mtd.offset <= absolute && absolute < mtd.offset + mtd.size {
@@ -1640,7 +1674,134 @@ fn stock_web_targets(
// ---------------------------------------------------------------- scripts
fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) -> String {
// Runs as root inside the from-stock web helper, before any alkane image is
// written. It leaves the genuine stock boot chain in the reserve area and
// writes the manifest last. Any failure exits through `fail`, so the stock
// board is never touched unless the backup is complete.
const STOCK_BACKUP_WEB_SCRIPT: &str = r#"
ak_base=0x5200000
ak_end=0x6000000
ak_hdr=131072
ak_blk=131072
ak_src_dtb=0x1a00000
ak_src_kernel=0x2000000
ak_src_ramdisk=0x2800000
ak_num() {
printf '%d\n' "$(( $1 ))"
}
ak_mtd_for() {
ak_abs=$(ak_num "$1") || return 1
for ak_d in /sys/class/mtd/mtd[0-9]*; do
[ -e "$ak_d/offset" ] || continue
ak_off=$(cat "$ak_d/offset" 2>/dev/null) || continue
ak_siz=$(cat "$ak_d/size" 2>/dev/null) || continue
[ -n "$ak_off" ] && [ -n "$ak_siz" ] || continue
ak_off=$(ak_num "$ak_off") || continue
ak_siz=$(ak_num "$ak_siz") || continue
if [ "$ak_abs" -ge "$ak_off" ] && [ "$ak_abs" -lt "$((ak_off + ak_siz))" ]; then
ak_name=$(basename "$ak_d")
printf '%s %s %s\n' "/dev/$ak_name" "$((ak_abs - ak_off))" "$ak_off"
return 0
fi
done
return 1
}
ak_be32() {
set -- $(od -An -tx1 -j "$2" -N4 "$1" 2>/dev/null)
[ "$#" -eq 4 ] || return 1
printf '%d\n' "$(( (0x$1 << 24) | (0x$2 << 16) | (0x$3 << 8) | 0x$4 ))"
}
ak_uimage_len() {
ak_magic=$(dd if="$1" bs=1 count=4 2>/dev/null | od -An -tx1 | tr -d ' \n')
[ "$ak_magic" = "27051956" ] || return 1
ak_total=$((64 + $(ak_be32 "$1" 12))) || return 1
[ "$ak_total" -gt 64 ] || return 1
ak_bytes=$(( ((ak_total + ak_blk - 1) / ak_blk) * ak_blk ))
[ "$((ak_bytes <= $2))" -eq 1 ] || return 1
printf '%d\n' "$ak_bytes"
}
set -- $(ak_mtd_for "$ak_base")
[ "$#" -eq 3 ] || fail bk-map
ak_dev=$1
ak_bakrel=$2
ak_devoff=$3
set -- $(ak_mtd_for "$ak_src_dtb")
[ "$#" -eq 3 ] || fail bk-src-dtb
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-dtb
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-dtb 2>/dev/null || fail bk-read-dtb
[ "$(wc -c < /tmp/.ak-bk-dtb 2>/dev/null)" = "$ak_hdr" ] || fail bk-short-dtb
ak_dtb_md5=$(md5sum /tmp/.ak-bk-dtb | cut -d' ' -f1) || fail bk-md5-dtb
ak_dtb_size=$ak_hdr
set -- $(ak_mtd_for "$ak_src_kernel")
[ "$#" -eq 3 ] || fail bk-src-kernel
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-kernel
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-kernel-head 2>/dev/null || fail bk-read-kernel
ak_kernel_size=$(ak_uimage_len /tmp/.ak-bk-kernel-head 0x800000) || fail bk-kernel
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_kernel_size / ak_blk))" of=/tmp/.ak-bk-kernel 2>/dev/null || fail bk-read-kernel
[ "$(wc -c < /tmp/.ak-bk-kernel 2>/dev/null)" = "$ak_kernel_size" ] || fail bk-short-kernel
ak_kernel_md5=$(md5sum /tmp/.ak-bk-kernel | cut -d' ' -f1) || fail bk-md5-kernel
set -- $(ak_mtd_for "$ak_src_ramdisk")
[ "$#" -eq 3 ] || fail bk-src-ramdisk
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-ramdisk
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-ramdisk-head 2>/dev/null || fail bk-read-ramdisk
ak_ramdisk_size=$(ak_uimage_len /tmp/.ak-bk-ramdisk-head 0x2000000) || fail bk-ramdisk
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_ramdisk_size / ak_blk))" of=/tmp/.ak-bk-ramdisk 2>/dev/null || fail bk-read-ramdisk
[ "$(wc -c < /tmp/.ak-bk-ramdisk 2>/dev/null)" = "$ak_ramdisk_size" ] || fail bk-short-ramdisk
ak_ramdisk_md5=$(md5sum /tmp/.ak-bk-ramdisk | cut -d' ' -f1) || fail bk-md5-ramdisk
ak_dtb_bak=$((ak_base + ak_hdr))
ak_kernel_bak=$((ak_dtb_bak + ak_dtb_size))
ak_ramdisk_bak=$((ak_kernel_bak + ak_kernel_size))
ak_end_used=$((ak_ramdisk_bak + ak_ramdisk_size))
[ "$((ak_end_used <= ak_end))" -eq 1 ] || fail bk-space
set -- $(ak_mtd_for "$ak_dtb_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
set -- $(ak_mtd_for "$ak_kernel_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
set -- $(ak_mtd_for "$ak_ramdisk_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
ak_blocks=$(( (ak_end_used - ak_base) / ak_blk ))
flash_erase "$ak_dev" "$ak_bakrel" "$ak_blocks" >/dev/null 2>&1 || fail bk-erase
nandwrite -p -s "$((ak_dtb_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-dtb >/dev/null 2>&1 || fail bk-write-dtb
nandwrite -p -s "$((ak_kernel_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-kernel >/dev/null 2>&1 || fail bk-write-kernel
nandwrite -p -s "$((ak_ramdisk_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-ramdisk >/dev/null 2>&1 || fail bk-write-ramdisk
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_dtb_bak - ak_devoff) / ak_blk ))" count="$((ak_dtb_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_dtb_md5" ] || fail bk-verify-dtb
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_kernel_bak - ak_devoff) / ak_blk ))" count="$((ak_kernel_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_kernel_md5" ] || fail bk-verify-kernel
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_ramdisk_bak - ak_devoff) / ak_blk ))" count="$((ak_ramdisk_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_ramdisk_md5" ] || fail bk-verify-ramdisk
{
printf '%s\n' "ALKANE-STOCK-BACKUP 1"
printf 'dtb 0x1a00000 0x%x 0x%x %s\n' "$ak_dtb_bak" "$ak_dtb_size" "$ak_dtb_md5"
printf 'kernel 0x2000000 0x%x 0x%x %s\n' "$ak_kernel_bak" "$ak_kernel_size" "$ak_kernel_md5"
printf 'ramdisk 0x2800000 0x%x 0x%x %s\n' "$ak_ramdisk_bak" "$ak_ramdisk_size" "$ak_ramdisk_md5"
printf '%s\n' "end"
} > /tmp/.ak-bk-header || fail bk-header
nandwrite -p -s "$ak_bakrel" "$ak_dev" /tmp/.ak-bk-header >/dev/null 2>&1 || fail bk-write-header
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$((ak_bakrel / ak_blk))" count=1 2>/dev/null | head -c 19)
[ "$ak_v" = "ALKANE-STOCK-BACKUP" ] || fail bk-verify-header
rm -f /tmp/.ak-bk-dtb /tmp/.ak-bk-kernel /tmp/.ak-bk-kernel-head \
/tmp/.ak-bk-ramdisk /tmp/.ak-bk-ramdisk-head /tmp/.ak-bk-header
"#;
fn flash_script(
targets: &[FlashTarget],
token: &str,
web_cgi: Option<&str>,
with_stock_backup: bool,
) -> String {
let mut script = String::new();
script.push_str("#!/bin/sh\n");
script.push_str("set -u\n");
@@ -1649,6 +1810,10 @@ fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) ->
}
script.push_str("fail(){ echo \"@@FAIL@@ $*\"; sync; exit 1; }\n");
if with_stock_backup {
script.push_str(STOCK_BACKUP_WEB_SCRIPT);
}
for target in targets {
let path = if web_cgi.is_some() {
format!("/tmp/.ak-{token}-{}", target.file)
@@ -1757,6 +1922,452 @@ fn build_web_body(
(body, boundary)
}
// ---------------------------------------------------------------- on-board stock backup
//
// A from-stock install copies the genuine stock device tree, kernel and ramdisk
// off their slots into the vendor `reserve` area before anything is overwritten.
// The copy is block-padded, carries a small text manifest with a digest for each
// member, and is written manifest-last so an interrupted install never leaves a
// backup that passes the presence check. Ownership/format stay inside this
// module; the public interface only reports complete/absent and restores.
#[derive(Clone, Debug)]
struct StockBackupEntry {
name: &'static str,
target_abs: u64,
backup_abs: u64,
size: u64,
md5: String,
}
#[derive(Clone, Debug)]
struct StockBackup {
entries: Vec<StockBackupEntry>,
}
fn parse_hex_u64(value: &str) -> Option<u64> {
let digits = value
.strip_prefix("0x")
.or_else(|| value.strip_prefix("0X"))?;
u64::from_str_radix(digits, 16).ok()
}
fn stock_entry_spec(name: &str) -> Option<(&'static str, u64, u64)> {
match name {
"dtb" => Some(("dtb", ABS_DTB, DTB_SLOT)),
"kernel" => Some(("kernel", ABS_KERNEL, KERNEL_SLOT)),
"ramdisk" => Some(("ramdisk", ABS_ROOTFS, ROOTFS_SLOT)),
_ => None,
}
}
fn parse_stock_backup(header: &[u8]) -> Option<StockBackup> {
let text = String::from_utf8_lossy(header);
let mut lines = text.lines();
let first = lines.next()?.trim_matches('\0').trim();
if first != STOCK_BACKUP_MAGIC {
return None;
}
let mut entries = Vec::new();
let mut ended = false;
for raw in lines {
let line = raw.trim_matches('\0').trim();
if line.is_empty() {
continue;
}
if line == "end" {
ended = true;
break;
}
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() != 5 {
return None;
}
let (name, target_abs, slot) = stock_entry_spec(fields[0])?;
let declared_target = parse_hex_u64(fields[1])?;
let backup_abs = parse_hex_u64(fields[2])?;
let size = parse_hex_u64(fields[3])?;
let md5 = fields[4].to_ascii_lowercase();
if declared_target != target_abs
|| md5.len() != 32
|| !md5.chars().all(|c| c.is_ascii_hexdigit())
{
return None;
}
if size == 0 || size % BLK != 0 || size > slot || (name == "dtb" && size != DTB_SLOT) {
return None;
}
let backup_end = backup_abs.checked_add(size)?;
if backup_abs % BLK != 0
|| backup_abs < STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER
|| backup_end > STOCK_BACKUP_END
{
return None;
}
if entries
.iter()
.any(|entry: &StockBackupEntry| entry.name == name)
{
return None;
}
entries.push(StockBackupEntry {
name,
target_abs,
backup_abs,
size,
md5,
});
}
if !ended || entries.len() != 3 {
return None;
}
let mut spans: Vec<(u64, u64)> = entries
.iter()
.map(|entry| (entry.backup_abs, entry.backup_abs + entry.size))
.collect();
spans.sort_unstable();
for pair in spans.windows(2) {
if pair[0].1 > pair[1].0 {
return None;
}
}
Some(StockBackup { entries })
}
fn render_stock_backup(entries: &[StockBackupEntry]) -> Vec<u8> {
let mut text = String::new();
text.push_str(STOCK_BACKUP_MAGIC);
text.push('\n');
for entry in entries {
text.push_str(&format!(
"{} 0x{:x} 0x{:x} 0x{:x} {}\n",
entry.name, entry.target_abs, entry.backup_abs, entry.size, entry.md5
));
}
text.push_str("end\n");
text.into_bytes()
}
fn read_mtd_span(
host: &str,
password: Option<&str>,
map: &[Mtd],
absolute: u64,
size: u64,
label: &str,
) -> Result<Vec<u8>, StockError> {
if size == 0 || size % BLK != 0 {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let (mtd, rel) = locate_mtd(map, absolute)
.ok_or_else(|| StockError::Method("target storage layout unsupported".into()))?;
if rel.checked_add(size).map_or(true, |end| end > mtd.size) {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
mtd.device,
BLK,
rel / BLK,
size / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?;
if !result.ok() {
return Err(StockError::Method(format!(
"could not read the on-board stock {label} backup"
)));
}
if result.stdout.len() as u64 != size {
return Err(StockError::Method(format!(
"the on-board stock {label} backup is short"
)));
}
Ok(result.stdout)
}
fn stock_uimage_span(
host: &str,
password: Option<&str>,
map: &[Mtd],
absolute: u64,
slot: u64,
label: &str,
) -> Result<Vec<u8>, StockError> {
let first = read_mtd_span(host, password, map, absolute, BLK, label)?;
if first.len() < 64 || first[..4] != [0x27, 0x05, 0x19, 0x56] {
return Err(StockError::Method(format!(
"the on-board stock {label} slot does not hold a stock image"
)));
}
let payload = u32::from_be_bytes([first[12], first[13], first[14], first[15]]) as u64;
let total = 64u64
.checked_add(payload)
.ok_or_else(|| StockError::Method(format!("the on-board stock {label} slot is invalid")))?;
let bytes = total.div_ceil(BLK) * BLK;
if total <= 64 || bytes > slot {
return Err(StockError::Method(format!(
"the on-board stock {label} slot does not hold a stock image"
)));
}
if bytes <= BLK {
return Ok(first[..bytes as usize].to_vec());
}
let rest = read_mtd_span(host, password, map, absolute + BLK, bytes - BLK, label)?;
let mut out = first;
out.extend_from_slice(&rest);
out.truncate(bytes as usize);
Ok(out)
}
fn read_validated_onboard_stock_backup(
host: &str,
password: Option<&str>,
map: &[Mtd],
) -> Result<Option<StockBackup>, StockError> {
let Some((mtd, rel)) = locate_mtd(map, STOCK_BACKUP_BASE) else {
return Ok(None);
};
if rel
.checked_add(STOCK_BACKUP_HEADER)
.map_or(true, |end| end > mtd.size)
{
return Ok(None);
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
mtd.device,
BLK,
rel / BLK,
STOCK_BACKUP_HEADER / BLK
);
let header = ssh_exec(host, password, &remote, Duration::from_secs(120))?;
if !header.ok() || header.stdout.len() as u64 != STOCK_BACKUP_HEADER {
return Ok(None);
}
let Some(backup) = parse_stock_backup(&header.stdout) else {
return Ok(None);
};
for entry in &backup.entries {
let Some((entry_mtd, entry_rel)) = locate_mtd(map, entry.backup_abs) else {
return Ok(None);
};
if entry_rel
.checked_add(entry.size)
.map_or(true, |end| end > entry_mtd.size)
{
return Ok(None);
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null | md5sum | cut -d' ' -f1",
entry_mtd.device,
BLK,
entry_rel / BLK,
entry.size / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(300))?;
if !result.ok() {
return Ok(None);
}
if !text(&result.stdout).trim().eq_ignore_ascii_case(&entry.md5) {
return Ok(None);
}
}
Ok(Some(backup))
}
fn create_onboard_stock_backup(
host: &str,
password: Option<&str>,
map: &[Mtd],
) -> Result<(), StockError> {
let dtb = read_mtd_span(host, password, map, ABS_DTB, DTB_SLOT, "device tree")?;
if dtb.len() < 8 || dtb[..4] != [0xd0, 0x0d, 0xfe, 0xed] {
return Err(StockError::Method(
"the stock device tree slot is not usable for a backup".into(),
));
}
let kernel = stock_uimage_span(host, password, map, ABS_KERNEL, KERNEL_SLOT, "kernel")?;
let ramdisk = stock_uimage_span(host, password, map, ABS_ROOTFS, ROOTFS_SLOT, "ramdisk")?;
let mut prepared: Vec<(&'static str, u64, Vec<u8>)> = vec![
("dtb", ABS_DTB, dtb),
("kernel", ABS_KERNEL, kernel),
("ramdisk", ABS_ROOTFS, ramdisk),
];
let mut entries = Vec::with_capacity(prepared.len());
let mut next = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER;
for (name, target_abs, data) in &prepared {
let size = data.len() as u64;
if next
.checked_add(size)
.map_or(true, |end| end > STOCK_BACKUP_END)
{
return Err(StockError::Method(
"the on-board stock backup area is too small".into(),
));
}
entries.push(StockBackupEntry {
name,
target_abs: *target_abs,
backup_abs: next,
size,
md5: md5_hex(data),
});
next += size;
}
let header = render_stock_backup(&entries);
let mut write: Vec<(&'static str, &'static str, u64, u64, Cow<'static, [u8]>)> = Vec::new();
write.push((
"backup-header-clear",
"stock-backup-empty.bin",
STOCK_BACKUP_BASE,
STOCK_BACKUP_HEADER,
Cow::Owned(vec![0u8; STOCK_BACKUP_HEADER as usize]),
));
for (entry, (_, _, data)) in entries.iter().zip(prepared.drain(..)) {
write.push((
match entry.name {
"dtb" => "backup-dtb",
"kernel" => "backup-kernel",
_ => "backup-ramdisk",
},
match entry.name {
"dtb" => "stock-backup.dtb",
"kernel" => "stock-backup-kernel.uimg",
_ => "stock-backup-ramdisk.uimg",
},
entry.backup_abs,
entry.size,
Cow::Owned(data),
));
}
write.push((
"backup-header",
"stock-backup.txt",
STOCK_BACKUP_BASE,
STOCK_BACKUP_HEADER,
Cow::Owned(header),
));
let targets = targets_from_map(map, write)?;
flash_via_ssh(host, password, &targets)?;
match read_validated_onboard_stock_backup(host, password, map)? {
Some(_) => Ok(()),
None => Err(StockError::Method(
"the on-board stock backup did not verify after it was written".into(),
)),
}
}
fn restore_from_onboard_backup_impl(
host: &str,
password: Option<&str>,
timeout: Duration,
) -> Result<(), StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(());
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let state = board_state(host, password)?;
if state == "stock" {
return Ok(());
}
let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?;
let Some(backup) = read_validated_onboard_stock_backup(host, password, &map)? else {
return Err(StockError::Method(
"no complete on-board stock backup".into(),
));
};
let name = |wanted: &str| -> Result<&StockBackupEntry, StockError> {
backup
.entries
.iter()
.find(|entry| entry.name == wanted)
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))
};
let dtb_entry = name("dtb")?;
let kernel_entry = name("kernel")?;
let ramdisk_entry = name("ramdisk")?;
let dtb = read_mtd_span(
host,
password,
&map,
dtb_entry.backup_abs,
dtb_entry.size,
"device tree",
)?;
let kernel = read_mtd_span(
host,
password,
&map,
kernel_entry.backup_abs,
kernel_entry.size,
"kernel",
)?;
let ramdisk = read_mtd_span(
host,
password,
&map,
ramdisk_entry.backup_abs,
ramdisk_entry.size,
"ramdisk",
)?;
let write = vec![
(
"ramdisk",
"stock-rootfs.uimg",
ABS_ROOTFS,
ROOTFS_SLOT,
Cow::Owned(ramdisk),
),
("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"stock-kernel.uimg",
ABS_KERNEL,
KERNEL_SLOT,
Cow::Owned(kernel),
),
];
let targets = targets_from_map(&map, write)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
let _ = wait_stock(host, timeout);
Ok(())
}
fn onboard_stock_backup_present_impl(
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(false);
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?;
Ok(read_validated_onboard_stock_backup(host, password, &map)?.is_some())
}
// ---------------------------------------------------------------- install / restore
fn install_via_web(
@@ -1792,7 +2403,7 @@ fn install_via_web(
let targets = stock_web_targets(kernel, dtb, rootfs)?;
let token = random_token();
let cgi = format!("zz{token}.cgi");
let script = flash_script(&targets, &token, Some(&cgi));
let script = flash_script(&targets, &token, Some(&cgi), true);
let (body, boundary) = build_web_body(&targets, &token, &cgi, &script);
let body_path = dir.join("upload.body");
write_private(&body_path, &body)?;
@@ -1846,8 +2457,16 @@ fn install_via_ssh(
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
backup_stock: bool,
) -> Result<(), StockError> {
let map = get_mtd_map(host, password)?;
let map = if backup_stock {
get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?
} else {
get_mtd_map(host, password)?
};
if backup_stock {
create_onboard_stock_backup(host, password, &map)?;
}
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
@@ -1877,7 +2496,7 @@ fn flash_via_ssh(
let timeout = Duration::from_secs(300);
ssh_push(host, password, &remote, target.data.as_ref(), timeout)?;
}
let script = flash_script(targets, "", None);
let script = flash_script(targets, "", None, false);
let remote_script = "/tmp/rs/go.sh";
ssh_push(
host,
@@ -2227,7 +2846,7 @@ impl StockMethod for Method {
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
return install_via_ssh(host, password, kernel, dtb, rootfs);
return install_via_ssh(host, password, kernel, dtb, rootfs, false);
}
// A board on genuine stock is reached through its own web gate.
@@ -2236,7 +2855,8 @@ impl StockMethod for Method {
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
return install_via_ssh(host, password, kernel, dtb, rootfs);
let stock = board_state(host, password)? == "stock";
return install_via_ssh(host, password, kernel, dtb, rootfs, stock);
}
return Err(StockError::Network("target unreachable".into()));
}
@@ -2311,6 +2931,23 @@ impl StockMethod for Method {
) -> Result<InPlaceOutcome, StockError> {
update_in_place_impl(host, afw, password, options)
}
fn onboard_stock_backup_present(
&self,
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
onboard_stock_backup_present_impl(host, password)
}
fn restore_from_onboard_backup(
&self,
host: &str,
password: Option<&str>,
timeout: Duration,
) -> Result<(), StockError> {
restore_from_onboard_backup_impl(host, password, timeout)
}
}
static METHOD: Method = Method;
@@ -2599,4 +3236,51 @@ mod tests {
assert!(absolute >= BOOTBIN_PRESERVE);
}
}
#[test]
fn stock_backup_manifest_round_trips_and_rejects_incomplete() {
let base = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER;
let entries = vec![
StockBackupEntry {
name: "dtb",
target_abs: ABS_DTB,
backup_abs: base,
size: DTB_SLOT,
md5: "0".repeat(32),
},
StockBackupEntry {
name: "kernel",
target_abs: ABS_KERNEL,
backup_abs: base + DTB_SLOT,
size: BLK,
md5: "1".repeat(32),
},
StockBackupEntry {
name: "ramdisk",
target_abs: ABS_ROOTFS,
backup_abs: base + DTB_SLOT + BLK,
size: BLK,
md5: "2".repeat(32),
},
];
let header = render_stock_backup(&entries);
let mut padded = header.clone();
padded.resize(STOCK_BACKUP_HEADER as usize, 0xff);
let parsed = parse_stock_backup(&padded).expect("manifest parses");
assert_eq!(parsed.entries.len(), 3);
assert_eq!(parsed.entries[1].size, BLK);
let text = String::from_utf8(header).unwrap();
let missing = text.replace(
&format!(
"kernel 0x{:x} 0x{:x} 0x{:x} {}\n",
ABS_KERNEL,
base + DTB_SLOT,
BLK,
"1".repeat(32)
),
"",
);
assert!(parse_stock_backup(missing.as_bytes()).is_none());
}
}
+15
View File
@@ -106,6 +106,9 @@ pub fn clear_credentials() -> std::io::Result<()> {
/// duplicated here; a firmware absent from this table defaults to blank.
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
&[
// Alkane OS ships with this control-board login, so restore-to-stock on
// an alkane board authenticates with no operator setup (issue #51).
("Alkane", "root", "alkane"),
("AntMiner Stock", "root", "root"),
("WhatsMiner Stock", "admin", "admin"),
("Braiins", "root", "root"),
@@ -134,6 +137,18 @@ pub fn firmware_default_for(name: &str) -> (String, String) {
.unwrap_or_default()
}
/// The login to use for a board running `firmware`: the operator's saved
/// per-firmware override if any, else the shipped default. This is how install
/// (a stock target) and restore (an alkane target) each pick the right login
/// automatically, without a password field in the dialog (issues #46, #51).
pub fn cred_for(firmware: &str) -> (String, String) {
load_firmware_credentials()
.get(firmware)
.cloned()
.filter(|(_, p)| !p.is_empty())
.unwrap_or_else(|| firmware_default_for(firmware))
}
/// Load the operator's per-firmware credential overrides, keyed by firmware
/// Display name. Malformed lines are skipped.
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
+58 -3
View File
@@ -692,9 +692,18 @@ impl MinerRow {
/// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so
/// a missing wattage reading is treated as unknown, never a false "down".
pub fn power_health(&self) -> CompHealth {
// A miner drawing power / spinning its PSU fan / actively mining has a live
// PSU regardless of any warning flag.
let delivering = self.power_w > 0.0 || self.psu_fan_rpm > 0.0 || self.is_mining;
// A live PSU shows real evidence: measured draw, a spinning PSU fan, or
// reported PSU output. A stock control board can assert a cgminer "mining"
// status with no PSU and no hashboards attached (issue #39: a bare S17
// control board showed a green PSU), so is_mining counts only when the
// miner is actually hashing (hashrate, or at least one healthy board).
let actually_hashing =
self.hashrate_ths > 0.0 || self.board_status.contains(&BoardHealth::Ok);
let delivering = self.power_w > 0.0
|| self.psu_fan_rpm > 0.0
|| self.psu_out_voltage_v.is_some()
|| self.psu_out_current_a.is_some()
|| (self.is_mining && actually_hashing);
// A reported PSU fault while the miner is actually mining is a warning, not
// a failure -- yellow, not red (round 18 #2: some WhatsMiners flag a PSU
// error while running fine). A fault on a miner that is not mining is a real
@@ -2476,6 +2485,52 @@ mod tests {
);
}
#[test]
fn stock_board_with_nothing_attached_shows_grey_psu() {
// Issue #39: a stock S17 control board with no PSU and no hashboards
// attached asserts a cgminer "mining" status (is_mining = true) while
// reporting zero watts, no PSU fan, and no PSU output. That is not
// evidence of a live PSU, so the bolt must read grey (Unreachable).
let bare = MinerRow {
is_mining: true,
power_w: 0.0,
psu_fan_rpm: 0.0,
hashrate_ths: 0.0,
board_status: vec![BoardHealth::Missing, BoardHealth::Missing],
..Default::default()
};
assert_eq!(bare.power_health(), CompHealth::Unreachable);
// A genuinely-running miner still greens: is_mining with real hashing is
// evidence enough even when the firmware reports no watts.
let hashing = MinerRow {
is_mining: true,
power_w: 0.0,
psu_fan_rpm: 0.0,
hashrate_ths: 90.0,
board_status: vec![BoardHealth::Ok, BoardHealth::Ok],
..Default::default()
};
assert_eq!(hashing.power_health(), CompHealth::Ok);
// Measured draw alone is always enough.
let drawing = MinerRow {
is_mining: false,
power_w: 19.0,
..Default::default()
};
assert_eq!(drawing.power_health(), CompHealth::Ok);
// Reported PSU output alone is enough even with zero measured watts.
let psu_out = MinerRow {
is_mining: false,
power_w: 0.0,
psu_out_voltage_v: Some(12.0),
..Default::default()
};
assert_eq!(psu_out.power_health(), CompHealth::Ok);
}
#[test]
fn warning_fault_degrades_board_to_yellow_not_red() {
// Round 21 #1: a board still mining near full hashrate with some failed/
+57 -12
View File
@@ -674,6 +674,62 @@ fn messages_to_faults(
.collect()
}
/// A hashboard's health dot from its reported activity. `active` is the firmware's
/// active flag; `working_chips` its working-chip count. Green needs positive
/// evidence (active, or a nonzero chip count); a board with neither flag nor count
/// reads grey ("not detected") rather than green (issue #39: an S17 control board
/// with no hashboards attached showed its boards green). A board that is present
/// but idle or has zero working chips reads as a fault (red).
fn board_health(
active: Option<bool>,
working_chips: Option<u16>,
miner_active: bool,
) -> crate::model::BoardHealth {
use crate::model::BoardHealth;
match (active, working_chips) {
(Some(true), _) => BoardHealth::Ok,
(Some(false), _) => BoardHealth::Fault,
(None, Some(c)) if c > 0 => BoardHealth::Ok,
(None, Some(_)) => BoardHealth::Fault,
// No per-board evidence. If the miner shows overall activity (hashing),
// the board is clearly present and working -> green; only an idle miner
// with no board telemetry reads grey (issue #39: bare S17; review #3: do
// not grey a genuinely-mining miner whose backend omits per-board fields).
(None, None) => {
if miner_active {
BoardHealth::Ok
} else {
BoardHealth::Missing
}
}
}
}
#[cfg(test)]
mod board_health_tests {
use super::board_health;
use crate::model::BoardHealth;
#[test]
fn no_activity_evidence_reads_grey_not_green() {
// Issue #39: the firmware lists a board but reports no active flag and no
// working-chip count -> not detected (grey), not green.
// Idle miner, no per-board evidence -> not detected (grey).
assert_eq!(board_health(None, None, false), BoardHealth::Missing);
// Mining miner, no per-board evidence -> still green (review #3).
assert_eq!(board_health(None, None, true), BoardHealth::Ok);
// Positive evidence still greens regardless of miner activity.
assert_eq!(board_health(Some(true), None, false), BoardHealth::Ok);
assert_eq!(board_health(None, Some(63), false), BoardHealth::Ok);
// Present but idle / zero working chips -> fault (red).
assert_eq!(
board_health(Some(false), Some(63), false),
BoardHealth::Fault
);
assert_eq!(board_health(None, Some(0), false), BoardHealth::Fault);
}
}
#[cfg(test)]
mod board_index_tests {
use super::board_index_from_text;
@@ -1189,18 +1245,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
let mut board_status: Vec<crate::model::BoardHealth> = data
.hashboards
.iter()
.map(|b| {
let ok = match (b.active, b.working_chips) {
(Some(a), _) => a,
(None, Some(c)) => c > 0,
(None, None) => true,
};
if ok {
crate::model::BoardHealth::Ok
} else {
crate::model::BoardHealth::Fault
}
})
.map(|b| board_health(b.active, b.working_chips, is_mining || hashrate_ths > 0.0))
.collect();
if let Some(exp) = data.expected_hashboards {
while board_status.len() < exp as usize {
+151 -26
View File
@@ -34,12 +34,26 @@ pub fn is_supported_board(board: &str) -> bool {
SUPPORTED_BOARDS.iter().any(|(b, _)| *b == board)
}
/// The release asset to install: its filename and download URL, resolved to a
/// local path on the worker thread so the download never blocks the UI. (Local-
/// file install is a CLI feature; the GUI installs from scanned releases.)
pub struct AfwChoice {
pub name: String,
pub url: String,
/// Where the `.afw` to install comes from. `Release` is a scanned Gitea asset
/// (its filename and download URL), fetched on the worker thread so the download
/// never blocks the UI. `Local` is a file the operator picked with the Browse
/// button -- the same local-file install the CLI offers, now in the GUI too.
pub enum AfwSource {
Release { name: String, url: String },
Local(PathBuf),
}
impl AfwSource {
/// A short human label for the status line (the filename in both cases).
fn label(&self) -> String {
match self {
AfwSource::Release { name, .. } => name.clone(),
AfwSource::Local(p) => p
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| p.to_string_lossy().into_owned()),
}
}
}
/// Progress + results streamed from the background worker to the UI.
@@ -81,9 +95,10 @@ fn download_dir() -> PathBuf {
pub fn start_install(
ips: Vec<String>,
board: String,
source: AfwChoice,
source: AfwSource,
allow_unsigned: bool,
password: Option<String>,
is_update: bool,
) -> StockHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
@@ -111,26 +126,49 @@ pub fn start_install(
.spawn(move || {
let _ = tx.send(StockMsg::Started);
// 1. Download the chosen release asset (on this worker thread).
let _ = tx.send(StockMsg::Progress("acquiring .afw...".into()));
let afw_path = match fetch::fetch_afw_url(
&ReleaseSource::alkane_os(),
&source.name,
&source.url,
&download_dir(),
) {
Ok(p) => p,
Err(e) => {
// One failure line per target so the UI clears its op-status.
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!("could not fetch .afw: {e}"),
});
// 1. Acquire the .afw: a local file is used in place; a release asset
// is downloaded on this worker thread (never blocking the UI).
let afw_path = match source {
AfwSource::Local(path) => {
let _ = tx.send(StockMsg::Progress(format!(
"using local {}...",
AfwSource::Local(path.clone()).label()
)));
if !path.is_file() {
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!("local .afw not found: {}", path.display()),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
path
}
AfwSource::Release { name, url } => {
let _ = tx.send(StockMsg::Progress("acquiring .afw...".into()));
match fetch::fetch_afw_url(
&ReleaseSource::alkane_os(),
&name,
&url,
&download_dir(),
) {
Ok(p) => p,
Err(e) => {
// One failure line per target so the UI clears its op-status.
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: format!("could not fetch .afw: {e}"),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
}
let _ = tx.send(StockMsg::Done);
return;
}
};
@@ -170,6 +208,22 @@ pub fn start_install(
let _ = tx.send(StockMsg::Done);
return;
}
// An in-place Update must never rewrite the bootloader (review #1):
// refuse a tier-3 (bootloader-writing) bundle so the "BOOT.bin is
// never written" guarantee holds for an already-alkane board.
if is_update && verified.manifest.flash_plan().writes_uboot {
for ip in &ips {
let _ = tx.send(StockMsg::Result {
ip: ip.clone(),
ok: false,
detail: "update refused: this release reflashes the bootloader (tier 3); \
pick a tier-1/2 release or use Install"
.to_string(),
});
}
let _ = tx.send(StockMsg::Done);
return;
}
// 3. Install onto each board via the network-only from-stock method.
for ip in ips {
@@ -282,3 +336,74 @@ pub fn start_restore(ips: Vec<String>, firmware: PathBuf, password: Option<Strin
}
StockHandle { rx, cancel }
}
/// Whether a board holds a restorable on-board stock backup (network probe). A
/// quick, synchronous check the restore dialog uses to grey out the on-board
/// option when no backup is present. Any error reads as "not present".
pub fn onboard_backup_present(ip: &str, password: Option<&str>) -> bool {
if fake_scan_enabled() {
return true;
}
stock::onboard_stock_backup_present(ip, password).unwrap_or(false)
}
/// Restore the given alkane boards to genuine stock, over the network, from each
/// board's own on-board stock backup (no vendor firmware file). `password`, if
/// set, is the board's alkane root credential.
pub fn start_restore_onboard(ips: Vec<String>, password: Option<String>) -> StockHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
if fake_scan_enabled() {
let _ = tx.send(StockMsg::Started);
for ip in ips {
let _ = tx.send(StockMsg::Result {
ip,
ok: true,
detail: "restored to stock from on-board backup (demo)".into(),
});
}
let _ = tx.send(StockMsg::Done);
return StockHandle { rx, cancel };
}
let tc = cancel.clone();
let err_tx = tx.clone();
let spawned = std::thread::Builder::new()
.name("restore-onboard".into())
.spawn(move || {
let _ = tx.send(StockMsg::Started);
let timeout = std::time::Duration::from_secs(300);
for ip in ips {
if tc.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(StockMsg::Progress(format!(
"restoring {ip} to stock from its on-board backup..."
)));
let (ok, detail) =
match stock::restore_from_onboard_backup(&ip, password.as_deref(), timeout) {
Ok(()) => (
true,
"restored to stock from on-board backup (verify over the network)"
.to_string(),
),
Err(e) => (false, format!("restore failed: {e}")),
};
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
return;
}
}
let _ = tx.send(StockMsg::Done);
});
if spawned.is_err() {
let _ = err_tx.send(StockMsg::Result {
ip: String::new(),
ok: false,
detail: "could not start the restore worker thread".into(),
});
let _ = err_tx.send(StockMsg::Done);
}
StockHandle { rx, cancel }
}
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -142,15 +142,15 @@ selected board:
for; today the Zynq-7010 Antminer S17/S17 Pro/T17) that is not running Alkane
OS yet. Scans the alkane-os releases on Gitea, lets you pick one (newest first;
pre-releases are marked), optionally takes a board password and an "allow
unsigned .afw (bench)" toggle, and - after you type FLASH to confirm -
downloads/verifies the `.afw` and installs it onto each selected board over the
network, via the same compiled-in engine the CLI uses.
unsigned .afw (bench)" toggle, then - when you click Install - downloads and
verifies the `.afw` and installs it onto each selected board over the network,
via the same compiled-in engine the CLI uses.
- "Update alkane OS..." - for a supported board already running Alkane OS: the
same release picker and confirmation; the board is updated in place (BOOT.bin
is never written).
- "Uninstall alkane OS (restore to stock)..." - for a board running Alkane OS:
takes the board's alkane root password, a genuine Bitmain firmware package and
a typed FLASH confirmation, then restores each selected board to genuine stock
takes the board's alkane root password and a genuine Bitmain firmware package,
then - when you click Restore - restores each selected board to genuine stock
over the network.
A stock board the scan identifies but cannot place on a supported control board
+43
View File
@@ -0,0 +1,43 @@
Subject: [PATCH 0012] linux: word-wrapping multiline text control
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -890,6 +890,15 @@
wxDefaultPosition, wxSize(-1, -1), style);
}
+// A multiline text control that word-wraps at the control's width instead of
+// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
+// report box, where long lines should wrap rather than run off the edge.
+void* wxbr_text_ctrl_wrap(void* parent) {
+ return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
+ wxDefaultPosition, wxSize(-1, -1),
+ wxTE_MULTILINE | wxTE_BESTWRAP);
+}
+
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
// entry so a saved password is never rendered in the clear (round 18 #12).
void* wxbr_text_ctrl_password(void* parent) {
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -41,6 +41,7 @@
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
+ pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
@@ -463,6 +464,12 @@
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
}
+ /// A multiline text control that word-wraps at its width (no horizontal
+ /// scroll), for prose entry such as the bug-report box.
+ pub fn text_ctrl_wrapped(parent: Widget) -> Widget {
+ Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) })
+ }
+
/// A single-line text control that masks its content (for password entry).
pub fn password_ctrl(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
+38
View File
@@ -0,0 +1,38 @@
Subject: [PATCH 0013] linux: Enable/disable (grey out) a control
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -945,6 +945,11 @@
((wxCheckBox*)win)->SetValue(v != 0);
}
+// Enable or disable (grey out) any window/control.
+void wxbr_enable(void* win, int on) {
+ ((wxWindow*)win)->Enable(on != 0);
+}
+
// ---- check list box ---------------------------------------------------------
void* wxbr_check_list_box(void* parent) {
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -49,6 +49,7 @@
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
+ pub fn wxbr_enable(win: *mut c_void, on: c_int);
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
pub fn wxbr_clb_clear(win: *mut c_void);
@@ -508,6 +509,11 @@
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
}
+ /// Enable or disable (grey out) this control.
+ pub fn set_enabled(&self, on: bool) {
+ unsafe { notsafe::wxbr_enable(self.0, on as c_int) }
+ }
+
pub fn check_list_box(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
}
@@ -890,6 +890,15 @@ void* wxbr_text_ctrl(void* parent, int multiline) {
wxDefaultPosition, wxSize(-1, -1), style);
}
// A multiline text control that word-wraps at the control's width instead of
// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
// report box, where long lines should wrap rather than run off the edge.
void* wxbr_text_ctrl_wrap(void* parent) {
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
wxDefaultPosition, wxSize(-1, -1),
wxTE_MULTILINE | wxTE_BESTWRAP);
}
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
// entry so a saved password is never rendered in the clear (round 18 #12).
void* wxbr_text_ctrl_password(void* parent) {
@@ -936,6 +945,11 @@ void wxbr_check_box_set(void* win, int v) {
((wxCheckBox*)win)->SetValue(v != 0);
}
// Enable or disable (grey out) any window/control.
void wxbr_enable(void* win, int on) {
((wxWindow*)win)->Enable(on != 0);
}
// ---- check list box ---------------------------------------------------------
void* wxbr_check_list_box(void* parent) {
+13
View File
@@ -41,6 +41,7 @@ mod notsafe {
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
@@ -48,6 +49,7 @@ mod notsafe {
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
pub fn wxbr_enable(win: *mut c_void, on: c_int);
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
pub fn wxbr_clb_clear(win: *mut c_void);
@@ -463,6 +465,12 @@ impl Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
}
/// A multiline text control that word-wraps at its width (no horizontal
/// scroll), for prose entry such as the bug-report box.
pub fn text_ctrl_wrapped(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) })
}
/// A single-line text control that masks its content (for password entry).
pub fn password_ctrl(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
@@ -501,6 +509,11 @@ impl Widget {
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
}
/// Enable or disable (grey out) this control.
pub fn set_enabled(&self, on: bool) {
unsafe { notsafe::wxbr_enable(self.0, on as c_int) }
}
pub fn check_list_box(parent: Widget) -> Widget {
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
}
+2 -2
View File
@@ -15,8 +15,8 @@ services:
GITEA_URL: http://gitea:3000
GITEA_REPO: blueflare/alkane-toolkit
GITEA_TOKEN_FILE: /run/secrets/gitea_token
RATE_PER_IP: "5"
RATE_GLOBAL: "60"
RATE_PER_IP: "100"
RATE_GLOBAL: "300"
volumes:
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
networks: [proxy]