Compare commits

...
9 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 79ecc100d3 review wave 3: log-fetch credential leak + JSON escaping + column-scan cost
Second review round (over the wave 1/2 fixes) surfaced further, mostly new-path
findings; this clears the substantive ones:

- HIGH log_scan.rs passed miner admin credentials on the curl command line (same
  class as the access-probe leak fixed in wave 1). Its curl() now takes optional
  stdin: the Antminer digest login goes through a curl config on stdin (-K -),
  the VNish unlock password through the POST body on stdin (-d @-), and the
  timeout path reaps the child so it no longer leaks a zombie.
- MEDIUM JSON injection/breakage: the VNish unlock body and the LuxOS
  uninstall command spliced a password / miner-supplied SessionID into JSON with
  format!. Both now build the JSON with serde_json, which escapes correctly.
- MEDIUM column scan cost: fill_rows computed table_columns() twice (my wave-2
  built_columns check added one), and with auto-hide-empty on that scans every
  cell of every row each time. It is now computed once and reused.

Accepted, documented tradeoffs from this round: miner_probe's setpools takes the
pool password as a CLI arg (inherent to a diagnostic CLI; it is the low-sensitivity
mining worker password), MinerRow::upsert_into's linear scan is fine at the tool's
fleet scale (hundreds), and bulk config-action writes stay serial deliberately.

96 tests + clippy-clean + selftest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 19:18:27 -06:00
noahandClaude Opus 4.8 51b4eb2556 review wave 2: scan concurrency, table-column lockstep, background log fetch
Continuing the recursive review's confirmed findings:

- HIGH scan telemetry was serial: the consumer awaited each responder's to_row
  (get_data + presets, several REST calls) inline in the identification stream
  loop, so telemetry ran one miner at a time. Now buffer_unordered runs it
  concurrently up to SCAN_CONCURRENCY_LIMIT; identification (which buffers
  internally) is unaffected, and telemetry only hits live responders.
- HIGH table columns diverged from the built widget with auto-hide-empty on:
  (1) drag-reorder was silently rejected because column_reordered fed
  table_columns() (empty-filtered) to apply_visible_reorder, which compared it to
  display_columns() (unfiltered) -- apply_visible_reorder now reorders the shown
  subset in place; (2) a column flipping non-empty mid-scan left the widget stale,
  so fill_rows now rebuilds when the shown set no longer matches built_columns.
  Both covered by a new unit test.
- HIGH viewing a miner's log blocked the wx UI thread for up to ~20s. The fetch
  now runs on a background thread; the viewer opens from the tick drain when the
  result lands (tick returns the dialog for dispatch to show modally).
- LOW start_pools_action's fake branch now honours the cancel flag like its
  siblings.
- Documented the intentional tradeoffs the review flagged: scan-restart uses
  cooperative cancellation (a hard join would freeze the UI), and the aftermarket
  re-probe stays per-scan for freshness (firmware can change between scans).

96 tests (+subset-reorder) + clippy-clean + selftest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 19:02:39 -06:00
noahandClaude Opus 4.8 3b18219e4e review wave 1: fix the critical restore false-success + security/correctness findings
From the recursive multi-agent review (18 confirmed findings). This wave clears
the critical, four highs, and several mediums/lows:

- CRITICAL restore.rs: a Braiins SSH restore reported SUCCESS on a wrong password
  or unreachable miner. run_with_timeout now captures the exit code and drains
  stderr on its own thread (also fixing the medium stderr-pipe stall), and a new
  testable classify_braiins() treats an ssh auth/connection failure (stderr
  diagnostic, empty stdout, non-zero exit) as failure while still reading a
  dropped connection / timeout as the expected reboot. Unit-tested.
- HIGH restore exclusivity: apply_restore_confirm now refuses when a scan/refresh/
  action/flash or another restore is in flight, so this destructive action never
  overlaps or orphans a running restore handle.
- HIGH secrets off the command line: Braiins SSH uses `sshpass -e` (env, not -p),
  and the access-probe curl passes credentials through a config on stdin (-K -)
  instead of `-u user:pass`; both were visible in the process list. New masked
  password field (wxTE_PASSWORD bridge) so the Credentials dialog no longer
  renders saved passwords in the clear.
- MEDIUM correctness: per-board Chip-temp readings are now index-aligned with the
  boards (a missing middle board shows "-" instead of shifting later boards left).
- MEDIUM: saved pool lists (which can hold a pool password) are chmod 0600.
- LOW: access-probe curl timeout now reaps the child (no zombie).

95 tests (+classify_braiins) + clippy-clean + selftest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 18:45:56 -06:00
noahandClaude Opus 4.8 bcc0ba38b6 ci: install clippy component before the gate; classify all GUI src as backend
Run 82 failed because the alkane-ci image ships no clippy component
("cargo-clippy is not installed for the toolchain"). Both workflows now
`rustup component add clippy` before the gate.

