Compare commits

..
Author SHA1 Message Date
noahandClaude Opus 4.8 795f80a44c fix(gui): bench driver uses the alkane root credential for the restore leg
source / check (pull_request) Skipped
verify / verify (pull_request) Skipped
The flag-restore reaches the running alkane board over SSH as root, which is a
different credential from the stock login used for install. Alkane bench images
bake root/alkane; pass that (overridable via ALKANE_ROOT_PASSWORD) to the
restore, and keep the saved board SSH credential for the install. The previous
single-credential handoff sent the stock login to the alkane root restore and
hit "Permission denied".

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 12:03:07 -06:00
13 changed files with 87 additions and 320 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
publish:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
+1 -1
View File
@@ -7,7 +7,7 @@ on:
jobs:
publish:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
+1 -1
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
check:
runs-on: alkane-ci
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
+6 -71
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
verify:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
outputs:
@@ -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-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Windows toolchain
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- name: Cache vendored wxMSW build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (Windows target, warnings are errors)
run: bash ci/windows-ci.sh clippy
- name: Build (Windows)
run: bash ci/windows-ci.sh build
- name: Unit tests (Windows build, under Wine)
run: bash ci/windows-ci.sh test
- name: Headless UI self-test (Windows build, under Wine)
run: bash ci/windows-ci.sh selftest
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
# 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.
+18 -58
View File
@@ -22,8 +22,8 @@ use alkane_flash::preflight::{preflight, PreflightOptions};
use alkane_flash::stock;
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
use alkane_flash::stock_firmware;
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
use alkane_flash::zynq_nand;
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -1042,10 +1042,7 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
/// of these; `compat` lists them so an operator knows what is supported.
const SUPPORTED: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
(
"a113d",
"Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)",
),
("a113d", "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)"),
];
fn is_supported(board: &str) -> bool {
@@ -1131,9 +1128,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
None => {
if opts.flag("dry-run") {
println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag");
println!(
"(no stock firmware needed; the untouched stock boot partition is booted)."
);
println!("(no stock firmware needed; the untouched stock boot partition is booted).");
println!("Re-run with --confirm FLASH.");
return Ok(());
}
@@ -1143,9 +1138,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
println!("restoring {host} to genuine stock (A113D flag flip, network-only)...");
match stock::restore_aml_flag(&host, password.as_deref()) {
Ok(()) => {
println!(
"restore reported success (boot flag cleared; stock boots via storeboot)."
);
println!("restore reported success (boot flag cleared; stock boots via storeboot).");
println!("verify independently: the board should present genuine stock");
println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x).");
return Ok(());
@@ -1193,7 +1186,9 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, ssh_values(), &[])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let cmd = opts.positionals.join(" ");
let cmd = opts
.positionals
.join(" ");
if cmd.trim().is_empty() {
return Err("usage: alkane-cli afw root-run --host <ip> <command...>".into());
}
@@ -1208,11 +1203,7 @@ fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
/// backup, write the boot slots and reboot. Drives the DSH root-on-stock
/// primitive; board must be on stock (credential root/root).
fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["confirm"]].concat(),
&["allow-unsigned"],
)?;
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["allow-unsigned"])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let afw_path = opts
.positionals
@@ -1220,33 +1211,18 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.ok_or("usage: alkane-cli afw nand-install <afw> --host <ip> --confirm FLASH")?;
let verified = load_afw(afw_path, &opts)?;
if !zynq::owns_board(&verified.manifest.board) {
return Err(format!(
"nand-install is zynq-7010 only, not {}",
verified.manifest.board
)
.into());
return Err(format!("nand-install is zynq-7010 only, not {}", verified.manifest.board).into());
}
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to install without --confirm FLASH".into());
}
let kernel = verified
.image("kernel")
.ok_or("afw missing kernel image")?
.1;
let kernel = verified.image("kernel").ok_or("afw missing kernel image")?.1;
let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1;
let rootfs = verified
.image("rootfs")
.ok_or("afw missing rootfs image")?
.1;
let rootfs = verified.image("rootfs").ok_or("afw missing rootfs image")?.1;
let password = read_board_password(&opts)?;
println!(
"installing {} onto stock board {host} (readable NAND path)...",
verified.manifest.board
);
println!("installing {} onto stock board {host} (readable NAND path)...", verified.manifest.board);
zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?;
println!(
"install reported success (on-board stock backup carved; boot slots written; rebooting)."
);
println!("install reported success (on-board stock backup carved; boot slots written; rebooting).");
print!("{}", zynq_verify_hint(&host));
Ok(())
}
@@ -1255,15 +1231,9 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
/// back to the boot slots over SSH (board on alkane). Needs the alkane image
/// that exposes the boot partitions.
fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["confirm", "stock-firmware"]].concat(),
&["dry-run"],
)?;
let opts = parse_args(args, &[ssh_values(), &["confirm", "stock-firmware"]].concat(), &["dry-run"])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let firmware = opts
.value("stock-firmware")
.ok_or("--stock-firmware <file> is required")?;
let firmware = opts.value("stock-firmware").ok_or("--stock-firmware <file> is required")?;
let fw = stock_firmware::parse(Path::new(firmware))?;
println!("stock firmware: {}", fw.summary());
if opts.value("confirm") != Some("FLASH") {
@@ -1271,16 +1241,8 @@ fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Err
}
let password = read_board_password(&opts)?;
println!("restoring {host} to genuine stock (readable NAND path)...");
zynq_nand::restore_to_stock(
&host,
&fw.kernel,
&fw.rootfs,
fw.dtb.as_deref(),
password.as_deref(),
)?;
println!(
"restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)."
);
zynq_nand::restore_to_stock(&host, &fw.kernel, &fw.rootfs, fw.dtb.as_deref(), password.as_deref())?;
println!("restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved).");
Ok(())
}
@@ -1382,9 +1344,7 @@ fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>
password.as_deref(),
std::time::Duration::from_secs(300),
)?;
println!(
"restore-from-onboard reported success. Verify independently the board answers as stock."
);
println!("restore-from-onboard reported success. Verify independently the board answers as stock.");
Ok(())
}
+8 -12
View File
@@ -53,7 +53,8 @@ const FLAG_MAGIC: [u8; 4] = *b"ALAN";
const KRNADDR: &str = "0x1200000";
const FDTADDR: &str = "0x8000000";
const RDADDR: &str = "0x8100000";
const ALK_BOOTARGS: &str = "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
const ALK_BOOTARGS: &str =
"console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory.
const ALKANE_DIR: &str = "alkane";
@@ -109,8 +110,8 @@ impl AlkaneShell {
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
let transport = SshTransport::connect(options, true)
.map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
@@ -219,7 +220,7 @@ fn b64_decode(s: &str) -> Option<Vec<u8>> {
fn b64_encode(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
@@ -606,10 +607,7 @@ mod tests {
#[test]
fn env_roundtrips_with_crc() {
let vars = vec![
(
"bootcmd".to_owned(),
"run checkalk; run storeboot".to_owned(),
),
("bootcmd".to_owned(), "run checkalk; run storeboot".to_owned()),
("bootdelay".to_owned(), "1".to_owned()),
("checkalk".to_owned(), checkalk_value()),
];
@@ -618,10 +616,8 @@ mod tests {
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
assert_eq!(crc32(&blob[4..]), stored);
let parsed = parse_env(&blob);
assert_eq!(
parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
"run checkalk; run storeboot"
);
assert_eq!(parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
"run checkalk; run storeboot");
assert!(parsed.iter().any(|(k, _)| k == "checkalk"));
}
+1 -2
View File
@@ -30,8 +30,7 @@ pub mod zynq_nand;
clippy::too_many_arguments,
clippy::manual_repeat_n,
clippy::manual_is_multiple_of,
clippy::unnecessary_map_or,
clippy::question_mark
clippy::unnecessary_map_or
)]
mod stock_method;
pub mod transport;
+30 -70
View File
@@ -34,6 +34,7 @@ use crate::md5::md5_hex;
use crate::stock::StockError;
use crate::transport::{Remote, SshOptions, SshTransport};
use crate::uimage::{self, Kind};
use std::io::Write as _;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
@@ -130,7 +131,6 @@ impl Drop for TempFile {
#[cfg(unix)]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new()
.create(true)
@@ -142,11 +142,6 @@ fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
f.flush()
}
#[cfg(not(unix))]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
std::fs::write(path, contents)
}
impl AlkaneShell {
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
@@ -162,8 +157,8 @@ impl AlkaneShell {
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
let transport = SshTransport::connect(options, true)
.map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
@@ -230,7 +225,11 @@ fn read_mtd_table(sh: &mut dyn Shell) -> Result<Vec<Mtd>, StockError> {
.and_then(|h| u64::from_str_radix(h, 16).ok())
.ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?;
let _erase = it.next();
let name = line.split('"').nth(1).unwrap_or("").to_owned();
let name = line
.split('"')
.nth(1)
.unwrap_or("")
.to_owned();
let base = match sysfs_offset(sh, dev) {
Some(off) => off,
None => cursor,
@@ -258,7 +257,11 @@ fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option<u64> {
/// Find the partition that contains `abs` and holding at least `len` bytes from
/// there; return (device, relative offset).
fn locate(table: &[Mtd], abs: u64, len: u64) -> Result<(&str, u64), StockError> {
fn locate<'a>(
table: &'a [Mtd],
abs: u64,
len: u64,
) -> Result<(&'a str, u64), StockError> {
for m in table {
if abs >= m.base && abs < m.base + m.size {
let rel = abs - m.base;
@@ -305,7 +308,7 @@ fn write_abs(
"refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin"
)));
}
if !abs.is_multiple_of(ERASE) {
if abs % ERASE != 0 {
return Err(StockError::Method(format!(
"{label} offset 0x{abs:x} is not erase-block aligned"
)));
@@ -332,9 +335,7 @@ fn write_abs(
if o.contains("WROTE") {
Ok(())
} else {
Err(StockError::Method(format!(
"{label}: erase/write failed: {o}"
)))
Err(StockError::Method(format!("{label}: erase/write failed: {o}")))
}
})?;
let readlen = round_up(data.len() as u64, PAGE);
@@ -487,7 +488,7 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64;
let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64;
// Sanity: headers must look like a uImage/fdt, sizes within slots.
if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) {
if kernel_len < 64 || kernel_len > SLOT_KERNEL || rootfs_len < 64 || rootfs_len > SLOT_ROOTFS {
return Err(StockError::Method(format!(
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
refusing to back up"
@@ -512,13 +513,7 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
rootfs_abs: r_dst,
rootfs_len,
};
write_abs(
sh,
table,
BK_MANIFEST,
&manifest.encode(),
"stock-backup-manifest",
)?;
write_abs(sh, table, BK_MANIFEST, &manifest.encode(), "stock-backup-manifest")?;
Ok(manifest)
}
@@ -574,7 +569,11 @@ struct BootImages {
rootfs_uimage: Vec<u8>,
}
fn write_boot_slots(sh: &mut dyn Shell, table: &[Mtd], img: &BootImages) -> Result<(), StockError> {
fn write_boot_slots(
sh: &mut dyn Shell,
table: &[Mtd],
img: &BootImages,
) -> Result<(), StockError> {
// rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs
// under an old kernel.
if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS {
@@ -624,9 +623,7 @@ pub fn install_from_stock(
password: password.map(str::to_owned),
};
if first_token(&sh.exec("id -u")?) != "0" {
return Err(StockError::Auth(
"did not obtain root on the stock board".into(),
));
return Err(StockError::Auth("did not obtain root on the stock board".into()));
}
let table = read_mtd_table(&mut sh)?;
// Carve the genuine-stock backup from the live stock NAND before any write.
@@ -677,14 +674,7 @@ pub fn restore_to_stock(
"no stock dtb supplied and no on-board backup to take one from".into(),
)
})?;
copy_abs(
&mut sh,
&table,
manifest.dtb_abs,
OFF_DTB,
manifest.dtb_len,
"dtb",
)?;
copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?;
}
}
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
@@ -713,34 +703,14 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
let manifest = read_backup_manifest(&mut sh, &table)?
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
// Copy within NAND: backup region -> boot slots.
copy_abs(
&mut sh,
&table,
manifest.rootfs_abs,
OFF_ROOTFS,
manifest.rootfs_len,
"rootfs",
)?;
copy_abs(
&mut sh,
&table,
manifest.dtb_abs,
OFF_DTB,
manifest.dtb_len,
"dtb",
)?;
copy_abs(
&mut sh,
&table,
manifest.kernel_abs,
OFF_KERNEL,
manifest.kernel_len,
"kernel",
)?;
copy_abs(&mut sh, &table, manifest.rootfs_abs, OFF_ROOTFS, manifest.rootfs_len, "rootfs")?;
copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?;
copy_abs(&mut sh, &table, manifest.kernel_abs, OFF_KERNEL, manifest.kernel_len, "kernel")?;
reboot(&mut sh);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -781,18 +751,8 @@ mod tests {
#[test]
fn locate_maps_absolute_to_partition() {
let table = vec![
Mtd {
dev: "mtd0".into(),
base: 0x0,
size: 0x2800000,
name: "x".into(),
},
Mtd {
dev: "mtd1".into(),
base: 0x2800000,
size: 0x2000000,
name: "y".into(),
},
Mtd { dev: "mtd0".into(), base: 0x0, size: 0x2800000, name: "x".into() },
Mtd { dev: "mtd1".into(), base: 0x2800000, size: 0x2000000, name: "y".into() },
];
assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000));
assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0));
+5 -40
View File
@@ -143,23 +143,12 @@ pub fn is_alkane(row: &MinerRow) -> bool {
}
/// The alkane-os board family the row's control board is, when it can be told:
/// what an Alkane board reports, the stock Antminer Zynq-7010 (S17/T17 era,
/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control
/// board.
/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17
/// era, "XIL (C49)") control board.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
// 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;
}
@@ -254,10 +243,7 @@ mod tests {
assert!(install_supported(&s17));
assert!(!is_alkane(&s17));
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
// The Amlogic A113D control board is the "a113d" install target.
assert!(install_supported(&stock("AML", "C76")));
assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d"));
assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target
assert!(!install_supported(&stock("AML", "C76")));
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
@@ -288,9 +274,7 @@ mod tests {
assert!(!install_supported(&other("S19")));
assert!(!install_supported(&other("S17+")));
assert!(!install_supported(&other("")));
// A reported control board overrides the model: an "S17" model on an
// Amlogic A113D control board resolves to a113d (the control board),
// not zynq (the model).
// A reported control board overrides the model.
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
@@ -298,26 +282,7 @@ mod tests {
board_code: "C76".into(),
..Default::default()
};
assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d"));
}
#[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));
assert!(!install_supported(&s17_on_aml));
}
/// Live check against a real board:
+9 -22
View File
@@ -53,7 +53,9 @@ fn drive(label: &str, handle: StockHandle) -> bool {
fn ssh_banner(host: &str) -> Option<String> {
let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?;
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).ok()?;
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.ok()?;
let mut buf = [0u8; 256];
let n = stream.read(&mut buf).ok()?;
if n == 0 {
@@ -127,10 +129,7 @@ fn mac_of(host: &str) -> Option<String> {
let _ = Command::new("ping")
.args(["-c", "1", "-W", "1", host])
.output();
let out = Command::new("ip")
.args(["neigh", "show", host])
.output()
.ok()?;
let out = Command::new("ip").args(["neigh", "show", host]).output().ok()?;
let s = String::from_utf8_lossy(&out.stdout);
let mut it = s.split_whitespace();
while let Some(t) = it.next() {
@@ -184,12 +183,7 @@ fn ip_for_mac(mac: &str) -> Option<String> {
/// Poll until the board (located by MAC, so a changed DHCP lease is followed)
/// reaches the wanted stock-ness, or `timeout` elapses. Returns the board's
/// current IP, a description, and whether the target state was reached.
fn wait_for(
mac: Option<&str>,
fallback: &str,
want_stock: bool,
timeout: Duration,
) -> (String, String, bool) {
fn wait_for(mac: Option<&str>, fallback: &str, want_stock: bool, timeout: Duration) -> (String, String, bool) {
let deadline = Instant::now() + timeout;
let mut ip = fallback.to_string();
let mut swept = Instant::now() - Duration::from_secs(60);
@@ -261,8 +255,7 @@ pub fn run(spec: &str) -> i32 {
let mac = mac_of(&host);
println!(
"board MAC: {}",
mac.as_deref()
.unwrap_or("unknown (will use the fixed host)")
mac.as_deref().unwrap_or("unknown (will use the fixed host)")
);
let boot_timeout = Duration::from_secs(300);
@@ -277,7 +270,7 @@ pub fn run(spec: &str) -> i32 {
vec![host.clone()],
board.clone(),
AfwSource::Local(afw.clone()),
true, // allow unsigned (bench image)
true, // allow unsigned (bench image)
stock_password.clone(),
false, // not an in-place update
);
@@ -293,10 +286,7 @@ pub fn run(spec: &str) -> i32 {
boot_timeout.as_secs()
);
let (alkane_ip, desc, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
println!(
" {desc} => {}",
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
);
println!(" {desc} => {}", if ok { "ALKANE" } else { "NOT ALKANE (fail)" });
all_ok = all_ok && ok;
// 3. restore (alkane -> stock) flag-flip at the board's CURRENT address
@@ -313,10 +303,7 @@ pub fn run(spec: &str) -> i32 {
boot_timeout.as_secs()
);
let (_stock_ip, desc, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
println!(
" {desc} => {}",
if ok { "STOCK" } else { "NOT STOCK (fail)" }
);
println!(" {desc} => {}", if ok { "STOCK" } else { "NOT STOCK (fail)" });
all_ok = all_ok && ok;
}
+1 -1
View File
@@ -138,7 +138,7 @@ fn headless_mode() -> bool {
"ALKANE_BENCH_SEQUENCE",
]
.iter()
.any(|v| std::env::var_os(v).is_some())
.any(|v| std::env::var_os(v).is_some())
}
/// A Windows GUI-subsystem process has no console, so output from the headless
+1 -4
View File
@@ -26,10 +26,7 @@ use crate::scan::fake_scan_enabled;
/// `SUPPORTED`). Only these are offered as install targets.
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
(
"a113d",
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
),
("a113d", "Antminer S19j Pro (Amlogic A113D/AXG control board)"),
];
/// The default install board when the user has not chosen another.
+5 -37
View File
@@ -7,7 +7,6 @@ import json
import pathlib
import sys
import threading
import time
import unittest
import urllib.error
import urllib.request
@@ -17,12 +16,6 @@ import relay # noqa: E402
TOKEN = "test-token-123"
# The repository's labels, as the real Gitea /labels endpoint would return them.
# The mock serves these, and setUp seeds the relay client's label cache from the
# same list so label resolution is deterministic (see RelayTests.setUp).
REPO_LABELS = [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
{"name": "feature", "id": 3}, {"name": "from-app", "id": 9}]
class FakeGitea:
"""Records issue creations; serves the repository's labels."""
@@ -47,7 +40,9 @@ class FakeGitea:
def do_GET(self):
assert self.headers["Authorization"] == f"token {TOKEN}"
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
return self._json(200, REPO_LABELS)
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
{"name": "feature", "id": 3},
{"name": "from-app", "id": 9}])
self._json(404, {})
def do_POST(self):
@@ -63,23 +58,6 @@ class FakeGitea:
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
# Block until the serve_forever thread is actually handling requests, so
# the relay's first label fetch cannot race server startup. The socket
# listens from __init__, but under load the daemon thread can be starved
# past the relay's HTTP timeout, which silently drops labels to [] and
# made the first test flaky in CI.
probe = urllib.request.Request(
self.url + "/api/v1/repos/blueflare/alkane-toolkit/labels",
headers={"Authorization": f"token {TOKEN}"})
deadline = time.monotonic() + 5
while True:
try:
urllib.request.urlopen(probe, timeout=1).read()
break
except Exception:
if time.monotonic() >= deadline:
raise
time.sleep(0.02)
def close(self):
self.server.shutdown()
@@ -92,18 +70,8 @@ class RelayTests(unittest.TestCase):
self.now = [1000.0]
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
self.logs = []
client = relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN)
# Seed the relay client's label cache directly from REPO_LABELS instead
# of letting a request handler fetch it live. Gitea.label_ids() caches
# for 10 minutes and silently falls back to [] on any fetch error; in CI
# that first live GET -- a second server-to-server hop made from inside
# the relay's own request thread -- failed reliably and dropped the
# labels to [], while the issue-filing POST on the same path still
# worked. Seeding the cache keeps label resolution deterministic (the
# name->id mapping is still exercised) and leaves the issue POST live.
client.labels = {label["name"]: label["id"] for label in REPO_LABELS}
client.labels_at = time.monotonic()
r = relay.Relay(client, self.limiter, log=self.logs.append)
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
self.limiter, log=self.logs.append)
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"