Also broadened compute-version.sh: any crates/alkane-gui/src/* file is backend
logic (previously only scan.rs/model.rs/main.rs were, so a fix confined to
naming.rs / pool_prefs.rs / restore.rs / access_probe.rs / credentials.rs would
never cut a release). ui.rs/fixtures.rs/bin still match the UI arm first. All 9
compute-version tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 18:22:32 -06:00
noahandClaude Opus 4.8 749cdc4eed item 12: CI verify/release split, dependency audit, README + badges
CI is now two workflows: verify.yml (pull requests + non-main pushes) runs the
clippy gate, build, unit tests, microbenchmarks, the headless self-test, and a
best-effort dependency audit; release.yml (main) repeats the clippy gate + audit
before its existing build/test/selftest/package/release, then refreshes the
committed README badges and pushes any change back (best-effort, and a badges-
only push does not bump the version, so it does not loop).

Security: cargo audit found a build-time-only advisory (h2 0.3 in the wx-rs
build script's reqwest 0.11 subtree, never linked into the runtime binary and
never executed on Linux). The vendored/offline tree can't upgrade it without
re-vendoring, so it is documented and accepted in .cargo/audit.toml (mirrored in
deny.toml with the project's permissive-license policy).

Badges: ci/gen-badges.py emits self-contained shields-style SVGs into badges/
(tests, coverage 36%, bench, LOC 12.5k, clippy clean, dependencies, license) --
committed and referenced by relative path so a self-hosted Gitea renders them
with no external service. README rewritten around what the toolkit actually does
today (discover / monitor / operate / install), with build, CLI, dev, and
architecture sections and the dual-license note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 18:17:31 -06:00
noahandClaude Opus 4.8 19e469ebc4 item 12: clippy-clean our crate + add LICENSE files
Cleared all clippy findings in alkane-gui (cargo clippy --no-deps): mechanical
fixes via clippy --fix (redundant imports, useless format!, manual_contains,
manual_is_multiple_of, unnecessary_map_or, unused parens) plus manual fixes:

- type_complexity: factored the segment tuple into model::{Rgb, Segment} aliases.
- large_enum_variant: #[allow] on ScanMsg/RefreshMsg with a note -- Row is the
  common variant, so boxing it to shrink the rare Started/Done would add an
  allocation per miner on the hot path.
- dead code: removed unused SHAPE_PULSE_DOT, ColorKind::Accent, clear_op_status,
  and RestoreMsg's unread `total`; kept the restore/access-probe cancel handles
  (workers honour cancellation; UI stop control pending) under #[allow].
- question_mark, needless_range_loop, drop_non_drop, doc_lazy_continuation fixes.

Only vendored wx-rs warnings remain (out of scope). Added LICENSE-MIT and
LICENSE-APACHE (Cargo.toml already declares MIT OR Apache-2.0). 94 tests +
selftest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 18:01:49 -06:00
noahandClaude Opus 4.8 6cd732dec5 Round C G7 (read side): per-board voltage/frequency in the board tooltip
Surfaces the per-hashboard configured voltage (V) and frequency (MHz) that
asic-rs already reads into BoardData but the toolkit dropped. Added
MinerRow.board_voltages / board_frequencies (index-aligned with the boards,
0.0 where unreported), populated at scan time, and appended to the per-board
Health tooltip as extra middot segments after actual/expected hashrate.

Verified live on LuxOS S19j Pro (10.4.1.60): boards report 12.73 V (frequency
is None in LuxOS's live stats path -- a pre-existing backend gap; the tooltip
omits absent values). miner_probe `msgs` now prints board freq/volt too.

The G7 WRITE path (per-board V/F override) stays deferred: no firmware accepts
Manual targets today and a bad voltage can damage a board, so per the parity
roadmap it is bench-only and not shipped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 17:40:32 -06:00
noahandClaude Opus 4.8 95b8428c12 Round C G3: named firmware presets (LuxOS) end to end
The flagship structured-tuning parity item: list and select a firmware's named
profiles/presets, not just map a watts number onto one.

Backend (vendored asic-rs, patch 0022): LuxOS now implements SupportsPresets
(get_presets reads the live `profiles` RPC) and a real SupportsTuningConfig
(set_tuning_config routes Preset(name) -> profileset, Power -> set_power_limit).
Unit-tested (parse_profiles_to_presets); verified live-read on two production
LuxOS S19j Pro (10.4.1.60/.67). VNish already exposed presets.

GUI: MinerCaps.supports_presets + MinerRow.presets (read live at scan time for
preset-capable miners; ~1 RPC per such miner per 300 s rescan). New "Set
profile..." right-click item opens a selector populated from the profiles
common to the whole selection (so the chosen name is valid on every target),
applied via the new ConfigAction::Preset. Offline fixtures seed demo presets.

CLI: `miner_probe presets <ip>` (list) and `setpreset <ip> <name>` (select).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 17:34:26 -06:00
noahandClaude Opus 4.8 a7ed34b8e4 gui: pool "+" "Add new..." opens a preset manager window (round 18 #8b)
The pool-field "+" menu previously offered a one-shot "Add new" (append
the current box value) plus a "Remove saved value" submenu. Both are now
replaced by "Add new...", which opens a small manager window: a multiline
editable list of all saved values for that field, seeded with the current
box value as the last line. Save rewrites the whole saved list at once.

- pool_prefs: new save_all() rewrites a field's saved list; the trim /
  drop-empties / drop-presets / de-dup step is factored into a pure
  dedupe_saved() with unit tests. Removed the now-unused add_saved /
  remove_saved.
- ui: build_pool_presets_dialog + apply_pool_presets, wired to
  ID_POOL_PRESETS_SAVE/CANCEL; "+" menu shows "Add new..." and no longer
  builds the remove submenu; ID_POOL_MENU_REMOVE_BASE dropped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 17:10:45 -06:00
33 changed files with 2014 additions and 265 deletions
+20
View File
@@ -0,0 +1,20 @@
# cargo-audit configuration (read by `cargo audit` from the project root).
#
# The two entries below are accepted, documented exceptions -- both live only in
# the wx-rs BUILD-dependency tree (reqwest 0.11, used by wx-rs's build.rs to
# download the wxWidgets source on Windows/macOS). On Linux download_dist()
# returns before ever constructing an HTTP client, and none of this is linked
# into the runtime binary, which talks to miners over asic-rs's reqwest 0.13
# (hyper 1.x / h2 0.4). The build tree is fully vendored and offline, so these
# cannot be upgraded without re-vendoring a newer reqwest.
#
# Re-review whenever the vendored dependency set is refreshed.
[advisories]
ignore = [
# h2 0.3 unbounded empty DATA frames (DoS). Build-time only; our build-time
# HTTP client only fetches a fixed HTTPS URL, and only on Windows/macOS.
"RUSTSEC-2026-0258",
# rustls-pemfile 1.0.4 unmaintained. Same build-only reqwest 0.11 subtree.
"RUSTSEC-2025-0134",
]
+44
View File
@@ -49,6 +49,13 @@ jobs:
echo "wx prefix restored from cache"
fi
- name: Clippy (our crate, warnings are errors)
if: steps.ver.outputs.release == 'true'
run: |
export WX_RS_WXCONFIG="$WX_PREFIX/bin/wx-config"
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --offline -- -D warnings
- name: Set crate version to ${{ steps.ver.outputs.version }}
if: steps.ver.outputs.release == 'true'
run: |
@@ -81,6 +88,43 @@ jobs:
BIN=target/release/alkane-toolkit
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
- name: Dependency audit (best-effort)
if: steps.ver.outputs.release == 'true'
continue-on-error: true
run: |
if command -v cargo-audit >/dev/null 2>&1; then
cargo audit || echo "cargo audit reported findings (accepted ones in .cargo/audit.toml)"
else
echo "cargo-audit not installed on this runner; skipping"
fi
# Refresh the committed README badges from live metrics and push any change
# back to main. Best-effort: a locked-down runner that can't push must not
# fail the release. A badges-only push does not bump the version (see
# compute-version.sh), so it does not loop back into another release.
- name: Refresh badges
if: steps.ver.outputs.release == 'true'
continue-on-error: true
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
export WX_RS_WXCONFIG="$WX_PREFIX/bin/wx-config"
PASS=$(cargo test -p alkane-gui --offline 2>&1 \
| grep -hoE '[0-9]+ passed' | grep -oE '[0-9]+' | awk '{s+=$1} END{print s+0}')
python3 ci/gen-badges.py --tests "${PASS:-0}" --bench "row-render + scan-parse"
if [ -n "$(git status --porcelain badges)" ]; then
git config user.name "alkane-ci"
git config user.email "ci@bluefla.re"
git add badges
git commit -m "ci: refresh README badges [skip release]"
API="${GITHUB_API_URL:-https://gitea.bluefla.re/api/v1}"
HOST="${API%/api/v1}"
git push "${HOST}/${GITHUB_REPOSITORY}.git" "HEAD:main" \
-c http.extraheader="Authorization: token ${TOKEN}" || echo "badge push skipped"
else
echo "badges unchanged"
fi
- name: Package artifact
if: steps.ver.outputs.release == 'true'
id: pkg
+74
View File
@@ -0,0 +1,74 @@
name: verify
# Pre-merge quality gate: clippy + build + tests + microbenchmarks + the headless
# UI self-test, plus a best-effort dependency audit. Runs on pull requests and on
# pushes to any branch EXCEPT main (main is gated by release.yml, which repeats
# these checks before it cuts a release -- so no work is duplicated on main).
on:
pull_request:
push:
branches-ignore: [main]
jobs:
verify:
runs-on: alkane-ci
env:
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install build dependencies
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
libssl-dev pkg-config ca-certificates >/dev/null
- name: Cache vendored wxWidgets build
uses: actions/cache@v4
with:
path: /root/.cache/wx-3.3.3-linux
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
- name: Build wxWidgets (once, then cached)
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
else
echo "wx prefix restored from cache"
fi
- name: Clippy (our crate, warnings are errors)
run: |
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --offline -- -D warnings
- name: Build
run: cargo build --release -p alkane-gui --offline
- name: Unit tests
run: cargo test -p alkane-gui --offline
- name: Microbenchmarks
run: cargo test -p alkane-gui --release --offline -- --ignored --nocapture bench_
- name: Headless UI self-test
run: |
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
xvfb xauth dbus-x11 fonts-dejavu-core >/dev/null
BIN=target/release/alkane-toolkit
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
# Advisory audit is best-effort: it needs the RustSec DB over the network,
# which the vendored/offline build otherwise never touches, so a locked-down
# runner must not fail the gate on it. Accepted advisories live in
# .cargo/audit.toml.
- name: Dependency audit (best-effort)
continue-on-error: true
run: |
if command -v cargo-audit >/dev/null 2>&1; then
cargo audit || echo "cargo audit reported findings (see .cargo/audit.toml for accepted ones)"
else
echo "cargo-audit not installed on this runner; skipping"
fi
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but not
limited to compiled object code, generated documentation, and
conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative
Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do
not modify the License. You may add Your own attribution notices
within Derivative Works that You distribute, alongside or as an
addendum to the NOTICE text from the Work, provided that such
additional attribution notices cannot be construed as modifying
the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Blueflare
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Blueflare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+99 -21
View File
@@ -1,38 +1,116 @@
# alkane-toolkit
Cross-platform desktop toolkit (Rust core, native GUI) to install **stock** or
**alkaneOS** firmware on ASIC miner control boards, whatever they currently run
(stock, Vnish/AnthillOS, Braiins OS+, LuxOS, ePIC, BixBit, WardenOS).
[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions/workflows/release.yml/badge.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
![tests](badges/tests.svg)
![coverage](badges/coverage.svg)
![bench](badges/bench.svg)
![lines of code](badges/loc.svg)
![clippy](badges/quality.svg)
![dependencies](badges/dependencies.svg)
![license](badges/license.svg)
Sibling to [alkane-sdk](https://gitea.bluefla.re/blueflare/alkane-sdk): the SDK
owns board knowledge and build outputs; this toolkit is the orchestration
engine and operator UI that executes its install recipes safely.
A cross-platform desktop toolkit for discovering, monitoring, and re-flashing
ASIC miners. It scans a fleet over the network, shows live health and hashrate
in a sortable table, and installs **stock** or **alkaneOS** firmware onto a
control board whatever it currently runs (stock, VNish/AnthillOS, Braiins OS+,
LuxOS, ePIC, HiveOn, BixBit, WardenOS).
## Status
The core and UI are pure Rust; the native window is wxWidgets driven through a
vendored, patched [wx-rs](thirdparty/wx-rs) bridge, so there is no Electron,
no web view, and a single self-contained binary per platform.
M1 primary view ships: discovery (vendored asic-rs 0.8.1) + the UI-SPEC
table (6 KPIs, sortable/drag-reorderable columns, row checkboxes, scan-range
editor, Excel-style filter, columns panel). Pure-Rust GUI on wxWidgets via
vendored + patched wx-rs (docs/adr/0002, 0003).
## What it does
## Build + run (Debian)
- **Discover** a fleet by CIDR or IP range and identify each miner's make,
model, control board, and firmware (via a vendored [asic-rs](vendor/asic-rs)).
- **Monitor** hashrate vs. expected, per-board health, chip temperatures, fans,
PSU state, and pool workers, with an Excel-style filter and drag-reorderable
columns.
- **Operate** miners from a right-click menu: flash the locate light, pause /
resume, restart, set a power or hashrate target, select a firmware profile
(LuxOS/VNish presets), configure pools, set the timezone, and change the
password -- each action offered only when every selected miner supports it.
- **Install firmware**: push stock or aftermarket images, or revert an
aftermarket miner to stock, behind a typed confirmation.
Discovery and telemetry are read-only and safe to run against any fleet; every
mutating action is capability-gated and, where destructive, confirmed.
## Build and run (Debian/Ubuntu)
```sh
scripts/build-wx-linux.sh # once: builds vendored wx 3.3.3 to ~/.cache
scripts/build-wx-linux.sh # once: builds the vendored wxWidgets 3.3.3 into ~/.cache
scripts/build-gui-linux.sh # cargo build --release -p alkane-gui
~/.cache/alkane-tk-target/release/alkane-toolkit
```
Windows/macOS: `scripts/build-gui-windows.sh` (needs a Windows/msys2
toolchain) and `scripts/build-gui-macos.sh` (needs a Mac) - the GUI code is
shared; only the C++ bridge + wx differ per platform.
Runtime needs GTK 3: `sudo apt install libgtk-3-0`. To explore the UI with no
hardware, run the offline demo fleet:
See `docs/IMPLEMENTATION-PLAN.md` for the roadmap.
```sh
ALKANE_FAKE_SCAN=1 alkane-toolkit
```
## Hard rules (from alkane-sdk `docs/install-methods.md`, encoded in code)
Windows and macOS share all GUI code; only the C++ bridge and wx build differ
(`scripts/build-gui-windows.sh` needs an msys2 toolchain, `-macos.sh` needs a
Mac).
1. Never write the bootloader/secure region.
## Command-line probe
`miner_probe` is a headless companion for hardware checks that should not go
through the window event loop -- discovery, telemetry, and each write action:
```sh
miner_probe scan 10.0.0.0/24 # discover + telemetry (TSV)
miner_probe presets 10.0.0.5 # list a firmware's selectable profiles
miner_probe setpreset 10.0.0.5 540MHz
```
Run `miner_probe` with no arguments for the full verb list.
## Development
```sh
export WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config"
export CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target" # keep the target tree off the source share
cargo test -p alkane-gui # unit tests
cargo test -p alkane-gui --release -- --ignored bench_ # microbenchmarks
cargo clippy -p alkane-gui --no-deps --bins -- -D warnings # lint gate
xvfb-run -a env ALKANE_SELFTEST=1 \
"$CARGO_TARGET_DIR/release/alkane-toolkit" # headless UI self-test
```
CI mirrors these: `verify.yml` runs the lint, tests, benchmarks, self-test, and
a best-effort dependency audit on every pull request and branch push;
`release.yml` repeats them on `main` and cuts an `X.Y.Z` release with the built
binary attached when the change warrants it. Dependencies are vendored under
`vendor/`, so builds never touch the network.
## Architecture
- `crates/alkane-gui` -- the application: scan engine, data model, wxWidgets UI,
and the `miner_probe` CLI (the other `crates/alkane-*` are early scaffolding).
- `vendor/asic-rs` -- the miner-discovery and control library, vendored and
extended through numbered patches under `thirdparty/asic-rs/patches`.
- `thirdparty/wx-rs` -- the patched wxWidgets bridge (see `docs/adr/0002`,
`0003`).
See [`docs/IMPLEMENTATION-PLAN.md`](docs/IMPLEMENTATION-PLAN.md) for the roadmap
and [`docs/aftermarket-parity-roadmap.md`](docs/aftermarket-parity-roadmap.md)
for the firmware config/scan parity work.
## Firmware safety rules
Encoded in code, from alkane-sdk `docs/install-methods.md`:
1. Never write the bootloader or secure region.
2. Verify on a channel the installer does not control.
3. Reboot is root-only; a dropped SSH connection can be success.
4. A packer is per board; never reuse across boards.
3. Reboot is root-only; a dropped SSH connection can still be success.
4. A packer is per board; never reuse one across boards.
5. Boot-switch handling is an explicit, verified step.
## License
Dual-licensed under either of [Apache-2.0](LICENSE-APACHE) or
[MIT](LICENSE-MIT) at your option.
+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="206.0" height="20" role="img" aria-label="bench: row-render + scan-parse">
<title>bench: row-render + scan-parse</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="206.0" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="44.5" height="20" fill="#555"/>
<rect x="44.5" width="161.5" height="20" fill="#007ec6"/>
<rect width="206.0" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="22.2" y="15" fill="#010101" fill-opacity=".3">bench</text>
<text x="22.2" y="14">bench</text>
<text x="125.2" y="15" fill="#010101" fill-opacity=".3">row-render + scan-parse</text>
<text x="125.2" y="14">row-render + scan-parse</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 993 B

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="95.5" height="20" role="img" aria-label="coverage: 36%">
<title>coverage: 36%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="95.5" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="64.0" height="20" fill="#555"/>
<rect x="64.0" width="31.5" height="20" fill="#fe7d37"/>
<rect width="95.5" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="32.0" y="15" fill="#010101" fill-opacity=".3">coverage</text>
<text x="32.0" y="14">coverage</text>
<text x="79.8" y="15" fill="#010101" fill-opacity=".3">36%</text>
<text x="79.8" y="14">36%</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 919 B

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="121.5" height="20" role="img" aria-label="dependencies: 349">
<title>dependencies: 349</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="121.5" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="90.0" height="20" fill="#555"/>
<rect x="90.0" width="31.5" height="20" fill="#007ec6"/>
<rect width="121.5" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="45.0" y="15" fill="#010101" fill-opacity=".3">dependencies</text>
<text x="45.0" y="14">dependencies</text>
<text x="105.8" y="15" fill="#010101" fill-opacity=".3">349</text>
<text x="105.8" y="14">349</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 940 B

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="180.0" height="20" role="img" aria-label="license: MIT OR Apache-2.0">
<title>license: MIT OR Apache-2.0</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="180.0" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="57.5" height="20" fill="#555"/>
<rect x="57.5" width="122.5" height="20" fill="#007ec6"/>
<rect width="180.0" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="28.8" y="15" fill="#010101" fill-opacity=".3">license</text>
<text x="28.8" y="14">license</text>
<text x="118.8" y="15" fill="#010101" fill-opacity=".3">MIT OR Apache-2.0</text>
<text x="118.8" y="14">MIT OR Apache-2.0</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 977 B

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="lines of code: 12.5k">
<title>lines of code: 12.5k</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="141.0" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="96.5" height="20" fill="#555"/>
<rect x="96.5" width="44.5" height="20" fill="#007ec6"/>
<rect width="141.0" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="48.2" y="15" fill="#010101" fill-opacity=".3">lines of code</text>
<text x="48.2" y="14">lines of code</text>
<text x="118.8" y="15" fill="#010101" fill-opacity=".3">12.5k</text>
<text x="118.8" y="14">12.5k</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 952 B

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="95.5" height="20" role="img" aria-label="clippy: clean">
<title>clippy: clean</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="95.5" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="51.0" height="20" fill="#555"/>
<rect x="51.0" width="44.5" height="20" fill="#4c1"/>
<rect width="95.5" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="25.5" y="15" fill="#010101" fill-opacity=".3">clippy</text>
<text x="25.5" y="14">clippy</text>
<text x="73.2" y="15" fill="#010101" fill-opacity=".3">clean</text>
<text x="73.2" y="14">clean</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 916 B

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="121.5" height="20" role="img" aria-label="tests: 94 passing">
<title>tests: 94 passing</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="121.5" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="44.5" height="20" fill="#555"/>
<rect x="44.5" width="77.0" height="20" fill="#4c1"/>
<rect width="121.5" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="22.2" y="15" fill="#010101" fill-opacity=".3">tests</text>
<text x="22.2" y="14">tests</text>
<text x="83.0" y="15" fill="#010101" fill-opacity=".3">94 passing</text>
<text x="83.0" y="14">94 passing</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 935 B

+4 -2
View File
@@ -35,9 +35,11 @@ crates/alkane-gui/src/bin/*)
ui=true ;;
crates/alkane-core/*|crates/alkane-discovery/*|crates/alkane-access/*|\
crates/alkane-flash/*|crates/alkane-artifacts/*|crates/alkane-cli/*|\
crates/alkane-gui/src/scan.rs|crates/alkane-gui/src/model.rs|\
crates/alkane-gui/src/main.rs|Cargo.toml|Cargo.lock|.gitea/*|ci/*|scripts/*|\
crates/alkane-gui/src/*|Cargo.toml|Cargo.lock|.gitea/*|ci/*|scripts/*|\
vendor/*|thirdparty/asic-rs/*)
# Any other GUI source file (naming, scan, model, pool_prefs, restore,
# access_probe, credentials, ...) is backend logic. ui.rs/fixtures.rs/bin
# match the UI arm above first, so they still bump Z, not Y.
backend=true ;;
*) : ;; # docs, HANDOFF, README, thirdparty/wxwidgets tree: no bump
esac
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Generate self-contained shields-style SVG badges into badges/.
Self-hosted Gitea renders a README's relative image links straight from the
repo, so committing the SVGs (rather than depending on an external badge
service that would have to reach a possibly-private Gitea) is the robust choice.
CI regenerates them from live metrics and commits any changes back.
Usage:
gen-badges.py --tests N --coverage PCT --bench "label" [--out badges]
Metrics not passed on the command line are computed here (LOC from the source
tree, dependency count from Cargo.lock, license from Cargo.toml).
"""
import argparse
import os
import re
import sys
# Approximate per-character width at 11px DejaVu Sans, in 1/10 px, matching the
# shields "flat" look closely enough for a fixed-width monospace-ish render.
CHAR_W = 6.5
PAD = 6.0
COLORS = {
"green": "#4c1",
"brightgreen": "#4c1",
"yellowgreen": "#a4a61d",
"yellow": "#dfb317",
"orange": "#fe7d37",
"red": "#e05d44",
"blue": "#007ec6",
"lightgrey": "#9f9f9f",
"grey": "#555",
}
def text_width(s: str) -> float:
return len(s) * CHAR_W + 2 * PAD
def badge_svg(label: str, message: str, color: str) -> str:
color = COLORS.get(color, color)
lw = round(text_width(label), 1)
mw = round(text_width(message), 1)
total = round(lw + mw, 1)
lx = round(lw / 2, 1)
mx = round(lw + mw / 2, 1)
# Text is drawn twice (a dark shadow then the light glyphs) for the shields look.
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{label}: {message}">
<title>{label}: {message}</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="{total}" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="{lw}" height="20" fill="#555"/>
<rect x="{lw}" width="{mw}" height="20" fill="{color}"/>
<rect width="{total}" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="{lx}" y="15" fill="#010101" fill-opacity=".3">{label}</text>
<text x="{lx}" y="14">{label}</text>
<text x="{mx}" y="15" fill="#010101" fill-opacity=".3">{message}</text>
<text x="{mx}" y="14">{message}</text>
</g>
</svg>
'''
def count_loc(root: str) -> int:
total = 0
for base in ("crates",):
for dirpath, _dirs, files in os.walk(os.path.join(root, base)):
for f in files:
if f.endswith(".rs"):
try:
with open(os.path.join(dirpath, f), encoding="utf-8", errors="ignore") as fh:
total += sum(1 for _ in fh)
except OSError:
pass
return total
def count_deps(root: str) -> int:
lock = os.path.join(root, "Cargo.lock")
try:
with open(lock, encoding="utf-8") as fh:
return sum(1 for line in fh if line.startswith("name = "))
except OSError:
return 0
def read_license(root: str) -> str:
try:
with open(os.path.join(root, "Cargo.toml"), encoding="utf-8") as fh:
for line in fh:
m = re.match(r'\s*license\s*=\s*"([^"]+)"', line)
if m:
return m.group(1)
except OSError:
pass
return "unknown"
def loc_color(n: int) -> str:
return "blue"
def cov_color(pct: float) -> str:
if pct >= 80:
return "brightgreen"
if pct >= 60:
return "yellowgreen"
if pct >= 40:
return "yellow"
if pct >= 20:
return "orange"
return "red"
def human(n: int) -> str:
if n >= 1000:
return f"{n / 1000:.1f}k".replace(".0k", "k")
return str(n)
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="badges")
ap.add_argument("--root", default=".")
ap.add_argument("--tests", type=int, default=None)
ap.add_argument("--coverage", type=float, default=None)
ap.add_argument("--bench", default=None)
ap.add_argument("--clippy", default="clean")
args = ap.parse_args()
os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
def write(name, label, message, color):
path = os.path.join(args.root, args.out, name + ".svg")
with open(path, "w", encoding="utf-8") as fh:
fh.write(badge_svg(label, message, color))
print(f"wrote {path}: {label}={message}")
loc = count_loc(args.root)
deps = count_deps(args.root)
lic = read_license(args.root)
write("loc", "lines of code", human(loc), loc_color(loc))
write("license", "license", lic, "blue")
write("dependencies", "dependencies", str(deps), "blue")
write("quality", "clippy", args.clippy, "brightgreen" if args.clippy == "clean" else "orange")
if args.tests is not None:
write("tests", "tests", f"{args.tests} passing", "brightgreen")
if args.coverage is not None:
write("coverage", "coverage", f"{args.coverage:.0f}%", cov_color(args.coverage))
if args.bench is not None:
write("bench", "bench", args.bench, "blue")
return 0
if __name__ == "__main__":
sys.exit(main())
+30 -8
View File
@@ -64,7 +64,6 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
return Ok(probe_whatsminer_access(ip, &whatsminer_password_candidates()));
}
let url = format!("http://{ip}{}", endpoint(make));
let userpass = format!("{user}:{pass}");
let mut cmd = Command::new("curl");
cmd.args([
"-s",
@@ -73,15 +72,18 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
"-w",
"%{http_code}",
"--digest",
"-u",
&userpass,
"--connect-timeout",
"5",
"--max-time",
"9",
"-K",
"-", // read the rest of the config (the credentials) from stdin
&url,
]);
let out = wait_with_timeout(cmd, Duration::from_secs(12))?;
// The user:pass goes through a curl config on stdin, never argv, so it can't
// be read from the process list (round 18 #12).
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
// curl prints the status code to stdout regardless of exit status (000 on a
// connection failure), so classify the code rather than the exit status.
let code = String::from_utf8_lossy(&out.stdout);
@@ -89,11 +91,25 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
}
/// Run a command with a wall-clock timeout (curl can hang past --max-time on a
/// black-holed host).
fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process::Output, String> {
use std::io::Read;
/// black-holed host). `stdin_data`, when set, is written to the child's stdin and
/// the pipe closed -- used to feed a curl config (with the credentials) instead
/// of putting them on the command line (round 18 #12).
fn wait_with_timeout(
mut cmd: Command,
timeout: Duration,
stdin_data: Option<&[u8]>,
) -> Result<std::process::Output, String> {
use std::io::{Read, Write};
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
if stdin_data.is_some() {
cmd.stdin(std::process::Stdio::piped());
}
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
if let Some(data) = stdin_data {
if let Some(mut si) = child.stdin.take() {
let _ = si.write_all(data);
} // dropping `si` closes the pipe so curl stops reading the config
}
let start = std::time::Instant::now();
loop {
match child.try_wait().map_err(|e| e.to_string())? {
@@ -111,6 +127,7 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait(); // reap so we never leave a zombie (round 18 #12)
return Err("curl timed out".into());
}
std::thread::sleep(Duration::from_millis(100));
@@ -119,6 +136,11 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process
}
}
/// Escape a value for a curl `--config` file (double-quoted string).
fn curl_config_quote(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
/// Passwords to try for a WhatsMiner access check: a user-set per-firmware
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
@@ -215,7 +237,7 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
Ok(v) => v,
Err(_) => return None,
};
let Some(msg) = v.get("Msg") else { return None };
let msg = v.get("Msg")?;
let (Some(salt), Some(newsalt), Some(time)) = (
msg.get("salt").and_then(|s| s.as_str()),
msg.get("newsalt").and_then(|s| s.as_str()),
+79 -2
View File
@@ -1,6 +1,6 @@
//! miner_probe -- a read-only (by default) asic-rs diagnostic for live-hardware
//! verification of the round-9 power-limit work. It reuses the same MinerFactory
//! + saved-credential setup the GUI uses (see crate::credentials), but as a
//! and saved-credential setup the GUI uses (see crate::credentials), but as a
//! standalone CLI so hardware checks don't go through the wx event loop.
//!
//! Usage:
@@ -300,13 +300,15 @@ async fn msgs(ip_s: &str) {
println!(" fans(rpm)={fans:?} psu_fans={}", d.psu_fans.len());
for b in d.hashboards.iter() {
println!(
" board pos={} hr={:?}TH chips={:?}/{:?} board_temp={:?} outlet_temp={:?}",
" board pos={} hr={:?}TH chips={:?}/{:?} board_temp={:?} outlet_temp={:?} freq={:?}MHz volt={:?}V",
b.position,
th(&b.hashrate),
b.working_chips,
b.expected_chips,
b.board_temperature.as_ref().map(|t| t.as_celsius()),
b.outlet_chip_temperature.as_ref().map(|t| t.as_celsius()),
b.frequency.as_ref().map(|f| f.as_megahertz()),
b.voltage.as_ref().map(|v| v.as_volts()),
);
}
if d.messages.is_empty() {
@@ -598,6 +600,77 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
}
}
/// READ: list the firmware's selectable profiles/presets (roadmap G3).
async fn presets(ip_s: &str) {
let ip: std::net::IpAddr = match ip_s.parse() {
Ok(ip) => ip,
Err(e) => {
eprintln!("bad ip {ip_s}: {e}");
return;
}
};
let f = factory();
match f.scan_miner(ip).await {
Ok(Some(m)) => {
if !m.supports_presets() {
println!("{ip}: firmware does not expose named presets");
return;
}
let list = m.get_presets().await;
if list.is_empty() {
println!("{ip}: no presets reported");
return;
}
for p in list {
match (p.pretty, p.status) {
(Some(pretty), Some(status)) => println!("{}\t{pretty}\t[{status}]", p.name),
(Some(pretty), None) => println!("{}\t{pretty}", p.name),
(None, _) => println!("{}", p.name),
}
}
}
Ok(None) => eprintln!("no miner at {ip}"),
Err(e) => eprintln!("scan_miner {ip}: {e}"),
}
}
/// WRITE (reversible): select a named firmware profile/preset (roadmap G3).
/// `setpreset <ip> <name>`. Prints the prior target so it can be restored.
async fn setpreset(ip_s: &str, name: &str) {
use asic_rs::core::config::tuning::TuningConfig;
use asic_rs::core::data::miner::TuningTarget;
let ip: std::net::IpAddr = match ip_s.parse() {
Ok(ip) => ip,
Err(e) => {
eprintln!("bad ip {ip_s}: {e}");
return;
}
};
let f = factory();
match f.scan_miner(ip).await {
Ok(Some(m)) => {
let before = m.get_data().await;
eprintln!(
"target {ip}: {} {} {} (supports_presets={}); prior target = {:?}",
before.device_info.make,
before.device_info.firmware,
before.device_info.model,
m.supports_presets(),
before.tuning_target,
);
let cfg = TuningConfig::new(TuningTarget::Preset(name.to_string()));
match m.set_tuning_config(cfg, None).await {
Ok(v) => println!("set_tuning_config(preset {name}) -> Ok({v})"),
Err(e) => println!("set_tuning_config(preset {name}) -> Err: {e:#}"),
}
let after = m.get_data().await;
println!(" target now = {:?}", after.tuning_target);
}
Ok(None) => eprintln!("no miner at {ip}"),
Err(e) => eprintln!("scan_miner {ip}: {e}"),
}
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
@@ -630,6 +703,8 @@ fn main() {
}
Some("msgs") if args.len() == 3 => rt.block_on(msgs(&args[2])),
Some("tune") if args.len() == 3 => rt.block_on(tune(&args[2])),
Some("presets") if args.len() == 3 => rt.block_on(presets(&args[2])),
Some("setpreset") if args.len() == 4 => rt.block_on(setpreset(&args[2], &args[3])),
Some("settune") if args.len() == 5 && matches!(args[3].as_str(), "power" | "hashrate") => {
let value: f64 = args[4].parse().unwrap_or(-1.0);
if value <= 0.0 {
@@ -651,6 +726,7 @@ fn main() {
\x20 hashrate <cidr> [<cidr>...] raw hashrate/algo dump\n\
\x20 msgs <ip> structured faults + per-board data\n\
\x20 tune <ip> structured-tuning support + capability envelope\n\
\x20 presets <ip> list selectable firmware profiles/presets\n\
\n\
WRITE (MUTATES the miner -- use the test-bed miners, not production):\n\
\x20 light <ip> <on|off> set the locate light\n\
@@ -660,6 +736,7 @@ fn main() {
\x20 restart <ip> restart/reboot\n\
\x20 setpl <ip> <watts> set power limit\n\
\x20 settune <ip> <power|hashrate> <v> set a structured tuning target (prints prior)\n\
\x20 setpreset <ip> <name> select a named firmware profile/preset (prints prior)\n\
\x20 setpools <ip> <url> <user> <pass> set the default pool group\n\
\x20 timezone <ip> [<IANA>] read (no arg) or set the timezone\n\
\x20 passwd <ip> <newpass> change the web/API password (DANGEROUS)\n\
+20
View File
@@ -67,6 +67,12 @@ impl Board {
} else {
vec![]
};
// Per-board configured frequency/voltage for the G7 read-side tooltip demo.
let (board_frequencies, board_voltages) = if self.mining {
(vec![590.0, 590.0, 565.0], vec![13.50, 13.50, 13.35])
} else {
(vec![], vec![])
};
// Air-cooled WhatsMiners report an ambient reading (asic-rs surfaces it in
// its fluid_temperature field); the scan routes it to env_temp for
// air-cooled models, so the demo mirrors that (round 11 #17).
@@ -117,6 +123,8 @@ impl Board {
hashrate_ths: self.hashrate,
expected_ths: self.expected,
board_hashrates,
board_voltages,
board_frequencies,
efficiency,
power_w: self.power,
chip_temp_c: self.temp,
@@ -173,6 +181,7 @@ impl Board {
power_limit: self.mining,
tuning: self.mining,
hashrate_target: self.mining,
supports_presets: self.mining,
firmware_flash,
pools: true,
timezone: self.mining,
@@ -203,6 +212,17 @@ impl Board {
} else {
Vec::new()
},
// Demo firmware presets (round 18 / G3) so the "Set profile..." dialog
// is exercisable offline on units that advertise preset support.
presets: if self.mining {
vec![
crate::model::MinerPreset { name: "default".into(), pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()) },
crate::model::MinerPreset { name: "540MHz".into(), pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()) },
crate::model::MinerPreset { name: "490MHz".into(), pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()) },
]
} else {
Vec::new()
},
..Default::default()
}
}
+67 -37
View File
@@ -122,35 +122,45 @@ fn summarize_log(log: &str) -> Vec<String> {
/// VNish: unlock -> bearer -> the full miner log.
fn fetch_vnish_log(ip: &str, pass: &str) -> Result<String, String> {
let unlock = curl(&[
"-s",
"--connect-timeout",
"5",
"--max-time",
"9",
"-X",
"POST",
"-H",
"Content-Type: application/json",
"-d",
&format!("{{\"pw\":\"{pass}\"}}"),
&format!("http://{ip}/api/v1/unlock"),
])?;
// The password goes in the POST body read from stdin (-d @-), never on argv,
// and is JSON-encoded by serde so it is both un-leakable and correctly escaped
// (round 18 #12).
let body = serde_json::json!({ "pw": pass }).to_string();
let unlock = curl(
&[
"-s",
"--connect-timeout",
"5",
"--max-time",
"9",
"-X",
"POST",
"-H",
"Content-Type: application/json",
"-d",
"@-",
&format!("http://{ip}/api/v1/unlock"),
],
Some(body.as_bytes()),
)?;
let token = serde_json::from_str::<serde_json::Value>(&unlock)
.ok()
.and_then(|v| v.get("token").and_then(|t| t.as_str()).map(str::to_string))
.filter(|t| !t.is_empty())
.ok_or_else(|| "VNish unlock rejected (check the VNish password in scan credentials)".to_string())?;
let log = curl(&[
"-s",
"--connect-timeout",
"5",
"--max-time",
"12",
"-H",
&format!("Authorization: Bearer {token}"),
&format!("http://{ip}/api/v1/logs/miner"),
])?;
let log = curl(
&[
"-s",
"--connect-timeout",
"5",
"--max-time",
"12",
"-H",
&format!("Authorization: Bearer {token}"),
&format!("http://{ip}/api/v1/logs/miner"),
],
None,
)?;
if log.trim().is_empty() {
return Err("VNish returned an empty log".to_string());
}
@@ -159,17 +169,23 @@ fn fetch_vnish_log(ip: &str, pass: &str) -> Result<String, String> {
/// Stock Antminer web log (digest auth). Absent on older models (404).
fn fetch_antminer_log(ip: &str, user: &str, pass: &str) -> Result<String, String> {
let body = curl(&[
"-s",
"--digest",
"-u",
&format!("{user}:{pass}"),
"--connect-timeout",
"5",
"--max-time",
"12",
&format!("http://{ip}/cgi-bin/log.cgi"),
])?;
// Credentials go through a curl config on stdin (-K -), never on argv, so they
// can't be read from the process list (round 18 #12).
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
let body = curl(
&[
"-s",
"--digest",
"--connect-timeout",
"5",
"--max-time",
"12",
"-K",
"-",
&format!("http://{ip}/cgi-bin/log.cgi"),
],
Some(config.as_bytes()),
)?;
if body.contains("404 - Not Found") || body.trim().is_empty() {
return Err("this firmware does not expose a log over its web API".to_string());
}
@@ -186,13 +202,21 @@ fn fetch_whatsminer_errors(ip: &str) -> Result<String, String> {
/// Run curl and return stdout, with a hard wall-clock cap. stdout is drained on a
/// separate thread so a large log (hundreds of KB) never deadlocks on a full pipe
/// -- the reason a naive "wait then read" times out on the VNish log.
fn curl(args: &[&str]) -> Result<String, String> {
use std::io::Read;
fn curl(args: &[&str], stdin_data: Option<&[u8]>) -> Result<String, String> {
use std::io::{Read, Write};
let mut cmd = Command::new("curl");
cmd.args(args);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::null());
if stdin_data.is_some() {
cmd.stdin(std::process::Stdio::piped());
}
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
if let Some(data) = stdin_data {
if let Some(mut si) = child.stdin.take() {
let _ = si.write_all(data);
} // dropping `si` closes the pipe so curl stops reading the config/body
}
let mut stdout = child.stdout.take().ok_or("no curl stdout")?;
let reader = std::thread::spawn(move || {
let mut buf = Vec::new();
@@ -208,6 +232,7 @@ fn curl(args: &[&str]) -> Result<String, String> {
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait(); // reap so we never leave a zombie (round 18 #12)
timed_out = true;
break;
}
@@ -222,6 +247,11 @@ fn curl(args: &[&str]) -> Result<String, String> {
Ok(String::from_utf8_lossy(&buf).into_owned())
}
/// Escape a value for a curl `--config` file (double-quoted string).
fn curl_config_quote(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
#[cfg(test)]
mod tests {
use super::*;
-1
View File
@@ -16,7 +16,6 @@ mod restore;
mod scan;
mod ui;
use wx_rs;
fn main() {
// Headless workflow self-test: render the bench-fleet fixtures through the
+98 -11
View File
@@ -123,12 +123,19 @@ fn combined_count(actual: Option<u32>, expected: Option<u32>) -> String {
}
}
/// An RGB colour (0-255 per channel) for a coloured text segment.
pub type Rgb = (u8, u8, u8);
/// One coloured text segment: an optional colour plus its text. Cells with
/// two-tone / multi-tone content (actual vs expected, per-fan colours) are built
/// as a `Vec<Segment>` and encoded via [`encode_segments`].
pub type Segment = (Option<Rgb>, String);
/// Encode colored text segments for a custom-rendered cell (see the wx-rs
/// `SegmentRenderer`): segments are joined by U+001F, and within a segment an
/// optional uppercase RRGGBB color is separated from its text by U+001E.
/// `decode_segments_plain` is the inverse for anything that just wants the
/// plain text (filtering, sorting, tests).
pub fn encode_segments(segs: &[(Option<(u8, u8, u8)>, String)]) -> String {
pub fn encode_segments(segs: &[Segment]) -> String {
segs.iter()
.map(|(color, text)| {
let hex = color.map(|(r, g, b)| format!("{r:02X}{g:02X}{b:02X}")).unwrap_or_default();
@@ -234,6 +241,10 @@ pub struct MinerCaps {
/// `set_tuning_config` (the firmware actively tunes by hashrate, e.g. ePIC).
/// Power targets are covered by `power_limit`.
pub hashrate_target: bool,
/// Round 18 / roadmap G3: supports selecting a named firmware preset/profile
/// via `set_tuning_config(TuningTarget::Preset)` (LuxOS profiles, VNish presets).
/// The available presets are read live into `MinerRow::presets` at scan time.
pub supports_presets: bool,
/// Whether this miner's asic-rs driver supports `upgrade_firmware`
/// (probed via `supports_upgrade_firmware()` at scan time).
pub firmware_flash: bool,
@@ -258,6 +269,7 @@ impl MinerCaps {
power_limit: self.power_limit && other.power_limit,
tuning: self.tuning && other.tuning,
hashrate_target: self.hashrate_target && other.hashrate_target,
supports_presets: self.supports_presets && other.supports_presets,
firmware_flash: self.firmware_flash && other.firmware_flash,
pools: self.pools && other.pools,
timezone: self.timezone && other.timezone,
@@ -291,6 +303,7 @@ impl MinerCaps {
|| self.power_limit
|| self.tuning
|| self.hashrate_target
|| self.supports_presets
|| self.firmware_flash
|| self.pools
|| self.timezone
@@ -382,6 +395,15 @@ pub enum HealthFacet {
Boards,
}
/// One selectable firmware preset/profile (round 18 / roadmap G3). `name` is the
/// identifier the firmware expects (e.g. LuxOS "540MHz", VNish "5560"); `pretty`
/// is an optional human summary (e.g. "2485 W ~ 111.5 TH @ 540 MHz").
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MinerPreset {
pub name: String,
pub pretty: Option<String>,
}
/// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the
/// scalar fields the table can display. Absent metrics are `None` / empty /
/// 0.0 and render as a blank cell.
@@ -441,6 +463,11 @@ pub struct MinerRow {
/// The per-board tooltip shows actual / expected (round 18 #3). Empty when the
/// firmware reports no per-board expected hashrate.
pub board_expected_hashrates: Vec<f64>,
/// Per-hashboard configured voltage (V) and frequency (MHz), index-aligned
/// with the hashboards (round 18 / roadmap G7 read side). Shown in the per-board
/// Health tooltip; 0.0 where the firmware reports no value.
pub board_voltages: Vec<f64>,
pub board_frequencies: Vec<f64>,
#[allow(dead_code)] // retained for the "slow" band; not shown as its own column
pub efficiency: f64,
pub power_w: f64,
@@ -457,6 +484,9 @@ pub struct MinerRow {
/// Current structured tuning target, rendered for display (e.g. "2832 W",
/// "96 TH/s", "preset 3550"), or None (round 17 C).
pub tuning_target_label: Option<String>,
/// The firmware's selectable named presets/profiles, read live at scan time
/// when `caps.supports_presets` (round 18 / roadmap G3). Empty otherwise.
pub presets: Vec<MinerPreset>,
/// Advertised power-target envelope in watts, when the firmware reports one
/// (round 17 C, e.g. Braiins 944-6435 W). Bounds + validate the power-target
/// prompt; `None` leaves it unbounded.
@@ -781,11 +811,22 @@ impl MinerRow {
let expected = self.board_expected_hashrates.get(i).copied().unwrap_or(0.0);
let a = hashrate_num_for(&self.algorithm, actual);
let e = hashrate_num_for(&self.algorithm, expected);
match (a, e) {
let mut s = match (a, e) {
(Some(a), Some(e)) => format!("{num} \u{00b7} {a} / {e} {unit}"),
(Some(a), None) => format!("{num} \u{00b7} {a} {unit}"),
_ => num.to_string(),
};
// Per-board configured frequency / voltage (round 18 / G7 read side),
// appended when the firmware reports them.
let freq = self.board_frequencies.get(i).copied().unwrap_or(0.0);
let volt = self.board_voltages.get(i).copied().unwrap_or(0.0);
if freq > 0.0 {
s.push_str(&format!(" \u{00b7} {freq:.0} MHz"));
}
if volt > 0.0 {
s.push_str(&format!(" \u{00b7} {volt:.2} V"));
}
s
} else {
String::new() // padding slot for fleet alignment
};
@@ -1301,7 +1342,12 @@ impl Column {
if r.board_temps.is_empty() {
if r.chip_temp_c > 0.0 { format!("{:.0}", r.chip_temp_c) } else { String::new() }
} else {
r.board_temps.iter().map(|&t| format!("{t:.0}")).collect::<Vec<_>>().join(" / ")
// 0.0 == a board with no reading; show "-" so positions align.
r.board_temps
.iter()
.map(|&t| if t > 0.0 { format!("{t:.0}") } else { "-".to_string() })
.collect::<Vec<_>>()
.join(" / ")
}
}
Column::FluidTemp => num(r.fluid_temp_c, 1, " C"),
@@ -1539,20 +1585,35 @@ impl ViewState {
/// into `order`, leaving hidden columns in their existing slots, so a
/// reorder while some column is hidden never drops or duplicates a column.
pub fn apply_visible_reorder(&mut self, new_visible: &[Column]) {
let disp = self.display_columns();
if new_visible.len() != disp.len() || new_visible.first() != Some(&Column::Ip) {
return;
if new_visible.first() != Some(&Column::Ip) {
return; // Ip is fixed first
}
let want: HashSet<Column> = disp.iter().copied().collect();
let got: HashSet<Column> = new_visible.iter().copied().collect();
if want != got {
return; // not a permutation of the visible columns: ignore
let shown: HashSet<Column> = new_visible.iter().copied().collect();
if shown.len() != new_visible.len() {
return; // duplicates: not a permutation
}
// `new_visible` is the set of columns the table actually SHOWS in their new
// order. That is `display_columns()` normally, but a SUBSET of it when
// auto-hide-empty is on (the widget omits the empty columns). Every shown
// column must be a real, currently-visible column; columns not in `shown`
// (hidden, or hidden-because-empty) keep their slot. Reordering just the
// shown subset is what lets drag-reorder work while a column is hidden
// (round 18 #12: the old code compared against display_columns() and so
// silently rejected every reorder whenever auto-hide-empty hid a column).
let reorderable: HashSet<Column> = self
.order
.iter()
.copied()
.filter(|c| *c == Column::Ip || self.visible.contains(c))
.collect();
if !shown.is_subset(&reorderable) {
return; // a non-visible column in the input: ignore
}
let mut next = new_visible.iter().copied();
self.order = self
.order
.iter()
.map(|&c| if want.contains(&c) { next.next().unwrap_or(c) } else { c })
.map(|&c| if shown.contains(&c) { next.next().unwrap_or(c) } else { c })
.collect();
}
@@ -2296,6 +2357,31 @@ mod tests {
assert_eq!(view.order, before, "a same-length non-permutation must be ignored");
}
#[test]
fn apply_visible_reorder_accepts_a_shown_subset() {
// Auto-hide-empty shows only a subset of the visible columns; dragging
// within that subset must be applied, not silently rejected (round 18 #12).
let mut view = ViewState::default();
let disp = view.display_columns();
assert!(disp.len() >= 4, "default view has several visible columns");
// Pretend disp[2] is empty and therefore hidden by the widget.
let dropped = disp[2];
let mut shown: Vec<Column> = disp.iter().copied().filter(|&c| c != dropped).collect();
shown.swap(1, 2); // reorder two columns of the shown subset
let before_set: HashSet<Column> = view.order.iter().copied().collect();
view.apply_visible_reorder(&shown);
assert_ne!(
view.display_columns().iter().copied().collect::<Vec<_>>(),
disp,
"a valid subset reorder must change the display order"
);
// No column lost or duplicated; Ip still first; the hidden column kept its slot.
assert_eq!(view.order.iter().copied().collect::<HashSet<_>>(), before_set);
assert_eq!(view.order.len(), before_set.len());
assert_eq!(view.display_columns().first(), Some(&Column::Ip));
assert_eq!(view.order.iter().filter(|&&c| c == dropped).count(), 1);
}
/// Microbenchmark: the DEFAULT view (Ip ascending) at 5000 rows. The existing
/// bench_view_pipeline overrides sort to Hashrate, so it never exercised the
/// default path (previously a lexical string sort).
@@ -2436,6 +2522,7 @@ mod tests {
power_limit: true,
tuning: true,
hashrate_target: true,
supports_presets: true,
firmware_flash: true,
pools: true,
timezone: true,
+1
View File
@@ -200,6 +200,7 @@ fn compact_upper(s: &str) -> String {
/// model era/class (best-effort, since the network data can't distinguish them):
/// - Xilinx: S17/T17-era -> C49, otherwise (S19-era) -> C55.
/// - AMLogic: XP-class / S19k (140mm fans) -> CBE, otherwise (120mm) -> C76.
///
/// `clean_model` is the already-cleaned model name (used for the era/class test).
pub fn control_board_code(make: &str, board_name: &str, clean_model: &str) -> String {
let (cpu, code) = control_board_split(make, board_name, clean_model);
+58 -31
View File
@@ -1,8 +1,8 @@
//! Dropdown presets + user-saved values for the Configure-pools dialog (round 15
//! #1). Each pool field (address / account / worker / password) has a "+" menu
//! offering built-in presets (pool stratums, worker placeholders) plus values the
//! user has saved, and the user can add the current box value to the saved list.
//! Saved lists persist one-per-line under the config dir.
//! user has saved. "Add new..." opens a manager window that edits the whole saved
//! list at once (round 18 #8b). Saved lists persist one-per-line under the config dir.
use std::path::PathBuf;
@@ -72,42 +72,47 @@ pub fn load_saved(field: PoolField) -> Vec<String> {
.unwrap_or_default()
}
/// Add `value` to `field`'s saved list (deduplicated, no-op if empty/already
/// present or already a preset). Returns true if it was newly added.
pub fn add_saved(field: PoolField, value: &str) -> bool {
let value = value.trim();
if value.is_empty() {
return false;
}
if field.presets().iter().any(|p| *p == value) {
return false;
}
let mut saved = load_saved(field);
if saved.iter().any(|s| s == value) {
return false;
}
saved.push(value.to_string());
/// Replace `field`'s entire saved list with `values` (round 18 #8b: the preset
/// manager edits the whole list at once). Each value is trimmed; empties, exact
/// duplicates, and any value that is already a built-in preset are dropped.
/// Returns the number of values actually written.
pub fn save_all(field: PoolField, values: &[String]) -> std::io::Result<usize> {
let out = dedupe_saved(&field.presets(), values);
let p = config_path(field.saved_file());
if let Some(dir) = p.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = std::fs::write(p, saved.join("\n"));
true
std::fs::write(&p, out.join("\n"))?;
// The password list can hold a pool password; keep every saved list owner-only
// (round 18 #12).
restrict_permissions(&p);
Ok(out.len())
}
/// Remove `value` from `field`'s saved list (round 16 #5). Returns true if it was
/// present and removed. Presets cannot be removed (they are not in the saved file).
pub fn remove_saved(field: PoolField, value: &str) -> bool {
let value = value.trim();
let mut saved = load_saved(field);
let before = saved.len();
saved.retain(|s| s != value);
if saved.len() == before {
return false;
/// Best-effort tighten a config file to owner-only (0600) on Unix. A no-op
/// elsewhere; a failure is ignored (the file still exists, just not restricted).
fn restrict_permissions(path: &std::path::Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
let p = config_path(field.saved_file());
let _ = std::fs::write(p, saved.join("\n"));
true
#[cfg(not(unix))]
let _ = path;
}
/// Trim every value, then drop empties, values equal to a built-in preset, and
/// later exact duplicates (first occurrence wins). Order is otherwise preserved.
fn dedupe_saved(presets: &[&str], values: &[String]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for v in values {
let v = v.trim();
if v.is_empty() || presets.contains(&v) || out.iter().any(|s| s == v) {
continue;
}
out.push(v.to_string());
}
out
}
/// The full dropdown list for a field: presets first, then the user's saved
@@ -129,3 +134,25 @@ pub fn dropdown_entries(field: PoolField) -> Vec<(String, String)> {
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
let presets = ["x", "{ip1}"];
let vals: Vec<String> = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"]
.iter()
.map(|s| s.to_string())
.collect();
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
// "keep" all drop; " keep " is trimmed and kept.
assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]);
}
#[test]
fn dedupe_saved_empty_input_is_empty() {
assert!(dedupe_saved(&[], &[]).is_empty());
}
}
+133 -36
View File
@@ -4,7 +4,7 @@
//! (the stock image is retained on-device at install time; no image is uploaded):
//! - VNish: POST /api/v1/unlock -> bearer -> POST /api/v1/firmware/remove
//! - LuxOS: luxminer :4028 {"command":"logon"} -> SessionID ->
//! {"command":"uninstallluxos","parameter":"<SessionID>"}
//! {"command":"uninstallluxos","parameter":"<SessionID>"}
//! - Braiins: SSH `uninstall.sh` (re-flashes the on-NAND stock backup)
//!
//! DESTRUCTIVE: this removes the running aftermarket firmware and reboots the
@@ -24,17 +24,21 @@ use std::time::Duration;
use crate::scan::fake_scan_enabled;
pub enum RestoreMsg {
Started { total: usize },
Started,
Result { ip: String, ok: bool, detail: String },
Done { total: usize },
Done,
}
pub struct RestoreHandle {
pub rx: Receiver<RestoreMsg>,
// The worker honours cancellation between miners (see `tc` below); a UI stop
// control is not wired yet, so the handle-side trigger is kept for when it is.
#[allow(dead_code)]
cancel: Arc<AtomicBool>,
}
impl RestoreHandle {
#[allow(dead_code)]
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
@@ -57,11 +61,10 @@ pub fn start_restore(
) -> RestoreHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let total = targets.len();
if fake_scan_enabled() {
// Offline demo: report each target as restored without touching anything.
let _ = tx.send(RestoreMsg::Started { total });
let _ = tx.send(RestoreMsg::Started);
for t in targets {
let _ = tx.send(RestoreMsg::Result {
ip: t.ip,
@@ -69,7 +72,7 @@ pub fn start_restore(
detail: "restored to stock (demo)".into(),
});
}
let _ = tx.send(RestoreMsg::Done { total });
let _ = tx.send(RestoreMsg::Done);
return RestoreHandle { rx, cancel };
}
@@ -77,7 +80,7 @@ pub fn start_restore(
let _ = std::thread::Builder::new()
.name("restore-stock".into())
.spawn(move || {
let _ = tx.send(RestoreMsg::Started { total });
let _ = tx.send(RestoreMsg::Started);
for t in targets {
if tc.load(Ordering::Relaxed) {
break;
@@ -87,7 +90,7 @@ pub fn start_restore(
return;
}
}
let _ = tx.send(RestoreMsg::Done { total });
let _ = tx.send(RestoreMsg::Done);
});
RestoreHandle { rx, cancel }
}
@@ -107,10 +110,13 @@ fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &s
/// VNish: unlock -> bearer -> firmware/remove (self-restores + reboots ~3 s).
fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
// serde-encode the body so a password with a quote/backslash can't break or
// inject into the JSON (round 18 #12).
let body = serde_json::json!({ "pw": pass }).to_string();
let unlock = match curl(&[
"-s", "--connect-timeout", "5", "--max-time", "9",
"-X", "POST", "-H", "Content-Type: application/json",
"-d", &format!("{{\"pw\":\"{pass}\"}}"),
"-d", &body,
&format!("http://{ip}/api/v1/unlock"),
]) {
Ok(s) => s,
@@ -152,7 +158,9 @@ fn restore_luxos(ip: &str) -> (bool, String) {
let Some(session) = session.filter(|s| !s.is_empty()) else {
return (false, format!("no SessionID in logon response: {}", logon.trim()));
};
let cmd = format!("{{\"command\":\"uninstallluxos\",\"parameter\":\"{session}\"}}");
// serde-encode so the miner-supplied SessionID can't break or inject into the
// JSON-RPC command (round 18 #12).
let cmd = serde_json::json!({ "command": "uninstallluxos", "parameter": session }).to_string();
match lux_rpc(ip, &cmd) {
// Code 350 "Uninstalling LuxOS"; the miner reboots + reverts in background.
Ok(resp) if resp.contains("350") || resp.to_lowercase().contains("uninstall") => {
@@ -169,28 +177,30 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
return (false, "Braiins restore needs an SSH password (set the SSH login)".into());
}
let target = format!("{user}@{ip}");
// uninstall.sh is on Braiins OS+'s PATH; run it non-interactively.
// sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it
// never shows up in the process list (round 18 #12). Host-key checking is
// deliberately disabled: these are LAN miners whose SSH host key changes on
// every reflash, so pinning it would break the very revert this performs.
// BatchMode stops any interactive prompt from hanging out the 60 s cap.
let mut cmd = Command::new("sshpass");
cmd.arg("-p").arg(pass).arg("ssh");
cmd.env("SSHPASS", pass);
cmd.arg("-e").arg("ssh");
cmd.args([
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=8",
&target,
"uninstall.sh || /sbin/uninstall.sh",
]);
match run_with_timeout(cmd, Duration::from_secs(60)) {
Ok(out) => {
let s = String::from_utf8_lossy(&out).to_lowercase();
if s.contains("not found") || s.contains("no such") {
(false, "uninstall.sh not found on the miner".into())
} else {
(true, "ran uninstall.sh (reverts to stock + reboots)".into())
}
}
Ok(out) => classify_braiins(
&String::from_utf8_lossy(&out.stdout),
&String::from_utf8_lossy(&out.stderr),
out.code,
out.timed_out,
),
Err(e) => {
// A reboot mid-command commonly drops the SSH connection; treat a
// connection-closed error after the command as likely success.
if e.contains("closed") || e.contains("reset") || e.contains("timed out") {
(true, "SSH dropped (miner likely rebooting to stock)".into())
} else {
@@ -200,6 +210,42 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
}
}
/// Decide a Braiins `uninstall.sh` outcome from its captured output. The critical
/// rule (round 18 #12): an SSH auth/connection failure -- which writes its
/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be
/// reported as a FAILURE, never a false success. A dropped connection or a
/// timeout after the command started is the expected signature of the reboot.
fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bool) -> (bool, String) {
let err = stderr.to_lowercase();
// ssh's own connection/auth failures (exit 255) never reach the remote command.
let conn_fail = [
"permission denied",
"connection refused",
"could not resolve",
"no route to host",
"connection timed out",
"operation timed out",
"host key verification failed",
"before authentication",
]
.iter()
.any(|m| err.contains(m));
if conn_fail {
let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty());
return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error")));
}
let out = stdout.to_lowercase();
if out.contains("not found") || out.contains("no such") || err.contains("not found") {
return (false, "uninstall.sh not found on the miner".into());
}
match code {
Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()),
None => (true, "SSH dropped (miner likely rebooting to stock)".into()),
_ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()),
Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())),
}
}
/// One luxminer :4028 request/response (line-framed, socket closes after reply).
fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?;
@@ -225,50 +271,101 @@ fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
}
/// curl with a wall-clock cap (small responses; no pipe-drain thread needed).
/// The captured result of a timed subprocess run.
struct CmdOutput {
/// The process exit code, or `None` if it was killed / dropped / timed out.
code: Option<i32>,
stdout: Vec<u8>,
stderr: Vec<u8>,
timed_out: bool,
}
/// curl with a wall-clock cap. Errors only when the run produced no output and
/// timed out (a black-holed host); otherwise returns stdout even on a non-zero
/// exit (curl prints useful bodies/status on failures).
fn curl(args: &[&str]) -> Result<String, String> {
let mut cmd = Command::new("curl");
cmd.args(args);
run_with_timeout(cmd, Duration::from_secs(15)).map(|o| String::from_utf8_lossy(&o).into_owned())
let out = run_with_timeout(cmd, Duration::from_secs(15))?;
if out.timed_out && out.stdout.is_empty() {
return Err("timed out".into());
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
/// Run a command, capture stdout, with a hard wall-clock timeout.
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Result<Vec<u8>, String> {
/// Run a command with a hard wall-clock timeout, capturing stdout, stderr, and
/// the exit code. Both pipes are drained on their own threads so a child that
/// writes a lot to stderr can never deadlock against a full pipe (round 18 #12).
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Result<CmdOutput, String> {
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?;
let mut stdout = child.stdout.take().ok_or("no stdout")?;
let reader = std::thread::spawn(move || {
let mut stderr = child.stderr.take().ok_or("no stderr")?;
let out_reader = std::thread::spawn(move || {
let mut b = Vec::new();
let _ = stdout.read_to_end(&mut b);
b
});
let err_reader = std::thread::spawn(move || {
let mut b = Vec::new();
let _ = stderr.read_to_end(&mut b);
b
});
let start = std::time::Instant::now();
let mut timed_out = false;
loop {
let status = loop {
match child.try_wait().map_err(|e| e.to_string())? {
Some(_) => break,
Some(s) => break Some(s),
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait(); // reap so we never leave a zombie
timed_out = true;
break;
break None;
}
std::thread::sleep(Duration::from_millis(50));
}
}
}
let out = reader.join().unwrap_or_default();
if timed_out && out.is_empty() {
return Err("timed out".into());
}
Ok(out)
};
Ok(CmdOutput {
code: status.and_then(|s| s.code()),
stdout: out_reader.join().unwrap_or_default(),
stderr: err_reader.join().unwrap_or_default(),
timed_out,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn braiins_auth_or_connection_failure_is_not_a_false_success() {
// The critical regression guard (round 18 #12): a wrong password or an
// unreachable miner writes to stderr, leaves stdout empty, and exits
// non-zero -- it must report failure, never "restored".
let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false);
assert!(!ok, "wrong password must not report success");
assert!(msg.to_lowercase().contains("ssh failed"), "{msg}");
let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false);
assert!(!ok, "unreachable miner must not report success");
let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false);
assert!(!ok, "unresolvable host must not report success");
// Genuine outcomes.
let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false);
assert!(ok, "clean exit 0 is success");
let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false);
assert!(ok, "connection dropped mid-command (reboot) is success");
let (ok, _) = classify_braiins("", "", None, true);
assert!(ok, "timeout after the command started (reboot) is success");
let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false);
assert!(!ok, "missing uninstall.sh is a failure");
}
#[test]
fn firmware_selects_the_right_flow() {
// The dispatcher only recognises the three revertible aftermarket
+112 -28
View File
@@ -13,6 +13,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
// `Row` is the common variant (one per miner) while `Started`/`Done` are sent
// once each, so boxing the large row to shrink the rare variants would add an
// allocation on the hot path for no real gain -- the message is moved straight
// through an mpsc channel and dropped.
#[allow(clippy::large_enum_variant)]
pub enum ScanMsg {
/// A new scan started: `total` addresses to probe, and the exact set of
/// target IPs (as strings) so the UI can drop miners no longer in range.
@@ -156,7 +161,7 @@ pub fn parse_line(line: &str) -> Result<Vec<Ipv4Addr>, String> {
if parts.len() == 4 && parts.iter().all(|p| is_octet_spec(p)) {
let r: Vec<(u8, u8)> =
parts.iter().map(|p| parse_octet_spec(p)).collect::<Result<_, String>>()?;
let count: u64 = r.iter().map(|(lo, hi)| (*hi as u64 - *lo as u64 + 1)).product();
let count: u64 = r.iter().map(|(lo, hi)| *hi as u64 - *lo as u64 + 1).product();
if count > MAX_ADDRS {
return Err(format!("range too large (> {MAX_ADDRS} addresses): {line}"));
}
@@ -403,31 +408,41 @@ pub fn start_scan(lines: Vec<String>, timeout_secs: u64) -> ScanHandle {
}
};
}
// scan_stream_with_ip yields one item per probed address, so we
// get accurate progress plus the responders.
let mut stream = factory.scan_stream_with_ip();
// scan_stream_with_ip yields one item per probed address (identification
// is already concurrent up to SCAN_CONCURRENCY_LIMIT). Each responder's
// telemetry (to_row -> get_data + presets: several REST calls) is then
// run concurrently via buffer_unordered instead of awaited one at a time
// -- otherwise the telemetry serialises and dominates the scan wall-clock
// (round 18 #12). buffer_unordered polls the underlying stream on its own,
// so identification concurrency is unaffected, and telemetry only ever
// targets responders (live miners), so the same cap is safe.
let mut done = 0usize;
// Emit progress per address for a smoothly-climbing counter; only a
// very large scan (> 5000 addresses) is throttled, to bound channel
// traffic. The UI coalesces these to one gauge update per refresh.
let step = (total / 5000).max(1);
while let Some((ip, miner)) = stream.next().await {
let mut results = factory
.scan_stream_with_ip()
.map(|(ip, miner)| async move {
match miner {
// Only surface a row for an address that actually has a miner
// behind it; a non-responding address is never a phantom row.
Some(m) => (ip, Some(to_row(&*m).await)),
None => (ip, None),
}
})
.buffer_unordered(SCAN_CONCURRENCY_LIMIT);
while let Some((ip, row)) = results.next().await {
if thread_cancel.load(Ordering::Relaxed) {
return; // Stop / re-scan requested
}
done += 1;
// Only surface a row for an address that actually has a miner
// behind it. A non-responding address is not shown -- we never
// fabricate a phantom "offline" row for an empty IP; a miner is
// reported as "not hashing" only when it responds and we can see
// it is not mining.
if let Some(m) = miner {
let row = to_row(&*m).await;
if let Some(row) = row {
if tx.send(ScanMsg::Row(row)).is_err() {
return; // UI gone
}
}
if done % step == 0 || done == total {
if done.is_multiple_of(step) || done == total {
let _ = tx.send(ScanMsg::Progress { done, total, ip: ip.to_string() });
}
}
@@ -569,6 +584,7 @@ mod board_index_tests {
/// generation (S21 family, T21), where Bitmain dropped the per-board PIC.
/// - PIC: the rest of the S19 line (BM1362/BM1366, PIC16F1704/1542).
/// - unknown: everything else (older Antminers, non-Antminer makes).
///
/// The one genuinely ambiguous model is the plain "S19j Pro" (both PIC and noPIC
/// revisions exist); it is assumed PIC unless the model string says noPIC.
fn infer_pic(model: &str) -> Option<bool> {
@@ -638,17 +654,26 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
// alarmingly high and didn't match the temperature the miner itself reports;
// the board temperature (~60-79C) is the figure the miner's own UI shows
// (round 12 #3). Falls back to the chip temp when no board temp is reported.
let board_temps: Vec<f64> = data
.hashboards
.iter()
.filter_map(|b| {
b.board_temperature
.as_ref()
.or(b.outlet_chip_temperature.as_ref())
.map(|t| t.as_celsius())
})
.filter(|&t| t > 0.0)
.collect();
// Index-aligned with the hashboards (index i == board i): a board with no
// reading is 0.0, NOT dropped, so a missing middle board can't shift the
// others left in the "77 / - / 74" Chip-temp cell (round 18 #12). Collapsed
// to empty when NO board reports a temperature, so the cell falls back to the
// fleet average instead of showing "- / - / -".
let board_temps: Vec<f64> = {
let v: Vec<f64> = data
.hashboards
.iter()
.map(|b| {
b.board_temperature
.as_ref()
.or(b.outlet_chip_temperature.as_ref())
.map(|t| t.as_celsius())
.filter(|&t| t > 0.0)
.unwrap_or(0.0)
})
.collect();
if v.iter().all(|&t| t <= 0.0) { Vec::new() } else { v }
};
// Per-board hashrate (TH/s), index-aligned with the hashboards, for the
// per-board Health tooltip (round 17 R2). Unlike board_temps this is NOT
// filtered/compacted -- index i must stay board i so the tooltip numbering
@@ -675,6 +700,18 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.unwrap_or(0.0)
})
.collect();
// Per-board configured voltage (V) and frequency (MHz), index-aligned, for the
// per-board tooltip (round 18 / roadmap G7 read side). 0.0 where unreported.
let board_voltages: Vec<f64> = data
.hashboards
.iter()
.map(|b| b.voltage.as_ref().map(|v| v.as_volts()).unwrap_or(0.0))
.collect();
let board_frequencies: Vec<f64> = data
.hashboards
.iter()
.map(|b| b.frequency.as_ref().map(|f| f.as_megahertz()).unwrap_or(0.0))
.collect();
let fan_rpms: Vec<f64> = data
.fans
.iter()
@@ -714,7 +751,11 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
// "Stock") and carry it into the version instead (round 11 #6).
let (mut firmware, mut fw_vendor) = crate::naming::firmware_family(&data.device_info.firmware);
// Bixbit/Hiveon masquerade as stock; relabel them from their cgminer signature
// so they get their own family + colour instead of "Stock" (round 17).
// so they get their own family + colour instead of "Stock" (round 17). This
// is one extra TCP probe per stock-labelled Antminer per scan (round 18 #12):
// deliberately re-run each scan rather than cached, because a miner's firmware
// can change under us between scans (a flash/restore), and the detection must
// stay current; it only fires for Antminers that still read as plain "Stock".
if data.device_info.make.eq_ignore_ascii_case("antminer") && firmware.eq_ignore_ascii_case("stock") {
if let Some(fam) = detect_aftermarket_antminer(data.ip).await {
firmware = fam.to_string();
@@ -828,12 +869,26 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
power_limit,
tuning: miner.supports_set_tuning_percent(),
hashrate_target,
supports_presets: miner.supports_presets(),
firmware_flash: miner.supports_upgrade_firmware(),
pools: miner.supports_pools_config(),
timezone: miner.supports_timezone_config(),
change_password: miner.supports_change_password(),
factory_reset: miner.supports_factory_reset(),
};
// The firmware's selectable named presets/profiles (round 18 / roadmap G3),
// read live only for miners that advertise them (LuxOS/VNish). One extra RPC
// at scan time for those miners; the default 300 s rescan makes it negligible.
let presets: Vec<crate::model::MinerPreset> = if caps.supports_presets {
miner
.get_presets()
.await
.into_iter()
.map(|p| crate::model::MinerPreset { name: p.name, pretty: p.pretty })
.collect()
} else {
Vec::new()
};
// PIC vs noPIC (round 14 #2 rework). No firmware exposes a PIC flag over the
// network -- it's a fixed hardware property of the hashboard type -- so infer
// it from the model, which every API reports. See `infer_pic`.
@@ -885,6 +940,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
model,
brand,
submodel,
presets,
mac: data.mac.map(|m| m.to_string()).unwrap_or_default(),
hostname: data.hostname.clone().unwrap_or_default(),
serial: {
@@ -913,6 +969,8 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
expected_ths,
board_hashrates,
board_expected_hashrates,
board_voltages,
board_frequencies,
efficiency: data.efficiency.unwrap_or(0.0),
power_w,
// PSU info (round 17 R5/G15; ePIC exposes it today). A reported-but-zero
@@ -976,6 +1034,7 @@ pub enum ConfigAction {
Resume,
PowerLimit(f64), // watts
HashRateTarget(f64), // TH/s -- structured hashrate target (round 17 C)
Preset(String), // named firmware profile/preset (round 18 / G3)
TuningPercent(u8),
Timezone(String), // IANA zone, e.g. "America/Edmonton" (round 17 B / G10)
ChangePassword(String), // new web/API password (round 17 B / G11)
@@ -993,6 +1052,7 @@ impl ConfigAction {
ConfigAction::Resume => "resume".into(),
ConfigAction::PowerLimit(w) => format!("power target {w:.0} W"),
ConfigAction::HashRateTarget(t) => format!("hashrate target {t:.0} TH/s"),
ConfigAction::Preset(name) => format!("preset {name}"),
ConfigAction::TuningPercent(p) => format!("tuning {p}%"),
ConfigAction::Timezone(tz) => format!("timezone {tz}"),
ConfigAction::ChangePassword(_) => "change password".into(),
@@ -1011,6 +1071,7 @@ impl ConfigAction {
ConfigAction::Resume => "resuming…".into(),
ConfigAction::PowerLimit(_) => "setting power…".into(),
ConfigAction::HashRateTarget(_) => "setting hashrate…".into(),
ConfigAction::Preset(_) => "setting preset…".into(),
ConfigAction::TuningPercent(_) => "tuning…".into(),
ConfigAction::Timezone(_) => "setting timezone…".into(),
ConfigAction::ChangePassword(_) => "changing password…".into(),
@@ -1067,6 +1128,13 @@ async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result<bool,
let scaling = miner.get_scaling_config().await.ok();
miner.set_tuning_config(cfg, scaling).await
}
ConfigAction::Preset(name) => {
use asic_rs::core::config::tuning::TuningConfig;
use asic_rs::core::data::miner::TuningTarget;
miner
.set_tuning_config(TuningConfig::new(TuningTarget::Preset(name.clone())), None)
.await
}
ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await,
ConfigAction::Timezone(tz) => {
use asic_rs::core::config::timezone::{Tz, TimezoneConfig};
@@ -1154,7 +1222,7 @@ pub fn start_config_action(ips: Vec<String>, action: ConfigAction) -> ActionHand
match outcome {
Ok(true) => (true, "ok".to_string()),
Ok(false) => (false, "refused".to_string()),
Err(e) => (false, format!("{e}")),
Err(e) => (false, e.to_string()),
}
}
Ok(None) => (false, "no miner at IP".to_string()),
@@ -1206,16 +1274,24 @@ pub fn start_pools_action(targets: Vec<PoolTarget>) -> ActionHandle {
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-pools".into()).spawn(move || {
let mut ok = 0usize;
for t in targets {
// Honour cancellation between miners, like every sibling background
// action's fake branch (round 18 #12).
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let first = t.pools.first().map(|p| p.username.clone()).unwrap_or_default();
let _ = tx.send(ActionMsg::Result {
ip: t.ip,
ok: true,
detail: format!("simulated ({} pool(s), {first})", t.pools.len()),
});
ok += 1;
}
let _ = tx.send(ActionMsg::Done { ok: total, total });
let _ = tx.send(ActionMsg::Done { ok, total });
});
if res.is_err() {
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
@@ -1289,6 +1365,10 @@ pub fn start_pools_action(targets: Vec<PoolTarget>) -> ActionHandle {
/// Progress/results from a background refresh of a specific, already-known
/// set of miners (re-poll on a timer or after a right-click "Refresh" action,
/// as opposed to `start_scan`'s full subnet sweep).
// `Row` is the common variant; boxing it to shrink the rare Started/Done/Failed
// variants would add an allocation per refreshed miner for no real gain (see the
// note on ScanMsg).
#[allow(clippy::large_enum_variant)]
pub enum RefreshMsg {
Started { total: usize },
/// A miner's telemetry was re-read successfully.
@@ -1468,7 +1548,7 @@ pub fn start_firmware_flash_action(ips: Vec<String>, image: FirmwareImage) -> Ac
match flash_one(&*miner, &image).await {
Ok(true) => (true, "ok".to_string()),
Ok(false) => (false, "refused".to_string()),
Err(e) => (false, format!("{e}")),
Err(e) => (false, e.to_string()),
}
}
}
@@ -1504,10 +1584,14 @@ pub enum AccessProbeMsg {
/// A running access probe; `stop` cancels the remaining miners.
pub struct AccessProbeHandle {
pub rx: Receiver<AccessProbeMsg>,
// The worker honours cancellation between miners; a UI stop control is not
// wired yet, so the handle-side trigger is kept for when it is.
#[allow(dead_code)]
cancel: Arc<AtomicBool>,
}
impl AccessProbeHandle {
#[allow(dead_code)]
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
+337 -85
View File
@@ -67,6 +67,7 @@ const ID_CTX_RESUME: i32 = 726;
const ID_CTX_TUNING: i32 = 727;
const ID_CTX_POWER: i32 = 728;
const ID_CTX_HASHRATE: i32 = 740; // Set hashrate target (round 17 C)
const ID_CTX_PRESET: i32 = 741; // Set firmware profile/preset (round 18 / G3)
const ID_CTX_RESTART: i32 = 729;
// Round 17 B: timezone / change-password / factory-reset config actions.
const ID_CTX_TIMEZONE: i32 = 737;
@@ -84,12 +85,18 @@ const ID_RESTORE_CANCEL: i32 = 787;
const ID_CTX_POOLS: i32 = 736;
const ID_POOLS_OK: i32 = 788;
const ID_POOLS_CANCEL: i32 = 789;
// Pool-preset manager dialog (round 18 #8b): edit the whole saved list at once.
const ID_POOL_PRESETS_SAVE: i32 = 790;
const ID_POOL_PRESETS_CANCEL: i32 = 791;
// Firmware profile/preset selector dialog (round 18 / roadmap G3).
const ID_FWPRESET_OK: i32 = 792;
const ID_FWPRESET_CANCEL: i32 = 793;
const ID_FWPRESET_CHOICE: i32 = 794;
// Pool-field "+" dropdown buttons (round 15 #1): 12 buttons (3 rows x 4 fields),
// id = base + row*4 + field. The dropdown menu items use their own id range.
const ID_POOL_PLUS_BASE: i32 = 800;
const ID_POOL_MENU_ADD: i32 = 819; // "add new" (adds current box value to the dropdown)
const ID_POOL_MENU_ADD: i32 = 819; // "Add new..." -> opens the preset-manager window (round 18 #8b)
const ID_POOL_MENU_BASE: i32 = 820; // one id per dropdown entry (820 + index)
const ID_POOL_MENU_REMOVE_BASE: i32 = 1000; // one id per removable saved entry (round 16 #5)
// Value-prompt dialog for power-limit / tuning-percent / timezone / password.
const ID_ACTION_OK: i32 = 740;
const ID_ACTION_CANCEL: i32 = 741;
@@ -279,12 +286,18 @@ fn encode_board_temps_cell(pal: &Palette, temps: &[f64], avg: f64) -> String {
let plain = if avg > 0.0 { format!("{avg:.0}") } else { String::new() };
return encode_temp_cell(pal, &plain, avg);
}
let mut segs: Vec<(Option<(u8, u8, u8)>, String)> = Vec::with_capacity(temps.len() * 2 - 1);
let mut segs: Vec<Segment> = Vec::with_capacity(temps.len() * 2 - 1);
for (i, &t) in temps.iter().enumerate() {
if i > 0 {
segs.push((None, " / ".to_string()));
}
segs.push((Some(temp_color(pal, t)), format!("{t:.0}")));
// A 0.0 slot means "this board reported no temperature"; show a dash in its
// position so the remaining boards stay aligned (round 18 #12).
if t > 0.0 {
segs.push((Some(temp_color(pal, t)), format!("{t:.0}")));
} else {
segs.push((None, "-".to_string()));
}
}
encode_segments(&segs)
}
@@ -308,9 +321,6 @@ const SHAPE_HASHING: &str = "\u{0004}";
const SHAPE_SLOW: &str = "\u{0005}";
const SHAPE_NOTHASHING: &str = "\u{0006}";
const SHAPE_PAUSED: &str = "\u{0008}";
/// Locate-light dot that fades in and out (round 12 #6); distinct from the static
/// `SHAPE_DOT` so only the flashing light pulses, not the hashboard health dots.
const SHAPE_PULSE_DOT: &str = "\u{000B}";
// Component-health icons (round 13 #3): one sentinel per component kind, each
// drawn from the operator-supplied Font Awesome SVG and recoloured per component
// state. Registered in `register_cell_icons`.
@@ -372,7 +382,7 @@ fn encode_board_dots(pal: &Palette, status: &[crate::model::BoardHealth]) -> Str
if status.is_empty() {
return encode_segments(&[(None, String::new())]);
}
let segs: Vec<(Option<(u8, u8, u8)>, String)> = status
let segs: Vec<Segment> = status
.iter()
.rev()
.map(|h| {
@@ -448,7 +458,7 @@ fn encode_component_health(
max_fans: usize,
max_boards: usize,
) -> String {
let mut segs: Vec<(Option<(u8, u8, u8)>, String)> = Vec::new();
let mut segs: Vec<Segment> = Vec::new();
segs.push((Some(health_color(pal, r.power_health())), SHAPE_BOLT.to_string()));
segs.push((Some(health_color(pal, r.control_health())), SHAPE_BRAIN.to_string()));
let fans = r.fan_healths();
@@ -528,7 +538,7 @@ fn encode_cooling_cell(pal: &Palette, fans: &[f64]) -> String {
if fans.is_empty() {
return encode_segments(&[(None, String::new())]);
}
let mut segs: Vec<(Option<(u8, u8, u8)>, String)> = Vec::with_capacity(fans.len() * 2 - 1);
let mut segs: Vec<Segment> = Vec::with_capacity(fans.len() * 2 - 1);
for (i, &rpm) in fans.iter().enumerate() {
if i > 0 {
segs.push((None, "/".to_string()));
@@ -564,7 +574,6 @@ enum ColorKind {
Green,
Amber,
Red,
Accent,
Blue,
}
@@ -574,7 +583,6 @@ fn kind_color(pal: &Palette, k: ColorKind) -> (u8, u8, u8) {
ColorKind::Green => pal.green,
ColorKind::Amber => pal.amber,
ColorKind::Red => pal.red,
ColorKind::Accent => pal.accent,
ColorKind::Blue => pal.accent,
}
}
@@ -637,6 +645,12 @@ pub struct App {
// the first time fill_rows runs with rows present, so the default widths fit
// their contents (capped) once and manual resizes afterwards are preserved.
columns_autosized: bool,
// The columns the wxDataViewCtrl was actually built with, in creation order.
// fill_rows/header_click/reorder index the widget through table_columns() and
// assume it stays in lockstep; with auto-hide-empty on, a scan can change which
// columns are non-empty, so fill_rows watches for a mismatch and rebuilds
// rather than render against stale columns (round 18 #12).
built_columns: Vec<crate::model::Column>,
table_parent: Widget,
root_sizer: Widget,
pub scan: Option<scan::ScanHandle>,
@@ -725,6 +739,11 @@ pub struct App {
fwcreds_rows: Vec<(String, Widget, Widget)>,
// Background access (lock-state) probe.
access_probe: Option<scan::AccessProbeHandle>,
// In-flight background log fetch (round 18 #12): the miner IP plus a channel
// the worker thread sends the fetched log (or an error) on, so the API log
// fetch never blocks the UI thread. Drained in tick(); builds the viewer when
// it lands.
logfetch: Option<(String, std::sync::mpsc::Receiver<Result<crate::log_scan::LogScan, String>>)>,
// The API log viewer dialog (round 12 #12).
logview_dialog: Widget,
// Settings > Logs page (round 15 #13).
@@ -742,6 +761,18 @@ pub struct App {
pool_menu_target: usize, // which field the open "+" menu edits
pool_menu_field: crate::pool_prefs::PoolField,
pool_menu_values: Vec<String>, // values behind the open menu, by item index
// The pool-preset manager dialog (round 18 #8b): a multiline editable list of
// the saved values for one field, reached from the "+" menu's "Manage saved".
pool_presets_dialog: Widget,
pool_presets_input: Widget,
pool_presets_field: crate::pool_prefs::PoolField,
// Firmware profile/preset selector (round 18 / roadmap G3): a Choice of the
// selected miner's presets, the names behind each entry, and the target IPs
// captured when the dialog opened.
fw_preset_dialog: Widget,
fw_preset_choice: Widget,
fw_preset_names: Vec<String>,
fw_preset_ips: Vec<String>,
// Saved view presets + the Presets dialog widgets.
presets: Vec<crate::presets::Preset>,
presets_dialog: Widget,
@@ -861,7 +892,8 @@ pub fn build(frame: Widget) -> App {
// (round 12 #1); it still dims with focus like the other neutral cards.
let (card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Neutral, Some(SVG_HIVE));
let (card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral, Some(SVG_BOLT));
drop(mk_card);
// (mk_card's borrow of kpi_cards ends here at its last use, freeing kpi_cards
// for the App below.)
// The two wide cards carry a units-bearing value (icon + e.g. "685 TH" /
// "21.3 kW"); give them a larger min width so the value never clips, and
// collapse them before the row would squeeze them below it (round 12 #2).
@@ -924,12 +956,12 @@ pub fn build(frame: Widget) -> App {
l10n_labels.push((b, label));
b
};
let presets_btn = tbtn("Presets", ID_PRESETS);
let filter_btn = tbtn("Filter", ID_FILTER);
let columns_btn = tbtn("Columns", ID_COLUMNS);
let export_btn = tbtn("Export", ID_EXPORT);
let _presets_btn = tbtn("Presets", ID_PRESETS);
let _filter_btn = tbtn("Filter", ID_FILTER);
let _columns_btn = tbtn("Columns", ID_COLUMNS);
let _export_btn = tbtn("Export", ID_EXPORT);
// The old Credentials button is now a Settings menu (round 15 #13).
let creds_btn = tbtn("Settings", ID_SETTINGS);
let _creds_btn = tbtn("Settings", ID_SETTINGS);
root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
// Track the KPI captions for live re-localization (index 5, the hashrate
// caption, is dynamic per-algorithm so it is refreshed by refresh_kpis).
@@ -988,6 +1020,7 @@ pub fn build(frame: Widget) -> App {
progress,
table: None,
columns_autosized: false,
built_columns: Vec::new(),
table_parent,
root_sizer: root,
scan: Some(scan::start_scan(ranges.clone(), scan::load_scan_timeout())),
@@ -1031,6 +1064,7 @@ pub fn build(frame: Widget) -> App {
fwcreds_dialog: frame,
fwcreds_rows: Vec::new(),
access_probe: None,
logfetch: None,
logview_dialog: frame,
logs_dialog: frame,
logs_text: frame,
@@ -1042,6 +1076,13 @@ pub fn build(frame: Widget) -> App {
pool_menu_target: 0,
pool_menu_field: crate::pool_prefs::PoolField::Address,
pool_menu_values: Vec::new(),
pool_presets_dialog: frame,
pool_presets_input: frame,
pool_presets_field: crate::pool_prefs::PoolField::Address,
fw_preset_dialog: frame,
fw_preset_choice: frame,
fw_preset_names: Vec::new(),
fw_preset_ips: Vec::new(),
presets: crate::presets::load_presets(),
presets_dialog: frame,
presets_choice: frame,
@@ -1176,6 +1217,10 @@ impl App {
// Re-apply the table zoom so a non-100% zoom survives this rebuild
// (round 14 #3); the fresh columns come back at their 100% widths.
wx_rs::table_zoom_reapply();
// Record exactly which columns the widget now holds, so fill_rows can
// detect an auto-hide-empty set change and rebuild rather than render
// against stale columns (round 18 #12).
self.built_columns = self.table_columns();
// Fresh columns come back at their configured default widths; let the
// next fill_rows shrink them to fit their contents (round 18 #10).
self.columns_autosized = false;
@@ -1184,12 +1229,24 @@ impl App {
pub fn fill_rows(&mut self) {
let Some(t) = self.table else { return };
// Compute the shown columns once and reuse it everywhere below (with
// auto-hide-empty on, table_columns() scans every cell of every row, so it
// must not be called per section of this function -- round 18 #12).
let cols = self.table_columns();
// If the set of shown columns has changed since the widget was built (only
// possible with auto-hide-empty on, when a scan makes a column non-empty),
// the widget's columns are stale: rendering now would misalign cells and
// header clicks. Rebuild instead -- deferred, because rebuild_table
// destroys this control (round 18 #12).
if cols != self.built_columns {
wx_rs::call_after(DEFER_TABLE);
return;
}
// Hold the scroll position across the full clear+refill so the table
// doesn't jump back to the top as new rows stream in during a scan.
let top = t.dvlc_get_top_row();
t.dvlc_clear();
self.view_idx = self.view.view(&self.rows);
let cols = self.table_columns();
for &ri in &self.view_idx {
let r = &self.rows[ri];
let cells: Vec<String> = cols.iter().map(|c| c.cell(r)).collect();
@@ -1518,6 +1575,9 @@ impl App {
if caps.hashrate_target {
menu.menu_append(ID_CTX_HASHRATE, &format!("Set hashrate target...{sfx}"));
}
if caps.supports_presets {
menu.menu_append(ID_CTX_PRESET, &format!("Set profile...{sfx}"));
}
if caps.restart {
menu.menu_append(ID_CTX_RESTART, &format!("Restart{sfx}"));
}
@@ -1575,12 +1635,6 @@ impl App {
self.fill_rows();
}
/// Clear one miner's in-flight operation label. Repaint is left to the caller
/// (usually a single fill_rows after draining a batch of results).
fn clear_op_status(&mut self, ip: &str) {
self.op_status.remove(ip);
}
/// Build (but do not show) the Configure-pools dialog (round 15 #1): three
/// pool rows, each with address + account + worker + password boxes and a "+"
/// dropdown next to each. Address/account are required per used row; the
@@ -1625,9 +1679,9 @@ impl App {
let lbl = Widget::static_text(dlg, &format!("Pool {}", row + 1));
lbl.set_min_size(46, -1);
rsizer.add(lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT, 6);
for field in 0..4usize {
for (field, &w) in widths.iter().enumerate() {
let input = Widget::text_ctrl(dlg, false);
input.set_min_size(widths[field], -1);
input.set_min_size(w, -1);
rsizer.add(input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT, 6);
let plus = Widget::button(dlg, "+", ID_POOL_PLUS_BASE + (row * 4 + field) as i32);
plus.set_min_size(PLUS_W, -1); // wide enough that the "+" glyph isn't clipped
@@ -1677,17 +1731,10 @@ impl App {
self.pool_menu_values.push(value);
}
menu.menu_append_separator();
menu.menu_append(ID_POOL_MENU_ADD, "Add new");
// Let the user remove values they previously added (round 16 #5); presets
// are built-in and stay. Listed in a submenu keyed by saved-list index.
let saved = crate::pool_prefs::load_saved(field);
if !saved.is_empty() {
let sub = Widget::menu_new();
for (i, val) in saved.iter().enumerate() {
sub.menu_append(ID_POOL_MENU_REMOVE_BASE + i as i32, val);
}
menu.menu_append_submenu("Remove saved value", sub);
}
// "Add new..." opens the preset-manager window: an editable list of all the
// saved values for this field, so the user can add, edit and remove them in
// one place (round 18 #8b -- replaces the old add-one / remove-submenu pair).
menu.menu_append(ID_POOL_MENU_ADD, "Add new...");
self.pool_menu_target = target;
self.pool_menu_field = field;
self.pending_popup = Some((self.pools_dialog, menu));
@@ -1695,29 +1742,12 @@ impl App {
/// A pool dropdown item was chosen (round 15 #1). Worker values insert at the
/// cursor (so several placeholders can be combined); other fields replace.
/// ("Add new..." is handled in on_menu_item, which opens the preset manager.)
fn choose_pool_dropdown(&mut self, id: i32) {
use crate::pool_prefs::PoolField;
let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() else {
return;
};
if id == ID_POOL_MENU_ADD {
let val = input.get_value();
if crate::pool_prefs::add_saved(self.pool_menu_field, &val) {
wx_rs::set_status_text("added to the dropdown list");
}
return;
}
// Remove a previously-saved value (round 16 #5).
if id >= ID_POOL_MENU_REMOVE_BASE {
let ri = (id - ID_POOL_MENU_REMOVE_BASE) as usize;
let saved = crate::pool_prefs::load_saved(self.pool_menu_field);
if let Some(val) = saved.get(ri) {
if crate::pool_prefs::remove_saved(self.pool_menu_field, val) {
wx_rs::set_status_text("removed from the dropdown list");
}
}
return;
}
let idx = (id - ID_POOL_MENU_BASE) as usize;
let Some(value) = self.pool_menu_values.get(idx).cloned() else {
return;
@@ -1729,6 +1759,73 @@ impl App {
}
}
/// Build (but do not show) the pool-preset manager (round 18 #8b): a multiline
/// editable list of the saved values for the field whose "+" menu is open. The
/// current box value (if non-empty and not already saved or a built-in preset)
/// is seeded as the last line, so "Add new..." pre-fills what the user typed.
fn build_pool_presets_dialog(&mut self) -> Widget {
use crate::pool_prefs::PoolField;
let field = self.pool_menu_field;
let field_name = match field {
PoolField::Address => "address",
PoolField::Account => "account",
PoolField::Worker => "worker",
PoolField::Password => "password",
};
let mut lines = crate::pool_prefs::load_saved(field);
if let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() {
let cur = input.get_value().trim().to_string();
if !cur.is_empty()
&& !lines.iter().any(|l| l == &cur)
&& !field.presets().iter().any(|p| *p == cur)
{
lines.push(cur);
}
}
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Saved {field_name} values"));
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
"One value per line. These appear in the + menu below the built-in\npresets. Edit freely, then Save.",
),
0,
sf::BORDER_ALL,
8,
);
let input = Widget::text_ctrl(dlg, true);
input.set_value(&lines.join("\n"));
input.set_min_size(360, 220);
root.add(input, 1, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Save", ID_POOL_PRESETS_SAVE), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_POOL_PRESETS_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(400, 340);
dlg.fit(dlg);
self.pool_presets_dialog = dlg;
self.pool_presets_input = input;
self.pool_presets_field = field;
dlg
}
/// Save the edited pool-preset list back to disk (round 18 #8b). Blank lines,
/// duplicates and built-in presets are dropped by pool_prefs::save_all.
fn apply_pool_presets(&mut self) {
let text = self.pool_presets_input.get_value();
let values: Vec<String> = text.lines().map(|l| l.trim().to_string()).collect();
match crate::pool_prefs::save_all(self.pool_presets_field, &values) {
Ok(n) => {
self.pool_presets_dialog.close(1);
wx_rs::set_status_text(&format!("saved {n} value(s)"));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save: {e}")),
}
}
/// Read the 3 pool rows, expand each row's worker per selected miner, and
/// start the background pool-config action (round 15 #1). Rows missing an
/// address or account are skipped; a miner with no usable rows is skipped.
@@ -1836,13 +1933,17 @@ impl App {
self.refresh = Some(scan::start_refresh(ips));
}
/// Fetch the selected miner's log over its firmware API and show it in a
/// viewer with a regex summary at the top (round 12 #12). The fetch is a
/// short blocking network call (a manual, single-miner action). Returns the
/// dialog to show, or None after reporting why no log could be read.
fn build_log_view_dialog(&mut self) -> Option<Widget> {
/// Start fetching the selected miner's log over its firmware API on a
/// background thread (round 18 #12: the fetch is a multi-second network call
/// and must never block the wx event loop). The viewer is shown when the
/// result lands, in `drain_logfetch`.
fn start_log_fetch(&mut self) {
if self.logfetch.is_some() {
wx_rs::set_status_text("a log fetch is already in progress");
return;
}
let rows = self.selected_rows();
let r = rows.first()?;
let Some(r) = rows.first() else { return };
let (ip, brand, firmware) = (r.ip.clone(), r.brand.clone(), r.firmware.clone());
// VNish unlock password + Antminer web login: a per-firmware override
// (round 12 #13) wins, else the shipped default / saved global creds.
@@ -1855,7 +1956,40 @@ impl App {
let (am_user, am_pass) =
credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
wx_rs::set_status_text(&format!("fetching log from {ip}..."));
let scan = match crate::log_scan::scan_log(&ip, &brand, &firmware, &vnish_pass, &am_user, &am_pass) {
let (tx, rx) = std::sync::mpsc::channel();
let ip_thread = ip.clone();
let spawned = std::thread::Builder::new().name("log-fetch".into()).spawn(move || {
let res = crate::log_scan::scan_log(
&ip_thread, &brand, &firmware, &vnish_pass, &am_user, &am_pass,
);
let _ = tx.send(res);
});
if spawned.is_err() {
wx_rs::set_status_text("could not start the log fetch");
return;
}
self.logfetch = Some((ip, rx));
}
/// Poll the in-flight log fetch; when it finishes, build the viewer dialog to
/// show (or report the error). Returns the dialog for `dispatch` to show
/// modally once the App borrow is released (round 18 #12).
fn drain_logfetch(&mut self) -> Option<Widget> {
let (ip, result) = {
let (ip, rx) = self.logfetch.as_ref()?;
match rx.try_recv() {
Ok(res) => (ip.clone(), res),
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
let ip = ip.clone();
self.logfetch = None;
wx_rs::set_status_text(&format!("log fetch aborted for {ip}"));
return None;
}
}
};
self.logfetch = None;
let scan = match result {
Ok(s) => s,
Err(e) => {
self.set_error_indicator(&format!("log: {e}"));
@@ -1865,6 +1999,11 @@ impl App {
};
self.clear_indicator();
wx_rs::set_status_text(&format!("{} miners", self.rows.len()));
Some(self.build_log_dialog(&ip, &scan))
}
/// Build (but do not show) the log viewer for an already-fetched log.
fn build_log_dialog(&mut self, ip: &str, scan: &crate::log_scan::LogScan) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Miner log (API) -- {ip}"));
let root = Widget::box_sizer(true);
@@ -1886,7 +2025,7 @@ impl App {
dlg.set_min_size(800, 540);
dlg.fit(dlg);
self.logview_dialog = dlg;
Some(dlg)
dlg
}
/// Confirmation before restoring aftermarket firmware to stock (round 12 #8a,
@@ -1943,6 +2082,21 @@ impl App {
/// keyword). Resolves the per-firmware credentials (VNish password from the
/// round 12 #13 defaults; Braiins SSH login from the saved SSH creds).
fn apply_restore_confirm(&mut self) {
// Restore-to-stock is destructive and needs exclusive access to the miners;
// refuse if any scan / refresh / action / flash or another restore is
// already in flight, so two operations never hit the same unit and a
// running restore handle is never orphaned by being overwritten (round 18 #12).
if self.flashing
|| self.scanning
|| self.action.is_some()
|| self.refresh.is_some()
|| self.restore.is_some()
{
wx_rs::set_status_text("busy (scan/action/restore in progress) -- try again once it finishes");
self.pending_restore.clear();
self.restore_dialog.close(0);
return;
}
let targets = std::mem::take(&mut self.pending_restore);
if targets.is_empty() {
self.restore_dialog.close(0);
@@ -1971,7 +2125,7 @@ impl App {
let mut op_clear: Vec<String> = Vec::new();
while let Ok(msg) = h.rx.try_recv() {
match msg {
restore::RestoreMsg::Started { .. } => {}
restore::RestoreMsg::Started => {}
restore::RestoreMsg::Result { ip, ok, detail } => {
op_clear.push(ip.clone());
if ok {
@@ -1980,7 +2134,7 @@ impl App {
fails.push(format!("{ip}: {detail}"));
}
}
restore::RestoreMsg::Done { .. } => done = true,
restore::RestoreMsg::Done => done = true,
}
}
for ip in &op_clear {
@@ -2089,9 +2243,12 @@ impl App {
/// A menu item was chosen. Direct actions start immediately; the value-input
/// actions (power limit / tuning %) return a prompt dialog to show modally.
fn on_menu_item(&mut self, id: i32) -> Option<Widget> {
// Pool "+" dropdown selections (round 15 #1): the "add current" item and
// one id per dropdown entry from ID_POOL_MENU_BASE up.
if id == ID_POOL_MENU_ADD || id >= ID_POOL_MENU_BASE {
// Pool "+" dropdown selections (round 15 #1). "Add new..." opens the preset
// manager (round 18 #8b, shown modally); the rest fill the box in place.
if id == ID_POOL_MENU_ADD {
return Some(self.build_pool_presets_dialog());
}
if id >= ID_POOL_MENU_BASE {
self.choose_pool_dropdown(id);
return None;
}
@@ -2113,7 +2270,7 @@ impl App {
}
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_VIEW_LOG => return self.build_log_view_dialog(),
ID_CTX_VIEW_LOG => self.start_log_fetch(),
ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(),
ID_CTX_POOLS => return self.build_pools_dialog(),
ID_CTX_FLASH => {
@@ -2136,9 +2293,7 @@ impl App {
// do inline here (unlike destroying a control) since
// `dispatch` already tolerates re-entrant events via
// try_borrow_mut while a nested loop is running.
let Some(path) = Widget::file_dialog(Widget::main_frame(), "Choose firmware image") else {
return None;
};
let path = Widget::file_dialog(Widget::main_frame(), "Choose firmware image")?;
match FirmwareImage::from_file(&path) {
Ok(image) => return Some(self.build_flash_confirm_dialog(&path, targets, image)),
Err(e) => wx_rs::set_status_text(&format!("failed to read firmware image: {e}")),
@@ -2154,6 +2309,7 @@ impl App {
// Value entry is itself the confirmation.
ID_CTX_POWER => return Some(self.build_action_prompt(PromptKind::Power)),
ID_CTX_HASHRATE => return Some(self.build_action_prompt(PromptKind::HashRateTarget)),
ID_CTX_PRESET => return self.build_fw_preset_dialog(),
ID_CTX_TUNING => return Some(self.build_action_prompt(PromptKind::Tuning)),
ID_CTX_TIMEZONE => return Some(self.build_action_prompt(PromptKind::Timezone)),
ID_CTX_PASSWORD => return Some(self.build_action_prompt(PromptKind::Password)),
@@ -2308,7 +2464,7 @@ impl App {
// A target must be positive, finite, and within the advertised range when
// one exists (round 17 C).
let in_range = |v: f64, range: Option<(f64, f64)>| {
v > 0.0 && v.is_finite() && range.map_or(true, |(a, b)| v >= a && v <= b)
v > 0.0 && v.is_finite() && range.is_none_or(|(a, b)| v >= a && v <= b)
};
let action = match self.action_kind {
PromptKind::Power => match val.trim().parse::<f64>() {
@@ -2373,6 +2529,86 @@ impl App {
}
}
/// Build (but do not show) the firmware profile/preset selector (round 18 /
/// roadmap G3). Populated live from the presets read at scan time; only the
/// profiles common (by name) to every selected preset-capable miner are
/// offered, so the chosen profile is valid on all of them. Returns None (with
/// a status hint) when there is nothing to offer.
fn build_fw_preset_dialog(&mut self) -> Option<Widget> {
let supporting: Vec<&MinerRow> = self
.selected_rows()
.into_iter()
.filter(|r| r.caps.supports_presets && !r.presets.is_empty())
.collect();
if supporting.is_empty() {
wx_rs::set_status_text("no firmware profiles available for the selection yet");
return None;
}
// Intersect the profile names across the selection so the chosen name is
// valid on every target; keep the first miner's pretty labels.
let mut common: Vec<crate::model::MinerPreset> = supporting[0].presets.clone();
for r in &supporting[1..] {
let names: std::collections::HashSet<&str> =
r.presets.iter().map(|p| p.name.as_str()).collect();
common.retain(|p| names.contains(p.name.as_str()));
}
if common.is_empty() {
wx_rs::set_status_text("selected miners share no common firmware profile");
return None;
}
self.fw_preset_ips = supporting.iter().map(|r| r.ip.clone()).collect();
self.fw_preset_names = common.iter().map(|p| p.name.clone()).collect();
let n = self.fw_preset_ips.len();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Set profile");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(dlg, &format!("Firmware profile for {n} miner(s):")),
0,
sf::BORDER_ALL,
8,
);
let choice = Widget::choice(dlg, ID_FWPRESET_CHOICE);
for p in &common {
let label = match &p.pretty {
Some(pretty) => format!("{} -- {pretty}", p.name),
None => p.name.clone(),
};
choice.choice_append(&label);
}
choice.choice_set_selection(0);
choice.set_min_size(340, -1);
root.add(choice, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Apply", ID_FWPRESET_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_FWPRESET_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(420, -1);
dlg.fit(dlg);
self.fw_preset_dialog = dlg;
self.fw_preset_choice = choice;
Some(dlg)
}
/// Apply the selected firmware profile to the captured targets (round 18 / G3).
fn apply_fw_preset(&mut self) {
let sel = self.fw_preset_choice.choice_get_selection();
let Some(name) = usize::try_from(sel)
.ok()
.and_then(|i| self.fw_preset_names.get(i))
.cloned()
else {
wx_rs::set_status_text("select a profile");
return;
};
let ips = std::mem::take(&mut self.fw_preset_ips);
self.fw_preset_dialog.close(1);
self.start_action(ips, scan::ConfigAction::Preset(name));
}
/// Strong typed confirmation before flashing firmware to hardware: the
/// operator must type FLASH exactly, on top of seeing the image's file
/// name and how many of the selected miners actually support it. Built
@@ -2489,7 +2725,8 @@ impl App {
user_input.set_min_size(150, -1);
user_input.set_value(&saved_user);
grow.add(user_input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_input = Widget::text_ctrl(dlg, false);
// Masked so a saved password is never rendered in the clear (round 18 #12).
let pass_input = Widget::password_ctrl(dlg);
pass_input.set_min_size(150, -1);
grow.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add_sizer(grow, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
@@ -2523,7 +2760,7 @@ impl App {
user_ctrl.set_min_size(150, -1);
user_ctrl.set_value(&user);
row.add(user_ctrl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_ctrl = Widget::text_ctrl(dlg, false);
let pass_ctrl = Widget::password_ctrl(dlg); // masked (round 18 #12)
pass_ctrl.set_min_size(150, -1);
pass_ctrl.set_value(&pass);
row.add(pass_ctrl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
@@ -2841,24 +3078,28 @@ impl App {
/// Called every second by the scan timer: drain scan messages, then run the
/// scan-loop scheduler (countdown to the next automatic rescan, or idle).
fn tick(&mut self) {
fn tick(&mut self) -> Option<Widget> {
self.drain_scan();
self.drain_action();
self.drain_refresh();
self.drain_access_probe();
self.drain_restore();
// A completed background log fetch yields a viewer dialog to show; return
// it so `dispatch` presents it modally after the App borrow is released
// (round 18 #12).
let to_show = self.drain_logfetch();
// The drains above run every fast tick (smooth scan progress); the
// auto-rescan scheduler + idle status only need ~1 Hz, so run them once
// per second.
self.tick_accum = self.tick_accum.wrapping_add(1);
if self.tick_accum % TICKS_PER_SEC != 0 {
return;
if !self.tick_accum.is_multiple_of(TICKS_PER_SEC) {
return to_show;
}
// The bottom-left status is for the scan only (round 15 #8): per-miner
// operation progress lives in the Health column, so operations no longer
// hold or overwrite this line -- only an active scan does.
if self.scanning {
return; // status already shows scan progress
return to_show; // status already shows scan progress
}
if self.playing && self.auto_secs > 0 {
if self.countdown > 1 {
@@ -2878,11 +3119,16 @@ impl App {
if self.playing { "auto-rescan off" } else { "paused" }
));
}
to_show
}
/// Cancel any in-flight scan, then start a fresh one over `lines`. Signalling
/// the old scan to stop before replacing it prevents two scan threads (and
/// two tokio runtimes) probing the network at once.
/// Cancel any in-flight scan, then start a fresh one over `lines`. The old
/// scan is signalled to stop and winds down cooperatively: it checks the flag
/// per address, so a handful of already-in-flight probes may still complete
/// after the new scan starts (round 18 #12). We accept that brief, bounded
/// overlap rather than block the UI by joining the old scan thread (which
/// could freeze it for up to the per-miner scan timeout); the probes target
/// live miners, so a momentary overlap is harmless.
fn begin_scan(&mut self, lines: Vec<String>) {
// Never probe the network while a firmware flash is uploading: a stray
// scan connection to a miner mid-write can interrupt/corrupt the flash.
@@ -3009,7 +3255,7 @@ impl App {
/// Apply a header-menu action to the remembered column.
fn on_header_menu(&mut self, id: i32) -> Option<Widget> {
let Some(col) = self.header_menu_col else { return None };
let col = self.header_menu_col?;
match id {
ID_HDR_SORT_ASC => {
self.view.sort = Some((col, true));
@@ -3880,6 +4126,12 @@ impl App {
}
ID_POOLS_OK => self.apply_pools(),
ID_POOLS_CANCEL => self.pools_dialog.close(0),
// Pool-preset manager buttons (round 18 #8b).
ID_POOL_PRESETS_SAVE => self.apply_pool_presets(),
ID_POOL_PRESETS_CANCEL => self.pool_presets_dialog.close(0),
// Firmware profile/preset selector buttons (round 18 / G3).
ID_FWPRESET_OK => self.apply_fw_preset(),
ID_FWPRESET_CANCEL => self.fw_preset_dialog.close(0),
// Pool-field "+" dropdown buttons (round 15 #1).
id if (ID_POOL_PLUS_BASE..ID_POOL_PLUS_BASE + 12).contains(&id) => {
self.open_pool_dropdown((id - ID_POOL_PLUS_BASE) as usize);
@@ -3931,7 +4183,7 @@ impl App {
WxEventKind::SysColour => self.repaint_theme(),
WxEventKind::Sized => self.on_resize(ev.p1 as i32),
WxEventKind::Deferred => self.on_deferred(ev.p1 as i32),
WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => self.tick(),
WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => return self.tick(),
_ => {}
}
None
+43
View File
@@ -0,0 +1,43 @@
# cargo-deny configuration (https://embarkstudios.github.io/cargo-deny/).
#
# Run locally with `cargo deny check`. CI's security gate is cargo-audit (lighter,
# already wired); this file documents the dependency policy and lets anyone run a
# fuller license/advisory/source check. The whole dependency set is vendored under
# ./vendor and resolved offline (see .cargo/config.toml).
[advisories]
version = 2
# Accepted, documented advisories (build-time-only reqwest 0.11 subtree of the
# wx-rs build script -- never linked into the runtime binary). Mirrors
# .cargo/audit.toml; re-review when the vendored dependency set is refreshed.
ignore = [
"RUSTSEC-2026-0258", # h2 0.3 DATA-frame DoS (build-time HTTP client only)
"RUSTSEC-2025-0134", # rustls-pemfile 1.0.4 unmaintained (same subtree)
]
[licenses]
version = 2
# The project is MIT OR Apache-2.0; only permissive licenses are allowed in the
# dependency tree.
allow = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"Unicode-3.0",
"Unicode-DFS-2016",
"MPL-2.0",
"CC0-1.0",
]
confidence-threshold = 0.9
[bans]
multiple-versions = "warn"
wildcards = "allow"
[sources]
unknown-registry = "warn"
unknown-git = "warn"
@@ -0,0 +1,159 @@
Subject: [PATCH 0022] luxminer: named presets + set_tuning_config (roadmap G3)
LuxOS tunes by discrete named profiles. This exposes them as first-class
presets and wires the structured tuning-config setter, so the toolkit can list
and select a profile (not only map a watts number onto one via SetPowerLimit).
- SupportsPresets: supports_presets()=true and get_presets() reads the live
`profiles` RPC into PresetInfo{name, pretty="<W> W ~ <TH> TH @ <MHz> MHz",
status=IsTuned?tuned:untuned}. Never hardcoded -- the step list varies by
model and tune state. New helper parse_profiles_to_presets + unit test.
- SupportsTuningConfig: supports_tuning_config()=true and set_tuning_config
handles Preset(name) -> profileset(name) (the same privileged RPC set_power_limit
already uses, proven in patch 0017) and Power(w) -> set_power_limit; hashrate /
mining-mode / manual targets are refused with clear messages.
Verified live (read) on two production LuxOS S19j Pro (10.4.1.60 / .67): the
profile ladders and supports_tuning_config=true are reported correctly. The
write path reuses the already-proven profileset(name) call; per the parity
roadmap, LuxOS profile writes are bench-only (never on the .60/.67 production
units), so the setter is not exercised against them here.
diff --git a/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs b/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs
index a4db1e03..b5a5a73c 100644
--- a/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs
+++ b/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs
@@ -5,6 +5,8 @@ use asic_rs_core::{
config::{
collector::{ConfigCollector, ConfigExtractor, ConfigField, ConfigLocation},
pools::{PoolConfig, PoolGroupConfig},
+ preset::PresetInfo,
+ tuning::TuningConfig,
},
data::{
board::{BoardData, ChipData, MinerControlBoard},
@@ -1102,6 +1104,38 @@ fn parse_profile_watts(profiles: &Value) -> Vec<(String, f64)> {
.unwrap_or_default()
}
+/// Parse a LuxOS `profiles` RPC reply into the firmware's tunable presets, one
+/// per dynamic profile (round 18 / roadmap G3). The `Profile Name` is the
+/// identifier `profileset` expects; the pretty string summarises the profile's
+/// watt / hashrate / frequency operating point, and `status` reflects `IsTuned`.
+fn parse_profiles_to_presets(profiles: &Value) -> Vec<PresetInfo> {
+ profiles
+ .get("PROFILES")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|p| {
+ let name = p.get("Profile Name").and_then(Value::as_str)?.to_string();
+ let watts = p.get("Watts").and_then(Value::as_f64);
+ let hashrate = p.get("Hashrate").and_then(Value::as_f64);
+ let freq = p.get("Frequency").and_then(Value::as_f64);
+ let pretty = match (watts, hashrate, freq) {
+ (Some(w), Some(h), Some(f)) => Some(format!("{w:.0} W ~ {h:.1} TH @ {f:.0} MHz")),
+ (Some(w), Some(h), None) => Some(format!("{w:.0} W ~ {h:.1} TH")),
+ (Some(w), None, _) => Some(format!("{w:.0} W")),
+ _ => None,
+ };
+ let status = p
+ .get("IsTuned")
+ .and_then(Value::as_bool)
+ .map(|t| if t { "tuned" } else { "untuned" }.to_string());
+ Some(PresetInfo { name, pretty, status })
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
/// Choose the LuxOS profile name to satisfy a watts power limit: the highest-watt
/// profile that does not exceed `target_w`, or -- when the target is below every
/// profile -- the lowest-watt profile. Returns None only when there are no
@@ -1284,7 +1318,38 @@ impl Validate for LuxMinerV1 {
#[async_trait]
impl SupportsTuningConfig for LuxMinerV1 {
fn supports_tuning_config(&self) -> bool {
- false
+ true
+ }
+
+ /// LuxOS tunes by named profile (roadmap G3). A `Preset` target is applied
+ /// straight through `profileset`; a `Power` target reuses the watts->profile
+ /// mapping in `set_power_limit`. LuxOS has no hashrate/mining-mode targets and
+ /// per-board manual tuning is not wired, so those targets are refused.
+ async fn set_tuning_config(
+ &self,
+ config: TuningConfig,
+ _scaling_config: Option<asic_rs_core::config::scaling::ScalingConfig>,
+ ) -> anyhow::Result<bool> {
+ match config.target {
+ TuningTarget::Preset(name) => {
+ let resp = self.rpc.profileset(&name).await?;
+ Ok(resp
+ .pointer("/STATUS/0/STATUS")
+ .and_then(Value::as_str)
+ .map(|s| matches!(s, "S" | "I"))
+ .unwrap_or(true))
+ }
+ TuningTarget::Power(p) => self.set_power_limit(p).await,
+ TuningTarget::HashRate(_) => {
+ anyhow::bail!("LuxOS does not tune by hashrate target; select a named profile")
+ }
+ TuningTarget::MiningMode(_) => {
+ anyhow::bail!("LuxOS has no mining modes; select a named profile")
+ }
+ TuningTarget::Manual { .. } => {
+ anyhow::bail!("Per-board manual tuning is not wired for LuxOS")
+ }
+ }
}
}
@@ -1299,7 +1364,21 @@ impl SupportsTemperatureConfig for LuxMinerV1 {}
impl GetTuningPercent for LuxMinerV1 {}
impl SetTuningPercent for LuxMinerV1 {}
-impl SupportsPresets for LuxMinerV1 {}
+#[async_trait]
+impl SupportsPresets for LuxMinerV1 {
+ fn supports_presets(&self) -> bool {
+ true
+ }
+
+ /// The firmware's tunable profiles, read live from the `profiles` RPC (roadmap
+ /// G3). Never hardcoded -- the step list varies by model and tune state.
+ async fn get_presets(&self) -> Vec<PresetInfo> {
+ match self.rpc.profiles().await {
+ Ok(profiles) => parse_profiles_to_presets(&profiles),
+ Err(_) => Vec::new(),
+ }
+ }
+}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
@@ -1361,6 +1440,22 @@ mod tests {
assert!(select_profile_at_or_below(&parsed, 2500.0).is_some());
}
+ #[test]
+ fn profiles_parse_to_presets() {
+ // The `profiles` reply becomes one PresetInfo per profile (roadmap G3).
+ let profiles: Value = serde_json::from_str(PROFILES).unwrap();
+ let presets = parse_profiles_to_presets(&profiles);
+ assert_eq!(presets.len(), 25, "one preset per fixture profile");
+ // The factory point is named "default"; its pretty string carries the
+ // watt / hashrate / frequency operating point.
+ let default = presets.iter().find(|p| p.name == "default").unwrap();
+ assert_eq!(default.pretty.as_deref(), Some("2794 W ~ 121.8 TH @ 590 MHz"));
+ // IsTuned maps to the status string.
+ let tuned = presets.iter().find(|p| p.name == "290MHz").unwrap();
+ assert_eq!(tuned.status.as_deref(), Some("tuned"));
+ assert_eq!(default.status.as_deref(), Some("untuned"));
+ }
+
#[tokio::test]
async fn test_luxminer_v1() -> anyhow::Result<()> {
+5
View File
@@ -39,6 +39,11 @@ version = "1.0"
[build-dependencies.embed-resource]
version = "1.3"
# reqwest is only used by build.rs to download the wxWidgets source on
# Windows/macOS; on Linux download_dist() returns before touching it, and it is
# never linked into the runtime binary. Kept at the vendored 0.11 (the build tree
# is fully vendored / offline); the h2 0.3 advisory it pulls is build-time only
# and is documented as accepted in audit.toml (RUSTSEC-2026-0258).
[build-dependencies.reqwest]
version = "0.11"
features = ["blocking"]
@@ -776,6 +776,13 @@ void* wxbr_text_ctrl(void* parent, int multiline) {
wxDefaultPosition, wxSize(-1, -1), style);
}
// 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) {
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
wxDefaultPosition, wxSize(-1, -1), wxTE_PASSWORD);
}
int wxbr_text_ctrl_get(void* win, char* buf, int cap) {
wxTextCtrl* t = (wxTextCtrl*)win;
wxString v = t->GetValue();
+6
View File
@@ -36,6 +36,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_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);
pub fn wxbr_text_ctrl_write(win: *mut c_void, value: *const c_char);
@@ -438,6 +439,11 @@ impl Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
}
/// 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) })
}
pub fn get_value(&self) -> String {
let mut buf = vec![0i8; 65536];
let n = unsafe { notsafe::wxbr_text_ctrl_get(self.0, buf.as_mut_ptr(), buf.len() as c_int) };
+1 -1
View File
@@ -1 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"fe8effe2bfdda5d4c390656c016729f531a2b1c60033228557659c0befdde9f2","Cargo.lock":"a2b2cb45bb8b574e4f29ffdcdb5ebafd1dd87a0e6e11b47383973a99be367784","Cargo.toml":"503efa00123f8567f5fe40bf6a93e9e453d13094df0e0e1b7e98bdacdfbd2595","Cargo.toml.orig":"1c4ba0315fb491c086fc22a5c9bafaf7288c6b1fd48679c3d03dbd9df156a8b5","src/backends/mod.rs":"548d988b877410e330a55e275f64b2adad95ca5f1a0f085fe144957c96b8906f","src/backends/v1/mod.rs":"0c12f7714b8486372054261afd263b61f432a446cef8ae9e6cd72550a0cf4f8f","src/backends/v1/rpc.rs":"25b0b9d56fbf113d5b8c3d3bc8eb7a0d67967b1f90f6d855da0b9f6ff24ae335","src/firmware.rs":"d95345295ae5043dfc357e69ae56c564b261fdb3b19b5c0ad1765267ff05ab3f","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"24191681066d5cf6a3022ad59c1baa92b57e3ce7717bb78d6a682af9e19a38c4","src/test/json/v1/config.json":"6ca9e6217d853d4bf1e75d69159630e9c9184ede96751706b88dfb699b5d59ad","src/test/json/v1/devs.json":"8f746dc6a02953eee5ee96dcf53be8dc7880a8ffc2c6e303f0284bcf6a97f42d","src/test/json/v1/events.json":"913683ff97af3333018807e1cc6e43467ea8a55925e5964dc402616615e2a5e3","src/test/json/v1/fans.json":"f8a9a1234d651055c80f4ebb1380bbb4e6d19eb33012902c55fff1385e592447","src/test/json/v1/healthchipget_0.json":"10619460049333ca016b2beec59ecc514ed9077fb19bdf7d0ed697201f8cb96c","src/test/json/v1/healthchipget_1.json":"80927fb1480c95be7f3a4e155d63f68f97720530ff7cf5d5ade06f2a3e810bf0","src/test/json/v1/healthchipget_2.json":"1e93ee2ab472ee7af58add08b4251e3ce0ad4f986d4325abbf43fd4c9b3dd28f","src/test/json/v1/mod.rs":"5a050f07455e622e35ad79ab1c8a6daf2ea38c4198472e49c6bbfe80538a9e48","src/test/json/v1/pools.json":"0068745327e31853fec051172abb7337f18a4cf9972c51967113d63f4f31f504","src/test/json/v1/power.json":"80534bb4581de7c8b747bf33b5d629b909c6e16a531d18ecb4afd7ffad3f014f","src/test/json/v1/profiles.json":"1f00429036e270daa08f12cd2d7357135070c57acd7a899a3c0af6167fe82abb","src/test/json/v1/stats.json":"2b105f0eb927046c9d2389bde978a43e3d54d12a420dfbe400786bb2f0ae31ca","src/test/json/v1/summary.json":"aaea3378eb7040952037e2f1ef7bd5f20a1b242bf93d4ba0501c46104b0b31a0","src/test/json/v1/temps.json":"1ee781cd2be3ed6a6a07e23be930248735fb51348c160453ba10f6ef71fcb7f1","src/test/json/v1/version.json":"4beb6ca5c0ebf359cee0434fdcc4d0a1a0607436634e46be3fd951e2256595df","src/test/json/v1/voltageget_0.json":"c445fa8674c2542b2d296fbafdd3166c53008dfbd9da8095327217989d37f1da","src/test/json/v1/voltageget_1.json":"96b91c3447dd66e7f1f575ed3b99611062e8b1d516d31422b74e425c46b2f49c","src/test/json/v1/voltageget_2.json":"7d40544021b2e32401135ae333067b770d2d736ada9e60deaca8fd8f5a79a1e3","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"513792d93a2a21d5258d9e6ac0e6dc9e0a6365118934514b4e656792add78066"}
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"fe8effe2bfdda5d4c390656c016729f531a2b1c60033228557659c0befdde9f2","Cargo.lock":"a2b2cb45bb8b574e4f29ffdcdb5ebafd1dd87a0e6e11b47383973a99be367784","Cargo.toml":"503efa00123f8567f5fe40bf6a93e9e453d13094df0e0e1b7e98bdacdfbd2595","Cargo.toml.orig":"1c4ba0315fb491c086fc22a5c9bafaf7288c6b1fd48679c3d03dbd9df156a8b5","src/backends/mod.rs":"548d988b877410e330a55e275f64b2adad95ca5f1a0f085fe144957c96b8906f","src/backends/v1/mod.rs":"abcf1ffb8443efa70838489b026730ac19de774ba9e6f7c9a9800e3ba03c06a4","src/backends/v1/rpc.rs":"25b0b9d56fbf113d5b8c3d3bc8eb7a0d67967b1f90f6d855da0b9f6ff24ae335","src/firmware.rs":"d95345295ae5043dfc357e69ae56c564b261fdb3b19b5c0ad1765267ff05ab3f","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"24191681066d5cf6a3022ad59c1baa92b57e3ce7717bb78d6a682af9e19a38c4","src/test/json/v1/config.json":"6ca9e6217d853d4bf1e75d69159630e9c9184ede96751706b88dfb699b5d59ad","src/test/json/v1/devs.json":"8f746dc6a02953eee5ee96dcf53be8dc7880a8ffc2c6e303f0284bcf6a97f42d","src/test/json/v1/events.json":"913683ff97af3333018807e1cc6e43467ea8a55925e5964dc402616615e2a5e3","src/test/json/v1/fans.json":"f8a9a1234d651055c80f4ebb1380bbb4e6d19eb33012902c55fff1385e592447","src/test/json/v1/healthchipget_0.json":"10619460049333ca016b2beec59ecc514ed9077fb19bdf7d0ed697201f8cb96c","src/test/json/v1/healthchipget_1.json":"80927fb1480c95be7f3a4e155d63f68f97720530ff7cf5d5ade06f2a3e810bf0","src/test/json/v1/healthchipget_2.json":"1e93ee2ab472ee7af58add08b4251e3ce0ad4f986d4325abbf43fd4c9b3dd28f","src/test/json/v1/mod.rs":"5a050f07455e622e35ad79ab1c8a6daf2ea38c4198472e49c6bbfe80538a9e48","src/test/json/v1/pools.json":"0068745327e31853fec051172abb7337f18a4cf9972c51967113d63f4f31f504","src/test/json/v1/power.json":"80534bb4581de7c8b747bf33b5d629b909c6e16a531d18ecb4afd7ffad3f014f","src/test/json/v1/profiles.json":"1f00429036e270daa08f12cd2d7357135070c57acd7a899a3c0af6167fe82abb","src/test/json/v1/stats.json":"2b105f0eb927046c9d2389bde978a43e3d54d12a420dfbe400786bb2f0ae31ca","src/test/json/v1/summary.json":"aaea3378eb7040952037e2f1ef7bd5f20a1b242bf93d4ba0501c46104b0b31a0","src/test/json/v1/temps.json":"1ee781cd2be3ed6a6a07e23be930248735fb51348c160453ba10f6ef71fcb7f1","src/test/json/v1/version.json":"4beb6ca5c0ebf359cee0434fdcc4d0a1a0607436634e46be3fd951e2256595df","src/test/json/v1/voltageget_0.json":"c445fa8674c2542b2d296fbafdd3166c53008dfbd9da8095327217989d37f1da","src/test/json/v1/voltageget_1.json":"96b91c3447dd66e7f1f575ed3b99611062e8b1d516d31422b74e425c46b2f49c","src/test/json/v1/voltageget_2.json":"7d40544021b2e32401135ae333067b770d2d736ada9e60deaca8fd8f5a79a1e3","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"513792d93a2a21d5258d9e6ac0e6dc9e0a6365118934514b4e656792add78066"}
+97 -2
View File
@@ -5,6 +5,8 @@ use asic_rs_core::{
config::{
collector::{ConfigCollector, ConfigExtractor, ConfigField, ConfigLocation},
pools::{PoolConfig, PoolGroupConfig},
preset::PresetInfo,
tuning::TuningConfig,
},
data::{
board::{BoardData, ChipData, MinerControlBoard},
@@ -1102,6 +1104,38 @@ fn parse_profile_watts(profiles: &Value) -> Vec<(String, f64)> {
.unwrap_or_default()
}
/// Parse a LuxOS `profiles` RPC reply into the firmware's tunable presets, one
/// per dynamic profile (round 18 / roadmap G3). The `Profile Name` is the
/// identifier `profileset` expects; the pretty string summarises the profile's
/// watt / hashrate / frequency operating point, and `status` reflects `IsTuned`.
fn parse_profiles_to_presets(profiles: &Value) -> Vec<PresetInfo> {
profiles
.get("PROFILES")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|p| {
let name = p.get("Profile Name").and_then(Value::as_str)?.to_string();
let watts = p.get("Watts").and_then(Value::as_f64);
let hashrate = p.get("Hashrate").and_then(Value::as_f64);
let freq = p.get("Frequency").and_then(Value::as_f64);
let pretty = match (watts, hashrate, freq) {
(Some(w), Some(h), Some(f)) => Some(format!("{w:.0} W ~ {h:.1} TH @ {f:.0} MHz")),
(Some(w), Some(h), None) => Some(format!("{w:.0} W ~ {h:.1} TH")),
(Some(w), None, _) => Some(format!("{w:.0} W")),
_ => None,
};
let status = p
.get("IsTuned")
.and_then(Value::as_bool)
.map(|t| if t { "tuned" } else { "untuned" }.to_string());
Some(PresetInfo { name, pretty, status })
})
.collect()
})
.unwrap_or_default()
}
/// Choose the LuxOS profile name to satisfy a watts power limit: the highest-watt
/// profile that does not exceed `target_w`, or -- when the target is below every
/// profile -- the lowest-watt profile. Returns None only when there are no
@@ -1284,7 +1318,38 @@ impl Validate for LuxMinerV1 {
#[async_trait]
impl SupportsTuningConfig for LuxMinerV1 {
fn supports_tuning_config(&self) -> bool {
false
true
}
/// LuxOS tunes by named profile (roadmap G3). A `Preset` target is applied
/// straight through `profileset`; a `Power` target reuses the watts->profile
/// mapping in `set_power_limit`. LuxOS has no hashrate/mining-mode targets and
/// per-board manual tuning is not wired, so those targets are refused.
async fn set_tuning_config(
&self,
config: TuningConfig,
_scaling_config: Option<asic_rs_core::config::scaling::ScalingConfig>,
) -> anyhow::Result<bool> {
match config.target {
TuningTarget::Preset(name) => {
let resp = self.rpc.profileset(&name).await?;
Ok(resp
.pointer("/STATUS/0/STATUS")
.and_then(Value::as_str)
.map(|s| matches!(s, "S" | "I"))
.unwrap_or(true))
}
TuningTarget::Power(p) => self.set_power_limit(p).await,
TuningTarget::HashRate(_) => {
anyhow::bail!("LuxOS does not tune by hashrate target; select a named profile")
}
TuningTarget::MiningMode(_) => {
anyhow::bail!("LuxOS has no mining modes; select a named profile")
}
TuningTarget::Manual { .. } => {
anyhow::bail!("Per-board manual tuning is not wired for LuxOS")
}
}
}
}
@@ -1299,7 +1364,21 @@ impl SupportsTemperatureConfig for LuxMinerV1 {}
impl GetTuningPercent for LuxMinerV1 {}
impl SetTuningPercent for LuxMinerV1 {}
impl SupportsPresets for LuxMinerV1 {}
#[async_trait]
impl SupportsPresets for LuxMinerV1 {
fn supports_presets(&self) -> bool {
true
}
/// The firmware's tunable profiles, read live from the `profiles` RPC (roadmap
/// G3). Never hardcoded -- the step list varies by model and tune state.
async fn get_presets(&self) -> Vec<PresetInfo> {
match self.rpc.profiles().await {
Ok(profiles) => parse_profiles_to_presets(&profiles),
Err(_) => Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
@@ -1361,6 +1440,22 @@ mod tests {
assert!(select_profile_at_or_below(&parsed, 2500.0).is_some());
}
#[test]
fn profiles_parse_to_presets() {
// The `profiles` reply becomes one PresetInfo per profile (roadmap G3).
let profiles: Value = serde_json::from_str(PROFILES).unwrap();
let presets = parse_profiles_to_presets(&profiles);
assert_eq!(presets.len(), 25, "one preset per fixture profile");
// The factory point is named "default"; its pretty string carries the
// watt / hashrate / frequency operating point.
let default = presets.iter().find(|p| p.name == "default").unwrap();
assert_eq!(default.pretty.as_deref(), Some("2794 W ~ 121.8 TH @ 590 MHz"));
// IsTuned maps to the status string.
let tuned = presets.iter().find(|p| p.name == "290MHz").unwrap();
assert_eq!(tuned.status.as_deref(), Some("tuned"));
assert_eq!(default.status.as_deref(), Some("untuned"));
}
#[tokio::test]
async fn test_luxminer_v1() -> anyhow::Result<()> {