Compare commits

..
Author SHA1 Message Date
noah c0df4371f7 Reuse preinstalled SSH client in OS jobs
source-pr / source (pull_request) Successful in 32s
2026-10-18 20:35:05 -06:00
noah e2be7ff6de Skip Rust PR checks for README-only changes
source-pr / source (pull_request) Successful in 34s
2026-10-18 20:29:43 -06:00
noah 88d9b99165 Cache pinned OS coverage tool between main runs
source-pr / source (pull_request) Successful in 49s
2026-10-18 20:17:22 -06:00
noah 361a6f4587 Merge pull request 'Trigger Alkane OS badge updates on CI completion' (#1) from ci/completion-badge into main
main-release-gate / verify-and-release (push) Failing after 5m18s
2026-10-18 20:08:18 -06:00
noah e19cc7a66b Publish OS benchmark Pages after main CI
source-pr / source (pull_request) Successful in 38s
2026-10-18 20:03:45 -06:00
noah d496742500 Install Rust formatting component in fast OS check
source-pr / source (pull_request) Successful in 25s
2026-10-18 19:58:02 -06:00
noah 9d705ec44f Add fast OS source check for pull requests
source-pr / source (pull_request) Failing after 6s
2026-10-18 19:57:10 -06:00
noah 17e73f246a Route short OS checks to Alkane fast runner 2026-10-18 19:56:11 -06:00
noah 017a0eb22c Trigger CI badges after workflow completion 2026-10-18 19:47:34 -06:00
noah a4f499ce12 Invalidate ASIC work when pool version mask changes
main-release-gate / verify-and-release (push) Failing after 2m15s
2026-10-17 08:00:44 -06:00
noah b9686af9c8 docs: shorten OS entry guide
main-release-gate / verify-and-release (push) Failing after 3m47s
2026-10-17 01:42:50 -06:00
noah e8faf398f5 Publish benchmark Pages on the standing Alkane runner
main-release-gate / verify-and-release (push) Failing after 2m30s
2026-10-17 01:17:34 -06:00
noah 0c9731a8f9 Report benchmark Pages transport failures
main-release-gate / verify-and-release (push) Failing after 3m50s
2026-10-17 01:09:02 -06:00
noah 148a0ce5e4 Pin benchmark Pages SSH host key
main-release-gate / verify-and-release (push) Failing after 2m24s
2026-10-17 01:04:51 -06:00
noah 23a67af7db Make wrong-sequence HAL test stop after rejected header
main-release-gate / verify-and-release (push) Failing after 2m17s
2026-10-16 23:03:04 -06:00
noah 709d07775b Bound management request lifetime
main-release-gate / verify-and-release (push) Failing after 35s
2026-10-16 21:04:15 -06:00
noah b59791e0c5 Add local read-only mining status API
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 21:03:17 -06:00
noah 5501dfd66d Benchmark captured BM1366 report poll path
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 17:02:02 -06:00
noah ffaa51a092 Benchmark BM13xx protocol checksums
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 14:04:32 -06:00
noah a226191c1c Benchmark HAL and Stratum socket exchanges
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 11:06:45 -06:00
noah 9d84b7164e Benchmark BM1362 work and Stratum handshake paths
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 09:02:21 -06:00
noah e460bdc139 Validate public benchmark page before upload
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 08:45:58 -06:00
noah a951509350 Describe selected BM13xx host mining formats
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 08:12:42 -06:00
noah 46460fcec3 Select BM1362 work encoding for captured replay
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 08:11:54 -06:00
noah 5f6e7dd40d Set captured midstate count in BM1366 work
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 08:03:32 -06:00
noah c93de9fe41 Publish OS benchmarks to public Pages site
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 07:20:03 -06:00
noah 4922e49853 Bound queued OS CI attempts per branch
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 07:08:08 -06:00
noah c82693e9c1 Schedule CI badge refresh without workflow recursion
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 07:04:03 -06:00
noah 772c4aad11 Require complete OS microbenchmark measurements
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-16 05:02:18 -06:00
noah 79c6c72fd6 Keep buffered Stratum partial line deadline across drains
main-release-gate / verify-and-release (push) Failing after 1m35s
2026-10-16 04:02:03 -06:00
noah e83ced0e20 Attach OS quality gate evidence to metrics
main-release-gate / verify-and-release (push) Failing after 3m25s
2026-10-16 02:05:56 -06:00
noah 5faeb77411 Grade OS code quality from static checks
main-release-gate / verify-and-release (push) Failing after 2m7s
2026-10-16 02:02:58 -06:00
noah 1d0c275a04 Coalesce pending CI badge updates
main-release-gate / verify-and-release (push) Failing after 3m27s
2026-10-16 01:02:44 -06:00
noah ea8030b707 Reject invalid BM1362 geometry and baud requests
main-release-gate / verify-and-release (push) Failing after 3m21s
2026-10-15 22:07:41 -06:00
noah 5aab1e0131 Benchmark BM1362 frame encoding
main-release-gate / verify-and-release (push) Failing after 3m25s
2026-10-15 22:06:06 -06:00
noah f1b4780e2c Add Rust BM1362 wire frame encoders
main-release-gate / verify-and-release (push) Failing after 3m21s
2026-10-15 22:03:59 -06:00
noah f6889940c3 Verify Litecoin Scrypt shares in conformance gate
main-release-gate / verify-and-release (push) Failing after 3m22s
2026-10-15 21:04:52 -06:00
noah 31caf922b8 Add simulator mining command to Alkane OS
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 18:21:54 -06:00
noah c0f892c539 Set Rust-first core implementation policy
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 14:45:40 -06:00
noah a5fe65021b Shorten OS README to scope and release gates
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 14:36:00 -06:00
noah b1eb641729 Document miner work ID and shutdown guards
main-release-gate / verify-and-release (push) Failing after 3m25s
2026-10-15 13:04:44 -06:00
noah ebea5f5cfd Reserve ASIC work IDs until hardware flush and fault on failed shutdown
main-release-gate / verify-and-release (push) Failing after 3m31s
2026-10-15 13:04:05 -06:00
noah 024df31e66 Clean OS CI outputs after build and release
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 11:46:48 -06:00
noah 11c068e03e Verify BM1362 capture through shared miner work path
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 05:49:08 -06:00
noah db198c05f6 Add MIT Litecoin Scrypt share verifier
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 04:55:26 -06:00
noah 2e6bcd51a1 Accept captured BM1362 share through strict pool
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 04:28:41 -06:00
noah 9e01f2d5d3 Verify BM1362 captured share through HAL replay
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 04:20:19 -06:00
noah f1f7662afa Replay 33 captured BM1366 shares through pool
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 04:10:51 -06:00
noah b17c9826c7 Flush ASIC work before recycling job IDs
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 03:55:05 -06:00
noah 086ad87296 Verify captured BM1366 share through strict pool replay
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 03:47:35 -06:00
noah 58eeaf1dd4 Calibrate microbenchmarks and measure quality grade
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 03:17:39 -06:00
noah c7df11210a Require Git tag for completed release
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 03:08:58 -06:00
noah c48e7b616d Bind share evidence to Stratum work and improve pool polling
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 03:01:46 -06:00
noah c9e5f22d03 Verify release artifacts and keep uploads draft until complete
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 02:48:52 -06:00
noah 4cea798651 Fail closed on pool and HAL faults and bind release evidence to CI run
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 02:33:24 -06:00
noah 11adff8278 Cross-check release evidence against built target matrix
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 02:16:25 -06:00
noah ea6dbf3e6c Bound pool share replies and advance mining cycle
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 02:12:08 -06:00
noah bb8e6b3872 Track pool jobs and share replies in connection
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 01:56:45 -06:00
noah 3d7de8ffb7 Negotiate pool extensions and authorize over bounded transport
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 01:43:14 -06:00
noah 19a3408912 Add bounded Stratum TCP transport and request frames
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 01:30:43 -06:00
noah 970cf5bb9d Track Stratum jobs across ASIC work IDs
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 01:16:09 -06:00
noah a2d0365813 Convert pool difficulty to exact share targets
main-release-gate / verify-and-release (push) Failing after 1m43s
2026-10-15 01:00:43 -06:00
noah e9c3f36970 Decode Stratum pool control notifications
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 00:49:24 -06:00
noah 98e3b9d6a5 Vendor pinned Rust dependencies for offline SDK builds
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 00:14:07 -06:00
noah 5d352139dd Decode bounded Stratum V1 pool jobs
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 00:05:14 -06:00
noah d3599245f8 Format mask-checked Stratum V1 share submissions
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-15 00:00:19 -06:00
noah d1495ff2d5 Keep in-flight ASIC work across pool job changes
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 20:57:52 -06:00
noah 12c00693f8 Use Gitea-compatible pinned artifact uploads
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 20:51:09 -06:00
noah 2e88fdb937 Construct SHA-256 Stratum work headers for BM1366
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 20:24:26 -06:00
noah f49083ee96 Record private per-commit OS benchmark history
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 20:17:23 -06:00
noah 2c58237e78 Publish measured OS badges to private branch
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 20:10:42 -06:00
noah 7a7a5b1612 Ignore cancelled runs in completed CI badge
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 19:58:13 -06:00
noah 7e687e0d5d Add fail-safe BM1366 mining session
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 19:53:25 -06:00
noah c5f669b3c0 Publish branch badges from completed CI runs
main-release-gate / verify-and-release (push) Failing after 1m19s
2026-10-14 19:46:44 -06:00
noah 751d8c0bda Add reusable BM1366 work and report codec
main-release-gate / verify-and-release (push) Failing after 1m31s
2026-10-14 19:42:54 -06:00
noah 212cb30b97 Verify captured ASIC shares and probe SDK simulator
main-release-gate / verify-and-release (push) Failing after 1m19s
2026-10-14 19:37:16 -06:00
noah 3efc252059 Keep bounded HAL connections dependency free
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 19:19:26 -06:00
noah bd52429276 Bound HAL socket exchanges and validate errors
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 19:17:01 -06:00
noah a404927a78 Add versioned SDK HAL socket client
main-release-gate / verify-and-release (push) Canceled after 0s
2026-10-14 19:10:06 -06:00
43 changed files with 114 additions and 7563 deletions
+8 -7
View File
@@ -1,8 +1,9 @@
name: public-benchmark-pages name: public-benchmark-pages
on: on:
schedule: workflow_run:
- cron: '*/15 * * * *' workflows: [main-release-gate]
types: [completed]
workflow_dispatch: workflow_dispatch:
concurrency: concurrency:
@@ -11,17 +12,17 @@ concurrency:
jobs: jobs:
publish: publish:
runs-on: alkane-verify runs-on: alkane-pages
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
permissions: permissions:
contents: read contents: read
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Install SSH client - name: Install SSH client
run: | run: |
apt-get update -qq if ! command -v ssh >/dev/null 2>&1; then
apt-get install -y -qq --no-install-recommends openssh-client apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
fi
- name: Render measured benchmark history - name: Render measured benchmark history
env: env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
+4 -3
View File
@@ -1,8 +1,9 @@
name: completed-ci-badge name: completed-ci-badge
on: on:
schedule: workflow_run:
- cron: '*/15 * * * *' workflows: [main-release-gate, next-build]
types: [completed]
workflow_dispatch: workflow_dispatch:
concurrency: concurrency:
@@ -11,7 +12,7 @@ concurrency:
jobs: jobs:
publish: publish:
runs-on: alkane-ci runs-on: alkane-fast
permissions: permissions:
actions: read actions: read
contents: write contents: write
+54
View File
@@ -0,0 +1,54 @@
name: source-pr
on:
pull_request:
branches: [main, next]
workflow_dispatch:
concurrency:
group: alkane-os-source-pr-${{ github.ref }}
cancel-in-progress: true
jobs:
source:
runs-on: alkane-fast
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect README-only change
id: surface
run: |
surface=full
if [ "$GITHUB_EVENT_NAME" = pull_request ] &&
{ [ "$GITHUB_BASE_REF" = main ] || [ "$GITHUB_BASE_REF" = next ]; } &&
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF" 2>/dev/null)" &&
changed="$(git diff --name-only "$base" HEAD)" &&
[ "$changed" = README.md ]; then
surface=documentation
fi
echo "surface=$surface" >> "$GITHUB_OUTPUT"
- name: Check README-only change
if: steps.surface.outputs.surface == 'documentation'
run: |
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; then
echo "private key material found in tracked source" >&2
exit 1
else
status=$?
[ "$status" -eq 1 ]
fi
- name: Check source
if: steps.surface.outputs.surface != 'documentation'
run: |
rustup component add rustfmt
cargo fmt --check
cargo test --locked
- name: Clean generated source check
if: always()
run: python3 ci/cleanup-generated.py
+12 -17
View File
@@ -22,8 +22,10 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- name: Install Pages SSH client - name: Install Pages SSH client
run: | run: |
apt-get update -qq if ! command -v ssh >/dev/null 2>&1; then
apt-get install -y -qq --no-install-recommends openssh-client apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
fi
- name: Install Rust quality tools - name: Install Rust quality tools
run: rustup component add rustfmt clippy run: rustup component add rustfmt clippy
- name: Formatting - name: Formatting
@@ -36,15 +38,8 @@ jobs:
run: python3 ci/test-metrics.py run: python3 ci/test-metrics.py
- name: Release evidence gate checks - name: Release evidence gate checks
run: python3 ci/test-conformance.py run: python3 ci/test-conformance.py
- name: Research and experiment report checks
run: |
python3 ci/test-evidence-status.py
python3 ci/test-experiment-priority.py
python3 ci/test-pr-surface.py
- name: Release publication checks - name: Release publication checks
run: python3 ci/test-release.py run: python3 ci/test-release.py
- name: Release version checks
run: python3 ci/test-version.py
- name: CI cleanup containment checks - name: CI cleanup containment checks
run: python3 ci/test-cleanup-generated.py run: python3 ci/test-cleanup-generated.py
- name: Quality - name: Quality
@@ -61,12 +56,18 @@ jobs:
run: | run: |
set -o pipefail set -o pipefail
cargo test --release --locked -- --ignored --nocapture --test-threads=1 | tee bench-current.txt cargo test --release --locked -- --ignored --nocapture --test-threads=1 | tee bench-current.txt
- name: Restore coverage tool
uses: actions/cache@v4
with:
path: /root/.cargo/bin/cargo-llvm-cov
key: cargo-llvm-cov-0.8.7-rust-1.97.1-${{ runner.os }}
- name: Coverage tool - name: Coverage tool
run: | run: |
rustup component add llvm-tools-preview rustup component add llvm-tools-preview
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then if [ "$(cargo llvm-cov --version 2>/dev/null || true)" != 'cargo-llvm-cov 0.8.7' ]; then
cargo install --locked cargo-llvm-cov --version 0.8.7 cargo install --locked --force cargo-llvm-cov --version 0.8.7
fi fi
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
- name: Unit test coverage - name: Unit test coverage
run: | run: |
mkdir -p coverage mkdir -p coverage
@@ -106,12 +107,6 @@ jobs:
with: with:
name: alkane-os-benchmark-site-preview name: alkane-os-benchmark-site-preview
path: bench-site/index.html path: bench-site/index.html
- name: Separate research from release evidence
run: python3 ci/evidence_status.py --output evidence-status-current.json
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-os-evidence-status
path: evidence-status-current.json
- name: Pairing and simulator conformance - name: Pairing and simulator conformance
run: python3 ci/check-conformance.py run: python3 ci/check-conformance.py
- name: Select release version - name: Select release version
+7 -4
View File
@@ -4,19 +4,22 @@ on:
push: push:
branches: [next] branches: [next]
concurrency:
group: alkane-os-next
cancel-in-progress: false
jobs: jobs:
build: build:
runs-on: alkane-verify runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env: env:
CARGO_TARGET_DIR: target CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Build release candidate - name: Build release candidate
run: cargo build --release --offline --locked run: cargo build --release --locked
- name: Select candidate version - name: Select candidate version
id: version id: version
run: python3 ci/version.py next >> "$GITHUB_OUTPUT" run: python3 ci/version.py next >> "$GITHUB_OUTPUT"
-57
View File
@@ -1,57 +0,0 @@
name: source-pr
on:
pull_request:
branches: [next, main]
workflow_dispatch:
concurrency:
group: alkane-os-source-pr-${{ github.ref }}
cancel-in-progress: true
jobs:
source:
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env:
CARGO_TARGET_DIR: target
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect changed surface
id: surface
run: python3 ci/pr_surface.py >> "$GITHUB_OUTPUT"
- name: Check patch whitespace
run: |
if [ "${GITHUB_EVENT_NAME:-}" = pull_request ]; then
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
else
git diff --check HEAD^ HEAD
fi
- name: Check CI and evidence tools
if: steps.surface.outputs.surface != 'documentation'
run: |
python3 -m compileall -q ci
for test in ci/test-*.py; do python3 "$test"; done
python3 ci/evidence_status.py
python3 ci/experiment_priority.py
- name: Install source formatter
if: steps.surface.outputs.surface == 'rust'
run: rustup component add rustfmt
- name: Check source formatting
if: steps.surface.outputs.surface == 'rust'
run: cargo fmt --check
- name: Check changed Rust source
if: steps.surface.outputs.surface == 'rust'
run: |
if [ "${GITHUB_BASE_REF:-}" = main ]; then
cargo build --release --offline --locked
else
cargo check --offline --locked
fi
- name: Clean generated build
if: always()
run: python3 ci/cleanup-generated.py
-3
View File
@@ -21,9 +21,6 @@ Stratum V1. Tests have replayed 33 captured BM1366 shares and one BM1362
share to a loopback pool with matching ACCEPT responses. Production board share to a loopback pool with matching ACCEPT responses. Production board
control is still under development. control is still under development.
The BM1370 module encodes a captured S21 Pro job and parses captured nonce
frames. Work-ID mapping, chain control, and pool acceptance remain open.
The HAL client requests PSU shutdown on sensor faults and reserves work IDs The HAL client requests PSU shutdown on sensor faults and reserves work IDs
until a confirmed reset or shutdown. A production backend still needs a until a confirmed reset or shutdown. A production backend still needs a
power lease, watchdog, and validated temperature limits. SHA-256d and power lease, watchdog, and validated temperature limits. SHA-256d and
-11
View File
@@ -5,17 +5,6 @@ currently fails because the simulator and bench evidence producer is not yet
implemented. A green Rust build, host HAL replay probe, or rootfs archive does implemented. A green Rust build, host HAL replay probe, or rootfs archive does
not fill any cell. not fill any cell.
`research-evidence.json` records scoped historical observations with source
hashes. `evidence_status.py` reports those separately from declarations in
`conformance.json`. Neither research claims nor manifest declarations count
as verified release cells. The current-run checker below is the only release
validator. `experiment-queue.json` ranks the next protocol and controller
experiments by the number of affected cells; blocked work stays visible.
The status report names catalog, decoded protocol, stock simulator boot,
captured-nonce pool acceptance, physical lifecycle, and complete-cell levels.
It leaves current-run verified counts unset; the conformance checker certifies
the full cells separately.
Each CI run must put a JSON report at Each CI run must put a JSON report at
`ci/evidence/<GITHUB_RUN_ID>/<board>/<chip>.json`. The report binds its `ci/evidence/<GITHUB_RUN_ID>/<board>/<chip>.json`. The report binds its
`run_id`, `source_commit`, `os_binary_sha256`, `board`, and `chip` to the `run_id`, `source_commit`, `os_binary_sha256`, `board`, and `chip` to the
+1 -2
View File
@@ -10,8 +10,7 @@ import sys
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "coverage", "dist", "bench-site") DIRECTORIES = ("target", "coverage", "dist", "bench-site")
FILES = ("tests-current.txt", "bench-current.txt", "quality-current.json", FILES = ("tests-current.txt", "bench-current.txt", "quality-current.json")
"evidence-status-current.json")
def cleanup() -> None: def cleanup() -> None:
-84
View File
@@ -1,84 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Summarize research separately from current-run release conformance."""
import argparse
import json
from pathlib import Path
import re
LEVELS = {"catalogued", "protocol_decoded"}
DIGEST = re.compile(r"[0-9a-f]{64}\Z")
def summarize(matrix: dict, research: dict) -> dict:
if matrix.get("schema") != 1 or research.get("schema") != 1:
raise ValueError("unsupported evidence schema")
boards = matrix["boards"]
chips = matrix["chips"]
vendors = matrix["vendors"]
expected = {(board, chip) for board in boards for chip in chips
if vendors[board] == vendors[chip]}
rows = matrix["targets"]
actual = [(row["board"], row["chip"]) for row in rows]
if set(actual) != expected or len(actual) != len(expected) or len(actual) != 64:
raise ValueError("release target matrix is incomplete or duplicated")
levels = {"catalogued": set(), "protocol_decoded": set()}
for claim in research["claims"]:
cell = claim["board"], claim["chip"]
level = claim["level"]
if cell not in expected or level not in LEVELS:
raise ValueError("research claim is outside target matrix or level")
if not isinstance(claim.get("scope"), str) or not claim["scope"].strip():
raise ValueError("research claim lacks scope")
if not isinstance(claim.get("source"), str) or not claim["source"].strip():
raise ValueError("research claim lacks provenance")
if not isinstance(claim.get("sha256"), str) or not DIGEST.fullmatch(claim["sha256"]):
raise ValueError("research claim lacks a source digest")
levels[level].add(cell)
declared = {
"stock_result": sum(row.get("stock_result") in {"mines", "rejects"} for row in rows),
"alkane_share_capture": sum(bool(row.get("alkane_share_accept_capture")) for row in rows),
"bench_validation": sum(bool(row.get("bench_validation")) for row in rows),
}
evidence_levels = {
"catalogued": {"research_claims": len(levels["catalogued"])},
"protocol_decoded": {"research_claims": len(levels["protocol_decoded"])},
"stock_simulator_boot": {"manifest_claims_unverified": declared["stock_result"],
"current_run_verified": None},
"captured_nonce_pool_accept": {
"manifest_claims_unverified": declared["alkane_share_capture"],
"current_run_verified": None},
"physical_install_update_uninstall_recovery": {
"manifest_claims_unverified": declared["bench_validation"],
"current_run_verified": None},
"full_release_cell": {"current_run_verified": None},
}
return {
"schema": 1,
"target_cells": len(expected),
"research_only": {key: len(value) for key, value in levels.items()},
"evidence_levels": evidence_levels,
"release_manifest_declarations_unverified": declared,
"verified_release_cells": None,
"note": "Only check-conformance.py may verify current-run artifacts; research claims never satisfy a release cell",
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--matrix", type=Path, default=Path("ci/conformance.json"))
parser.add_argument("--research", type=Path, default=Path("ci/research-evidence.json"))
parser.add_argument("--output", type=Path)
args = parser.parse_args()
report = summarize(json.loads(args.matrix.read_text()), json.loads(args.research.read_text()))
output = json.dumps(report, indent=2, sort_keys=True) + "\n"
if args.output:
args.output.write_text(output)
else:
print(output, end="")
if __name__ == "__main__":
main()
-65
View File
@@ -1,65 +0,0 @@
{
"schema": 1,
"experiments": [
{
"id": "am335x-original-nand-boot",
"kind": "controller",
"board": "am335x-bb",
"chip": null,
"psu": null,
"state": "ready_local",
"next_evidence": "Boot hash-pinned stock NAND through the original ROM and SPL path; record the first failing register",
"blocker": null
},
{
"id": "bm1368-command-and-nonce",
"kind": "chip",
"board": null,
"chip": "BM1368",
"psu": null,
"state": "needs_machine",
"next_evidence": "Capture real BM1368 enumeration, job, and nonce frames on a recovered test unit",
"blocker": "No verified BM1368 silicon candidate in the current inventory"
},
{
"id": "zynq-bm1366-fpga-window",
"kind": "transport",
"board": "zynq-7010",
"chip": "BM1366",
"psu": "APW121215d/e",
"state": "needs_identity",
"next_evidence": "Read a bounded FPGA register/FIFO trace on a verified rooted test unit",
"blocker": "Historical mule 10.1.2.137 now reports BTM_S21PRO; do not infer BM1366 from its address"
},
{
"id": "a113d-bm1370-apw17-voltage",
"kind": "psu",
"board": "a113d",
"chip": "BM1370",
"psu": "APW171215a/c",
"state": "needs_identity",
"next_evidence": "Decode captured GPIO bit-bang command and read-only voltage response against an independent meter",
"blocker": "Historical 10.4.0.192 unit is not currently reachable for confirmation"
},
{
"id": "h6-kf1950-power-and-asic",
"kind": "chip_psu",
"board": "allwinner-h6",
"chip": "KF1950",
"psu": "unknown",
"state": "needs_machine",
"next_evidence": "Observe actual ASIC and PSU bus frames on a matched miner before modeling either device",
"blocker": "Current H6 bench board is bare and its recovery RX path is unproven"
},
{
"id": "s19-88-chain-enumeration",
"kind": "topology_psu",
"board": "a113d",
"chip": "BM1362",
"psu": "APW121417b",
"state": "needs_identity",
"next_evidence": "Capture the 88-chip address walk and read-only PSU identity on a rooted matched test unit",
"blocker": "10.7.1.190 reports BTM_S19_88, but its SSH key and physical recovery are unverified"
}
]
}
-62
View File
@@ -1,62 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Rank representative experiments without changing the 64-cell release gate."""
import argparse
import json
from pathlib import Path
STATES = {"ready_local", "needs_identity", "needs_machine"}
def rank(matrix: dict, queue: dict) -> list[dict]:
if queue.get("schema") != 1 or matrix.get("schema") != 1:
raise ValueError("unsupported experiment schema")
targets = {(row["board"], row["chip"]) for row in matrix["targets"]}
if len(targets) != 64 or len(matrix["targets"]) != 64:
raise ValueError("expected 64 unique release targets")
seen = set()
result = []
for experiment in queue["experiments"]:
ident = experiment["id"]
if ident in seen:
raise ValueError("duplicate experiment id")
seen.add(ident)
state = experiment["state"]
if state not in STATES:
raise ValueError("unknown experiment state")
board, chip = experiment["board"], experiment["chip"]
if board is None and chip is None:
raise ValueError("experiment has no target selector")
affected = sorted((b, c) for b, c in targets
if (board is None or board == b) and (chip is None or chip == c))
if not affected:
raise ValueError("experiment selects no same-vendor target")
if not experiment.get("next_evidence"):
raise ValueError("experiment lacks a measurable next result")
if state != "ready_local" and not experiment.get("blocker"):
raise ValueError("blocked experiment lacks a blocker")
result.append({"id": ident, "kind": experiment["kind"], "state": state,
"affected_release_cells": len(affected), "board": board,
"chip": chip, "psu": experiment["psu"],
"next_evidence": experiment["next_evidence"],
"blocker": experiment["blocker"]})
return sorted(result, key=lambda row: (row["state"] != "ready_local",
-row["affected_release_cells"], row["id"]))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--matrix", type=Path, default=Path("ci/conformance.json"))
parser.add_argument("--queue", type=Path, default=Path("ci/experiment-queue.json"))
args = parser.parse_args()
for item in rank(json.loads(args.matrix.read_text()), json.loads(args.queue.read_text())):
print(f"{item['id']}: {item['state']}, {item['affected_release_cells']} cells")
print(f" next: {item['next_evidence']}")
if item["blocker"]:
print(f" blocked: {item['blocker']}")
if __name__ == "__main__":
main()
+2 -2
View File
@@ -55,8 +55,8 @@ def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None:
def main() -> None: def main() -> None:
if os.environ["GITHUB_EVENT_NAME"] not in ("schedule", "workflow_dispatch"): if os.environ["GITHUB_EVENT_NAME"] not in ("workflow_run", "workflow_dispatch"):
raise RuntimeError("badge publisher must run on a timer or manual dispatch") raise RuntimeError("badge publisher must follow CI completion or manual dispatch")
if os.environ["GITHUB_REF"] != "refs/heads/main": if os.environ["GITHUB_REF"] != "refs/heads/main":
raise RuntimeError("badge publisher must use the main branch") raise RuntimeError("badge publisher must use the main branch")
repo = os.environ["GITHUB_REPOSITORY"] repo = os.environ["GITHUB_REPOSITORY"]
-47
View File
@@ -1,47 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Select a safe fast PR check from the exact merge-base diff."""
import os
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def classify(paths: list[str]) -> str:
if not paths:
return "rust"
docs = {"README.md", "LICENSE", "AGENTS.md", "ci/CONFORMANCE.md"}
def is_doc(path: str) -> bool:
return path in docs or path.startswith("docs/") and path.endswith(".md")
def is_tool(path: str) -> bool:
return (path.startswith("ci/") and Path(path).suffix in {".py", ".json"}
or path.startswith(".gitea/workflows/") and path.endswith(".yml"))
if all(is_doc(path) for path in paths):
return "documentation"
if all(is_doc(path) or is_tool(path) for path in paths):
return "tooling"
return "rust"
def changed_paths() -> list[str]:
if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
return []
base = os.environ.get("GITHUB_BASE_REF")
if base not in {"next", "main"}:
return []
try:
merge_base = subprocess.check_output(
["git", "merge-base", "HEAD", f"origin/{base}"], cwd=ROOT).strip()
diff = subprocess.check_output(
["git", "diff", "--name-only", "-z", merge_base, "HEAD"], cwd=ROOT)
return [path.decode() for path in diff.split(b"\0") if path]
except (OSError, UnicodeError, subprocess.CalledProcessError):
return []
if __name__ == "__main__":
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
output.write(f"surface={classify(changed_paths())}\n")
+6 -2
View File
@@ -21,8 +21,12 @@ PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO
def run(*args: str, env: dict[str, str] | None = None, def run(*args: str, env: dict[str, str] | None = None,
cwd: Path | None = None) -> subprocess.CompletedProcess[str]: cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, env=env, cwd=cwd, text=True, result = subprocess.run(args, env=env, cwd=cwd, text=True,
capture_output=True, check=True) capture_output=True, check=False)
if result.returncode:
detail = result.stderr.strip()[:2000]
raise RuntimeError(f"{args[0]} {args[1]} exited {result.returncode}: {detail}")
return result
def current_main_sha() -> str: def current_main_sha() -> str:
-21
View File
@@ -1,21 +0,0 @@
{
"schema": 1,
"claims": [
{
"board": "a113d",
"chip": "BM1366",
"level": "protocol_decoded",
"source": "miner-firmware/firmware-analysis/prong-b/aml-112/fullcov/capC1.strace",
"sha256": "05303e93f6d00433a6db5a9ee973b6cdb0351f3efa35d293dd172ede7da89d54",
"scope": "Historical BM1366 UART enumeration and nonce frames on an A113D S19k Pro"
},
{
"board": "zynq-7010",
"chip": "BM1366",
"level": "catalogued",
"source": "miner-firmware/firmware-analysis/prong-b/xil-137/fullcov/capC1.strace",
"sha256": "3daa3f7381580ef87f3b5925d5a03fdb4d2e7cd93a82b943ef2578da3d545607",
"scope": "Historical sensor and board observations; FPGA chip data path was not captured"
}
]
}
-43
View File
@@ -1,43 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Research observations cannot promote a target into release conformance."""
import copy
import importlib.util
import json
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location("evidence_status", ROOT / "evidence_status.py")
status = importlib.util.module_from_spec(spec)
spec.loader.exec_module(status)
MATRIX = json.loads((ROOT / "conformance.json").read_text())
RESEARCH = json.loads((ROOT / "research-evidence.json").read_text())
class EvidenceStatusTest(unittest.TestCase):
def test_historical_protocol_does_not_satisfy_release(self):
report = status.summarize(MATRIX, RESEARCH)
self.assertEqual(report["target_cells"], 64)
self.assertEqual(report["research_only"], {"catalogued": 1, "protocol_decoded": 1})
self.assertIsNone(report["verified_release_cells"])
self.assertEqual(sum(report["release_manifest_declarations_unverified"].values()), 0)
for level in ("stock_simulator_boot", "captured_nonce_pool_accept",
"physical_install_update_uninstall_recovery", "full_release_cell"):
self.assertIsNone(report["evidence_levels"][level]["current_run_verified"])
def test_rejects_missing_cell_and_unsupported_claim(self):
matrix = copy.deepcopy(MATRIX)
matrix["targets"].pop()
with self.assertRaisesRegex(ValueError, "incomplete"):
status.summarize(matrix, RESEARCH)
research = copy.deepcopy(RESEARCH)
research["claims"][0]["level"] = "pool_accept"
with self.assertRaisesRegex(ValueError, "outside target matrix or level"):
status.summarize(MATRIX, research)
if __name__ == "__main__":
unittest.main()
-41
View File
@@ -1,41 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Representative experiments preserve the full release target set."""
import copy
import importlib.util
import json
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location("experiment_priority", ROOT / "experiment_priority.py")
priority = importlib.util.module_from_spec(spec)
spec.loader.exec_module(priority)
MATRIX = json.loads((ROOT / "conformance.json").read_text())
QUEUE = json.loads((ROOT / "experiment-queue.json").read_text())
class ExperimentPriorityTest(unittest.TestCase):
def test_local_boot_model_ranks_first_without_reducing_gate(self):
ordered = priority.rank(MATRIX, QUEUE)
self.assertEqual(ordered[0]["id"], "am335x-original-nand-boot")
self.assertEqual(ordered[0]["affected_release_cells"], 13)
self.assertEqual(len(MATRIX["targets"]), 64)
self.assertEqual(next(row for row in ordered if row["id"] == "bm1368-command-and-nonce")
["affected_release_cells"], 4)
def test_no_selector_or_unexplained_blocker(self):
queue = copy.deepcopy(QUEUE)
queue["experiments"][0]["board"] = None
with self.assertRaisesRegex(ValueError, "no target selector"):
priority.rank(MATRIX, queue)
queue = copy.deepcopy(QUEUE)
queue["experiments"][1]["blocker"] = None
with self.assertRaisesRegex(ValueError, "lacks a blocker"):
priority.rank(MATRIX, queue)
if __name__ == "__main__":
unittest.main()
+10 -4
View File
@@ -36,7 +36,7 @@ assert b">fail</text>" in svg
assert b"#d1242f" in svg assert b"#d1242f" in svg
assert b">pass</text>" in module.badge("next", "success", 108) assert b">pass</text>" in module.badge("next", "success", 108)
environment = { environment = {
"GITHUB_EVENT_NAME": "schedule", "GITHUB_EVENT_NAME": "workflow_run",
"GITHUB_REF": "refs/heads/main", "GITHUB_REF": "refs/heads/main",
"GITHUB_REPOSITORY": "owner/repo", "GITHUB_REPOSITORY": "owner/repo",
"GITHUB_API_URL": "https://example.invalid/api/v1", "GITHUB_API_URL": "https://example.invalid/api/v1",
@@ -49,13 +49,19 @@ with patch.dict(os.environ, environment), \
module.main() module.main()
assert latest.call_count == 2 assert latest.call_count == 2
assert [call.args[2] for call in published.call_args_list] == ["main", "next"] assert [call.args[2] for call in published.call_args_list] == ["main", "next"]
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "workflow_run"}): with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "workflow_dispatch"}), \
patch.object(module, "latest_completed", side_effect=[(201, "success"),
(202, "failure")]), \
patch.object(module, "publish") as published:
module.main()
assert published.call_count == 2
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "schedule"}):
try: try:
module.main() module.main()
except RuntimeError as error: except RuntimeError as error:
assert "timer or manual dispatch" in str(error) assert "CI completion or manual dispatch" in str(error)
else: else:
raise AssertionError("workflow_run event entered badge publisher") raise AssertionError("scheduled event entered badge publisher")
for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"): for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"):
try: try:
publish_file("https://example.invalid/api/v1", "owner/repo", invalid, publish_file("https://example.invalid/api/v1", "owner/repo", invalid,
-28
View File
@@ -1,28 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Unknown PR paths must retain compiled source checks."""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location("pr_surface", Path(__file__).with_name("pr_surface.py"))
surface = importlib.util.module_from_spec(spec)
spec.loader.exec_module(surface)
class PrSurfaceTest(unittest.TestCase):
def test_documentation_and_tooling(self):
self.assertEqual(surface.classify(["README.md", "docs/boards.md"]), "documentation")
self.assertEqual(surface.classify(["ci/evidence_status.py", "ci/CONFORMANCE.md"]), "tooling")
def test_unknown_and_rust_paths_fail_open_to_build(self):
for paths in ([], ["src/main.rs"], ["Cargo.toml"], ["unknown/file"],
["ci/evidence_status.py", "src/main.rs"]):
with self.subTest(paths=paths):
self.assertEqual(surface.classify(paths), "rust")
if __name__ == "__main__":
unittest.main()
-59
View File
@@ -1,59 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check candidate numbering and covered-commit reruns with real Git tags."""
from pathlib import Path
import subprocess
import tempfile
VERSION = Path(__file__).with_name("version.py")
def git(root: Path, *args: str) -> str:
result = subprocess.run(
["git", *args], cwd=root, text=True, check=True, capture_output=True
)
return result.stdout.strip()
def selected(root: Path, branch: str) -> dict[str, str]:
result = subprocess.run(
["python3", str(VERSION), branch], cwd=root,
text=True, check=True, capture_output=True
)
return dict(line.split("=", 1) for line in result.stdout.splitlines())
def main() -> None:
with tempfile.TemporaryDirectory(prefix="alkane-os-version-") as path:
root = Path(path)
(root / "ci").mkdir()
(root / "ci/version-x.txt").write_text("0\n")
git(root, "init", "-q")
git(root, "config", "user.name", "Alkane CI")
git(root, "config", "user.email", "ci@example.invalid")
git(root, "add", ".")
git(root, "commit", "-qm", "First source")
first = git(root, "rev-parse", "HEAD")
assert selected(root, "next") == {
"release": "true", "tag": "v0.1.0-rc.1", "version": "0.1.0-rc.1"
}
git(root, "tag", "v0.1.0-rc.1")
assert selected(root, "next") == {"release": "false"}
(root / "README.md").write_text("A later merge.\n")
git(root, "add", ".")
git(root, "commit", "-qm", "Later source")
assert selected(root, "next") == {
"release": "true", "tag": "v0.1.0-rc.2", "version": "0.1.0-rc.2"
}
git(root, "tag", "v0.1.0-rc.2")
assert selected(root, "next") == {"release": "false"}
git(root, "checkout", "-q", first)
assert selected(root, "next") == {"release": "false"}
print("PASS: exact and superseded candidate reruns do not publish")
if __name__ == "__main__":
main()
-7
View File
@@ -27,13 +27,6 @@ def main():
parser.add_argument("branch", choices=("main", "next")) parser.add_argument("branch", choices=("main", "next"))
args = parser.parse_args() args = parser.parse_args()
major = int(pathlib.Path("ci/version-x.txt").read_text().strip()) major = int(pathlib.Path("ci/version-x.txt").read_text().strip())
# A rerun of a commit already covered by a published tag must not issue
# a newer candidate number for older source.
tagged_descendants = set(git("tag", "--contains", "HEAD", "-l", "v*").splitlines())
known_tags = {tag for _, tag in versions("main") + versions("next")}
if tagged_descendants & known_tags:
print("release=false")
return
finals = versions("main") finals = versions("main")
previous = finals[-1] if finals else None previous = finals[-1] if finals else None
if previous and previous[0][0] > major: if previous and previous[0][0] > major:
-19
View File
@@ -1,19 +0,0 @@
{
"schema": 1,
"profiles": [
{
"name": "s19jpro-bm1362-pic",
"chip": "bm1362",
"sensor": "pic",
"chains": 3,
"envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700}
},
{
"name": "s19kpro-bm1366-nopic",
"chip": "bm1366",
"sensor": "nopic",
"chains": 3,
"envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700}
}
]
}
-589
View File
@@ -1,589 +0,0 @@
// SPDX-License-Identifier: MIT
//! Process wiring: start the API and UI servers and publish the hardware snapshot.
//!
//! The binary and the tests use the same function, so the wiring that CI exercises is the wiring
//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover
//! ephemeral ports instead of guessing them.
use crate::detect::{
run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget,
SensorTopology,
};
use crate::fanmap::{FanMap, MapThresholds, SweepConfig};
use crate::fanmap_store::ensure_map;
use crate::fault::FaultPolicy;
use crate::hal_wire::{HalClient, HalError};
use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus};
use crate::profiles::{ProfileDb, ProfileError};
use crate::runtime::MinerRuntime;
use crate::tuning::{PidConfig, TuningTarget};
use crate::web;
use std::fmt;
use std::io;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Duration;
/// Bound servers and their worker threads.
pub struct Servers {
pub api: Option<SocketAddr>,
pub web: Option<SocketAddr>,
handles: Vec<JoinHandle<()>>,
}
impl Servers {
/// Addresses actually bound, which matters when port 0 was requested.
pub fn addresses(&self) -> (Option<SocketAddr>, Option<SocketAddr>) {
(self.api, self.web)
}
/// Wait for the workers. Only useful in tests; the binary runs until it is killed.
pub fn join(self) {
for handle in self.handles {
let _ = handle.join();
}
}
}
/// Bind and start the cgminer-style API and the web UI, each when an address is given.
pub fn start(
status: Arc<MiningStatus>,
api: Option<SocketAddr>,
web_bind: Option<SocketAddr>,
) -> io::Result<Servers> {
let api_listener = match api {
Some(address) => Some(bind_local(address)?),
None => None,
};
let api_address = api_listener
.as_ref()
.map(|listener| listener.local_addr())
.transpose()?;
let web_listener = match web_bind {
Some(address) => Some(TcpListener::bind(address)?),
None => None,
};
let web_address = web_listener
.as_ref()
.map(|listener| listener.local_addr())
.transpose()?;
let mut handles = Vec::new();
if let Some(listener) = api_listener {
let snapshot = Arc::clone(&status);
handles.push(std::thread::spawn(move || {
if let Err(error) = serve(listener, snapshot) {
eprintln!("management API stopped: {error}");
}
}));
}
if let Some(listener) = web_listener {
let snapshot = Arc::clone(&status);
handles.push(std::thread::spawn(move || {
if let Err(error) = web::serve_listener(listener, snapshot) {
eprintln!("web UI stopped: {error}");
}
}));
}
Ok(Servers {
api: api_address,
web: web_address,
handles,
})
}
/// Build the API snapshot from the live runtime.
pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot {
let plan = runtime.plan();
HardwareSnapshot {
plan: plan.clone(),
active_chains: runtime.active_chains(),
stopped: runtime.stop_reason().map(|reason| match reason {
crate::fault::StopReason::Temperature => "temperature",
crate::fault::StopReason::NoChainsLeft => "no chains left",
}),
frequency_mhz: runtime.operating_point().frequency_mhz,
target: target.to_owned(),
}
}
/// Everything a boot needs besides the backend.
#[derive(Clone, Debug, PartialEq)]
pub struct BootConfig {
pub profile_db_json: String,
pub chain_ports: Vec<u8>,
pub sensor: SensorTopology,
pub budget: ProbeBudget,
pub fan_zones: Vec<FanZone>,
pub target: TuningTarget,
pub pid: PidConfig,
pub ceiling_mc: i32,
pub fault_policy: FaultPolicy,
}
/// Why boot did not reach a running runtime.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BootError<E> {
Profile(ProfileError),
Detection(DetectionFailure<E>),
/// The board backend could not be reached or refused an operation.
Backend(E),
}
impl<E: fmt::Debug> fmt::Display for BootError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Profile(error) => write!(f, "profile database rejected: {error:?}"),
Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"),
Self::Backend(error) => write!(f, "hardware backend failed: {error:?}"),
}
}
}
impl<E: fmt::Debug> std::error::Error for BootError<E> {}
/// Operator target in the form the API and UI report.
pub fn target_label(target: &TuningTarget) -> String {
match *target {
TuningTarget::PowerW(watts) => format!("power:{watts:.0}"),
TuningTarget::HashrateThs(rate) => format!("hashrate:{rate:.0}"),
TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"),
TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"),
}
}
/// Detect, decide, and publish: the sequence a family image runs at start-up.
pub fn boot<B: DetectionBackend>(
backend: &mut B,
config: &BootConfig,
status: &MiningStatus,
) -> Result<MinerRuntime, BootError<B::Error>> {
let db = ProfileDb::from_json(&config.profile_db_json).map_err(BootError::Profile)?;
let request = DetectionRequest {
chain_ports: &config.chain_ports,
budget: config.budget,
sensor: config.sensor,
fan_zones: config.fan_zones.clone(),
};
let plan = run_detection(backend, &db, &request).map_err(BootError::Detection)?;
let runtime = MinerRuntime::new(
plan,
config.fault_policy,
config.target,
config.pid,
config.ceiling_mc,
);
status.set_hardware(snapshot(&runtime, &target_label(&config.target)));
Ok(runtime)
}
/// A boot over the real local HAL contract, including the one-time fan sweep.
pub struct HalBoot<'a> {
pub config: &'a BootConfig,
pub sweep: SweepConfig,
pub thresholds: MapThresholds,
pub map_path: &'a Path,
}
/// Connect the board backend, detect, map the fans once, and publish.
///
/// This is the path an image takes on real hardware; the fakes in the tests speak the same HAL
/// protocol, so the wiring is exercised rather than assumed.
pub fn boot_from_hal(
socket: &Path,
settings: &HalBoot<'_>,
status: &MiningStatus,
) -> Result<(MinerRuntime, FanMap), BootError<HalError>> {
let mut client = HalClient::connect(socket).map_err(BootError::Backend)?;
let zone_count = settings.sweep.zones;
let map = if zone_count == 0 {
FanMap::default()
} else {
ensure_map(
&mut client,
&settings.sweep,
settings.thresholds,
settings.map_path,
|millis| std::thread::sleep(std::time::Duration::from_millis(u64::from(millis))),
)
.map_err(|error| match error {
crate::fanmap_store::StoreError::Sweep(crate::fanmap::SweepError::Backend(error)) => {
BootError::Backend(error)
}
crate::fanmap_store::StoreError::Sweep(_) => {
BootError::Backend(HalError::Protocol("fan sweep configuration rejected"))
}
crate::fanmap_store::StoreError::Io(message) => {
BootError::Backend(HalError::Protocol(message))
}
})?
};
let config = BootConfig {
fan_zones: map.assignments.clone(),
..settings.config.clone()
};
let runtime = boot(&mut client, &config, status)?;
Ok((runtime, map))
}
/// Read one HTTP response body from a bound server, for health checks and tests.
pub fn http_get(address: SocketAddr, path: &str) -> io::Result<String> {
use std::io::{Read, Write};
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2))?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())?;
let mut reply = String::new();
stream.read_to_string(&mut reply)?;
Ok(reply)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::{
ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint,
};
use crate::detect::{ProbeOutcome, PsuCapability};
use crate::fanmap::{MapThresholds, SweepConfig};
use crate::fault::FaultPolicy;
use crate::tuning::{PidConfig, TuningTarget};
use std::io::{Read, Write};
fn runtime() -> MinerRuntime {
MinerRuntime::new(
HardwarePlan {
profile: "s19jpro-bm1362-pic".into(),
chip: ChipModel::Bm1362,
chains: vec![ChainReport {
index: 0,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom: EepromState::Absent,
response_per_mille: Some(950),
}],
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
operating_point: OperatingPoint {
voltage_mv: 1200,
frequency_mhz: 300,
confirmed: false,
},
psu: "APW12".into(),
fan_zones: vec![FanZone {
fan: 0,
zones: vec![0],
}],
},
FaultPolicy::default(),
TuningTarget::PowerW(2_400.0),
PidConfig::default(),
95_000,
)
}
#[test]
fn both_servers_serve_the_published_snapshot() {
let status = Arc::new(MiningStatus::new());
status.set_hardware(snapshot(&runtime(), "power:2400"));
let servers = start(
Arc::clone(&status),
Some("127.0.0.1:0".parse().unwrap()),
Some("127.0.0.1:0".parse().unwrap()),
)
.expect("start");
let (api, web) = servers.addresses();
let api = api.expect("api address");
let web = web.expect("web address");
let page = http_get(web, "/api/hardware").expect("web");
assert!(page.contains("s19jpro-bm1362-pic"));
assert!(page.contains("power:2400"));
let mut client =
TcpStream::connect_timeout(&api, Duration::from_secs(2)).expect("api connect");
client
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("timeout");
client.write_all(b"summary").expect("api write");
let mut summary = String::new();
client.read_to_string(&mut summary).expect("api read");
assert!(summary.contains("SUMMARY"));
}
#[test]
fn servers_are_optional() {
let status = Arc::new(MiningStatus::new());
let servers = start(status, None, None).expect("start");
assert_eq!(servers.addresses(), (None, None));
}
#[test]
fn the_snapshot_reports_runtime_state_not_boot_defaults() {
let mut runtime = runtime();
runtime.tick(&crate::runtime::Tick {
power_w: Some(1_000.0),
hashrate_ths: None,
hottest_mc: Some(60_000),
ambient_mc: None,
dt_s: 1.0,
});
let snapshot = snapshot(&runtime, "power:2400");
assert_eq!(snapshot.target, "power:2400");
assert_eq!(snapshot.active_chains, vec![0]);
assert!(snapshot.frequency_mhz > 300);
assert!(snapshot.stopped.is_none());
}
struct BootBackend {
outcome: ProbeOutcome,
psu: Option<PsuCapability>,
}
impl DetectionBackend for BootBackend {
type Error = ();
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
Ok(self.outcome)
}
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
Ok(EepromState::Absent)
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
Ok(self.psu.clone())
}
}
const DB: &str = r#"{"schema":1,"profiles":[{"name":"s19jpro-bm1362-pic",
"chip":"bm1362","sensor":"pic","chains":3,
"envelope":{"v_min_mv":1100,"v_max_mv":1500,"f_min_mhz":300,"f_max_mhz":700}}]}"#;
fn boot_config() -> BootConfig {
BootConfig {
profile_db_json: DB.into(),
chain_ports: vec![0, 1, 2],
sensor: SensorTopology::Pic,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target: TuningTarget::PowerW(2_400.0),
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: FaultPolicy::default(),
}
}
fn psu() -> PsuCapability {
PsuCapability {
name: "APW12".into(),
envelope: Envelope {
v_min_mv: 1200,
v_max_mv: 1600,
f_min_mhz: 0,
f_max_mhz: 1_000,
},
max_dc_watts: 3_600,
}
}
#[test]
fn boot_detects_and_publishes() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
psu: Some(psu()),
};
let status = MiningStatus::new();
let runtime = boot(&mut backend, &boot_config(), &status).expect("boot");
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
let document = status.hardware_document();
assert_eq!(document["available"], true);
assert_eq!(document["target"], "power:2400");
assert_eq!(document["psu"], "APW12");
}
#[test]
fn boot_refuses_an_unknown_chip() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Silent,
psu: Some(psu()),
};
let status = MiningStatus::new();
assert!(matches!(
boot(&mut backend, &boot_config(), &status),
Err(BootError::Detection(DetectionFailure::Refused(_)))
));
assert_eq!(status.hardware_document()["available"], false);
}
#[test]
fn boot_refuses_a_bad_profile_database() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
psu: Some(psu()),
};
let mut config = boot_config();
config.profile_db_json = "{\"schema\": 9}".into();
assert!(matches!(
boot(&mut backend, &config, &MiningStatus::new()),
Err(BootError::Profile(_))
));
}
#[test]
fn boot_refuses_a_missing_psu() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
psu: None,
};
assert!(matches!(
boot(&mut backend, &boot_config(), &MiningStatus::new()),
Err(BootError::Detection(DetectionFailure::Refused(_)))
));
}
#[test]
fn target_labels_are_stable() {
assert_eq!(target_label(&TuningTarget::PowerW(3_000.0)), "power:3000");
assert_eq!(
target_label(&TuningTarget::HashrateThs(200.0)),
"hashrate:200"
);
assert_eq!(
target_label(&TuningTarget::AmbientC { margin_mc: 20_000 }),
"ambient:20000"
);
assert_eq!(
target_label(&TuningTarget::MaxFan { max_pwm: 100 }),
"fan:100"
);
}
fn hal_server(socket: std::path::PathBuf) -> std::thread::JoinHandle<()> {
use std::io::{Read, Write};
use std::os::unix::net::UnixListener;
let listener = UnixListener::bind(&socket).expect("bind hal");
std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
loop {
let mut header = [0_u8; 16];
if stream.read_exact(&mut header).is_err() {
return;
}
let opcode = header[5];
let sequence = header[8..12].to_vec();
let length =
u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && stream.read_exact(&mut payload).is_err() {
return;
}
let body: Vec<u8> = match opcode {
// CAPABILITIES: chain probe, EEPROM, PSU identity.
7 => {
let mut body = vec![0_u8];
body.extend_from_slice(&7_u32.to_le_bytes());
body
}
// PROBE_CHAIN: identified, bm1362, 126 chips.
8 => vec![0, 0, 1, 126, 0],
// READ_EEPROM: absent.
9 => vec![0, 1],
// IDENTIFY_PSU: APW12 with its envelope.
10 => {
let name = b"APW12";
let mut body = vec![0_u8, name.len() as u8];
body.extend_from_slice(name);
for word in [1200_u16, 1600, 0, 1000, 3600] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
_ => vec![1],
};
let mut out = [0_u8; 16];
out[..4].copy_from_slice(b"ALKH");
out[4] = 1;
out[5] = opcode;
out[6..8].copy_from_slice(&1_u16.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
if stream.write_all(&out).is_err() || stream.write_all(&body).is_err() {
return;
}
}
})
}
#[test]
fn boot_over_the_hal_socket_detects_and_publishes() {
let base = std::env::temp_dir().join(format!("alkane-hal-{}", std::process::id()));
let socket = base.with_extension("sock");
let map_path = base.with_extension("map.json");
let _ = std::fs::remove_file(&socket);
let server = hal_server(socket.clone());
let status = MiningStatus::new();
let config = boot_config();
let settings = HalBoot {
config: &config,
sweep: SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: MapThresholds::default(),
map_path: &map_path,
};
let (runtime, map) = boot_from_hal(&socket, &settings, &status).expect("boot over hal");
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
assert!(map.assignments.is_empty());
let document = status.hardware_document();
assert_eq!(document["available"], true);
assert_eq!(document["psu"], "APW12");
assert_eq!(document["chip"], "bm1362");
let _ = std::fs::remove_file(&socket);
let _ = server.join();
}
#[test]
fn boot_over_a_missing_socket_is_a_backend_error() {
let socket =
std::env::temp_dir().join(format!("alkane-missing-{}.sock", std::process::id()));
let status = MiningStatus::new();
let config = boot_config();
let settings = HalBoot {
config: &config,
sweep: SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: MapThresholds::default(),
map_path: &socket,
};
assert!(matches!(
boot_from_hal(&socket, &settings, &status),
Err(BootError::Backend(_))
));
}
}
-203
View File
@@ -1,203 +0,0 @@
// SPDX-License-Identifier: MIT
//! BM1370 wire frames observed on an S21 Pro. This module does not control power.
use crate::bm13xx::{crc16, crc5};
pub use crate::bm1362::Job;
pub const JOB_BYTES: usize = 88;
pub const REPORT_BYTES: usize = 11;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NonceReport {
pub nonce: u32,
pub byte6: u8,
pub byte7: u8,
pub byte8: u8,
pub byte9: u8,
/// Raw trailer: bit 7 marks a nonce response; bits 4:0 carry CRC5.
/// No chip identity is inferred from this byte.
pub trailer: u8,
}
impl NonceReport {
/// Work ID observed in the Braiins S21 Pro capture. Chip and version
/// attribution remain unknown, and this has no accepted-share proof.
pub fn observed_work_id(&self) -> u8 {
(self.byte7 & 0xf0) >> 1
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReportError {
Length,
Preamble,
RegisterResponse,
Checksum,
}
/// Encode only the job shape observed in the S21 Pro capture. `Job` fields
/// are in wire order; this does not validate a pool header or start a chain.
pub fn encode_job(job: &Job) -> Option<[u8; JOB_BYTES]> {
if job.work_id & 7 != 0 || job.num_midstates != 1 || job.start_nonce != 0 {
return None;
}
let mut frame = crate::bm1362::encode_job(job);
frame[3] = 0x36;
let checksum = crc16(&frame[2..86]);
frame[86..88].copy_from_slice(&checksum.to_be_bytes());
Some(frame)
}
/// Keep the five trailing bytes raw. The work-ID expression is correlated with
/// same-UART jobs in one capture; chip and version mapping remain unverified.
/// The marker bit distinguishes nonce reports from register replies.
pub fn decode_nonce_report(frame: &[u8]) -> Result<NonceReport, ReportError> {
if frame.len() != REPORT_BYTES {
return Err(ReportError::Length);
}
if frame[..2] != [0xaa, 0x55] {
return Err(ReportError::Preamble);
}
if frame[10] & 0x80 == 0 {
return Err(ReportError::RegisterResponse);
}
if crc5(&frame[2..]) != 0 {
return Err(ReportError::Checksum);
}
Ok(NonceReport {
nonce: u32::from_le_bytes(frame[2..6].try_into().expect("four-byte nonce")),
byte6: frame[6],
byte7: frame[7],
byte8: frame[8],
byte9: frame[9],
trailer: frame[10],
})
}
#[cfg(test)]
mod tests {
use super::*;
// firmware-analysis/prong-b/s21-192/c2-steady.strace, SHA-256
// c0aac1222e05e95bdcbd1de5a8ee244a581256e8f28e3dadf5300df6110229c7.
const CAPTURED_JOB: &str = concat!(
"55aa21366001000000008f060217834f276af0f09aafc588165b7fbfc56f8f09a55d3d0de5",
"798bd87460278af180c4696fc200000000000000008af701003acc10cdebe5bc3c90f095e5",
"03c6b7de69ca8b5d00000020e769"
);
fn captured_bytes<const N: usize>(hex: &str) -> [u8; N] {
assert_eq!(hex.len(), N * 2);
let mut bytes = [0; N];
for (index, pair) in hex.as_bytes().chunks_exact(2).enumerate() {
bytes[index] = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap();
}
bytes
}
fn with_valid_crc(mut frame: [u8; REPORT_BYTES]) -> [u8; REPORT_BYTES] {
for checksum in 0..32 {
frame[10] = (frame[10] & 0xe0) | checksum;
if crc5(&frame[2..]) == 0 {
return frame;
}
}
panic!("no valid CRC5 trailer");
}
#[test]
fn live_job_matches_all_88_bytes() {
let captured = captured_bytes::<JOB_BYTES>(CAPTURED_JOB);
let mut merkle_root = [0; 32];
merkle_root.copy_from_slice(&captured[18..50]);
let mut previous_hash = [0; 32];
previous_hash.copy_from_slice(&captured[50..82]);
let job = Job {
work_id: captured[4],
num_midstates: captured[5],
start_nonce: u32::from_le_bytes(captured[6..10].try_into().unwrap()),
nbits: u32::from_le_bytes(captured[10..14].try_into().unwrap()),
ntime: u32::from_le_bytes(captured[14..18].try_into().unwrap()),
merkle_root,
previous_hash,
version: u32::from_le_bytes(captured[82..86].try_into().unwrap()),
};
assert_eq!(encode_job(&job), Some(captured));
let mut invalid = job;
invalid.work_id |= 1;
assert_eq!(encode_job(&invalid), None);
invalid = job;
invalid.num_midstates = 2;
assert_eq!(encode_job(&invalid), None);
invalid = job;
invalid.start_nonce = 1;
assert_eq!(encode_job(&invalid), None);
assert_eq!(
crc16(&captured[2..86]),
u16::from_be_bytes([captured[86], captured[87]])
);
}
#[test]
fn live_nonce_reports_preserve_raw_tags() {
for hex in [
"aa555804a92a041e133e86",
"aa55771def23001c16fc82",
"aa5574480ae6021417b492",
] {
let frame = captured_bytes::<REPORT_BYTES>(hex);
let report = decode_nonce_report(&frame).unwrap();
assert_eq!(
report.nonce,
u32::from_le_bytes(frame[2..6].try_into().unwrap())
);
assert_eq!(report.byte6, frame[6]);
assert_eq!(report.byte7, frame[7]);
assert_eq!(report.byte8, frame[8]);
assert_eq!(report.byte9, frame[9]);
assert_eq!(report.trailer, frame[10]);
}
}
#[test]
fn observed_work_id_matches_same_uart_job() {
// c2-steady.strace lines 1287 and 1352: job byte 4 is 0x10.
let frame = captured_bytes::<REPORT_BYTES>("aa554a3488c70022013291");
let report = decode_nonce_report(&frame).unwrap();
assert_eq!(report.observed_work_id(), 0x10);
assert_eq!(report.byte7, 0x22);
}
#[test]
fn invalid_report_fails_closed() {
let mut frame = captured_bytes::<REPORT_BYTES>("aa555804a92a041e133e86");
assert_eq!(decode_nonce_report(&frame[..10]), Err(ReportError::Length));
frame[0] = 0;
assert_eq!(decode_nonce_report(&frame), Err(ReportError::Preamble));
frame[0] = 0xaa;
frame[10] &= 0x60;
frame = with_valid_crc(frame);
assert_eq!(crc5(&frame[2..]), 0);
assert_eq!(
decode_nonce_report(&frame),
Err(ReportError::RegisterResponse)
);
frame[10] |= 0x80;
frame = with_valid_crc(frame);
frame[4] ^= 1;
assert_eq!(decode_nonce_report(&frame), Err(ReportError::Checksum));
}
#[test]
fn trailer_low_bits_are_checksum_not_chip_identity() {
let original = captured_bytes::<REPORT_BYTES>("aa555804a92a041e133e86");
let mut changed_nonce = original;
changed_nonce[2] ^= 1;
changed_nonce = with_valid_crc(changed_nonce);
assert_eq!(crc5(&changed_nonce[2..]), 0);
assert_ne!(changed_nonce[10] & 0x1f, original[10] & 0x1f);
assert_eq!(changed_nonce[10] & 0xe0, original[10] & 0xe0);
assert!(decode_nonce_report(&changed_nonce).is_ok());
}
}
-761
View File
@@ -1,761 +0,0 @@
// SPDX-License-Identifier: MIT
//! Hardware detection model.
//!
//! The detection core decides what is physically attached to a control board and whether that
//! combination is safe to run. It never talks to a chain directly; backends report what they
//! probed, and this module turns that into a `HardwarePlan` the miner can execute.
//!
//! Identification deliberately does not require a hashboard EEPROM. The EEPROM, when present and
//! valid, confirms a board revision; a chain probe alone is enough to select a chip profile.
/// Chip families the detection core can name. `Unknown` is a real answer, not a placeholder.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChipModel {
Bm1362,
Bm1366,
Bm1368,
Bm1370,
Bm1398,
Unknown,
}
impl ChipModel {
/// Stable wire/API name for this chip family.
pub fn name(self) -> &'static str {
match self {
Self::Bm1362 => "bm1362",
Self::Bm1366 => "bm1366",
Self::Bm1368 => "bm1368",
Self::Bm1370 => "bm1370",
Self::Bm1398 => "bm1398",
Self::Unknown => "unknown",
}
}
}
/// How a chain reports temperature. PIC boards proxy telemetry through the power MCU.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SensorTopology {
Pic,
NoPic,
Unknown,
}
/// State of a hashboard EEPROM. Absence is normal and must never block detection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EepromState {
Present { model: String },
Absent,
Invalid,
}
/// What a backend observed on one physical chain.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChainReport {
pub index: u8,
pub chip: ChipModel,
pub chips_found: u16,
pub eeprom: EepromState,
/// Nonce responses per mille of dispatched work, when the backend could measure it.
pub response_per_mille: Option<u16>,
}
impl ChainReport {
pub fn is_identified(&self) -> bool {
self.chip != ChipModel::Unknown && self.chips_found > 0
}
}
/// Safe operating envelope for one hashboard/chip profile, from the profile database.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Envelope {
pub v_min_mv: u16,
pub v_max_mv: u16,
pub f_min_mhz: u16,
pub f_max_mhz: u16,
}
impl Envelope {
/// Voltage that pairs with a frequency across this envelope.
///
/// Voltage follows frequency linearly between the profile's floor and ceiling and is clamped
/// outside it. Boards do not run at a fixed voltage across their frequency range, so reporting
/// one voltage while the frequency moves would describe a machine that does not exist.
pub fn voltage_for(self, frequency_mhz: u16) -> u16 {
if frequency_mhz <= self.f_min_mhz {
return self.v_min_mv;
}
if frequency_mhz >= self.f_max_mhz {
return self.v_max_mv;
}
let span_f = u32::from(self.f_max_mhz - self.f_min_mhz);
let span_v = u32::from(self.v_max_mv - self.v_min_mv);
let offset = u32::from(frequency_mhz - self.f_min_mhz);
let voltage = u32::from(self.v_min_mv) + (span_v * offset) / span_f;
voltage.min(u32::from(u16::MAX)) as u16
}
pub fn intersect(self, other: Envelope) -> Option<Envelope> {
let v_min_mv = self.v_min_mv.max(other.v_min_mv);
let v_max_mv = self.v_max_mv.min(other.v_max_mv);
let f_min_mhz = self.f_min_mhz.max(other.f_min_mhz);
let f_max_mhz = self.f_max_mhz.min(other.f_max_mhz);
if v_min_mv > v_max_mv || f_min_mhz > f_max_mhz {
return None;
}
Some(Envelope {
v_min_mv,
v_max_mv,
f_min_mhz,
f_max_mhz,
})
}
}
/// A hashboard profile from the database.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BoardProfile {
pub name: String,
pub chip: ChipModel,
pub sensor: SensorTopology,
pub chains: u8,
pub envelope: Envelope,
}
/// What the PSU reports about itself and what it can deliver.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PsuCapability {
pub name: String,
pub envelope: Envelope,
pub max_dc_watts: u16,
}
/// Which fans cool which thermal zones, learned by active probing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FanZone {
pub fan: u8,
pub zones: Vec<u8>,
}
/// Why detection refused a combination.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DetectionError {
NoChains,
UnknownChip,
ChipProfileMismatch,
PsuUnidentified,
EnvelopeEmpty,
}
/// Operating point chosen for the machine.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OperatingPoint {
pub voltage_mv: u16,
pub frequency_mhz: u16,
/// True when the profile was confirmed by an EEPROM or a full chain identification.
pub confirmed: bool,
}
/// The result of detection: everything the miner needs and nothing it has to guess.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HardwarePlan {
pub profile: String,
pub chip: ChipModel,
pub chains: Vec<ChainReport>,
pub envelope: Envelope,
pub operating_point: OperatingPoint,
pub psu: String,
pub fan_zones: Vec<FanZone>,
}
impl HardwarePlan {
/// Chains that identified but reported no nonces, or fewer than expected chips.
pub fn degraded_chains(&self, expected: u16) -> Vec<u8> {
self.chains
.iter()
.filter(|chain| {
chain.chips_found < expected
|| chain.response_per_mille.is_some_and(|ratio| ratio == 0)
})
.map(|chain| chain.index)
.collect()
}
}
/// Turn observations into a plan, or refuse.
///
/// Refusal is a feature: an unverified or out-of-envelope combination must not mine silently.
pub fn plan(
chains: &[ChainReport],
profile: &BoardProfile,
psu: Option<&PsuCapability>,
fan_zones: Vec<FanZone>,
) -> Result<HardwarePlan, DetectionError> {
if chains.is_empty() {
return Err(DetectionError::NoChains);
}
if chains.iter().all(|chain| chain.chip == ChipModel::Unknown) {
return Err(DetectionError::UnknownChip);
}
if chains
.iter()
.filter(|chain| chain.is_identified())
.any(|chain| chain.chip != profile.chip)
{
return Err(DetectionError::ChipProfileMismatch);
}
let psu = psu.ok_or(DetectionError::PsuUnidentified)?;
let envelope = profile
.envelope
.intersect(psu.envelope)
.ok_or(DetectionError::EnvelopeEmpty)?;
let confirmed = chains
.iter()
.any(|chain| matches!(chain.eeprom, EepromState::Present { .. }))
&& chains.iter().all(ChainReport::is_identified);
let operating_point = if confirmed {
OperatingPoint {
voltage_mv: envelope.v_max_mv.min(profile.envelope.v_max_mv),
frequency_mhz: envelope.f_max_mhz.min(profile.envelope.f_max_mhz),
confirmed: true,
}
} else {
// Unverified hardware runs at the conservative floor of the usable envelope.
OperatingPoint {
voltage_mv: envelope.v_min_mv,
frequency_mhz: envelope.f_min_mhz,
confirmed: false,
}
};
Ok(HardwarePlan {
profile: profile.name.clone(),
chip: profile.chip,
chains: chains.to_vec(),
envelope,
operating_point,
psu: psu.name.clone(),
fan_zones,
})
}
/// Outcome of one chip-identification attempt on a chain.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProbeOutcome {
/// Chips answered: the model and how many responded.
Identified { chip: ChipModel, chips: u16 },
/// The port is electrically silent (no signal at all).
Silent,
/// Bytes arrived but did not frame as a chip response: wrong baud, noise, or a dead TX.
Garbled,
}
/// Backend contract for identification.
///
/// Framing, baud switching and electrical detail stay in the SDK image for that family; the OS
/// only decides how many attempts to spend and what the results mean.
pub trait DetectionBackend {
type Error;
/// Attempt one identification on `chain`. `attempt` lets the backend cycle its candidate
/// interface/baud set deterministically. A transport failure is an error, never `Silent`.
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error>;
/// Read the hashboard EEPROM, or report that it is absent or unreadable.
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error>;
/// Identify the PSU, if this backend can. `None` means "cannot tell", which refuses later.
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error>;
}
/// How many identification attempts to spend per chain before declaring it unidentified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProbeBudget {
pub attempts: u8,
}
impl Default for ProbeBudget {
fn default() -> Self {
Self { attempts: 4 }
}
}
/// Probe one chain until it identifies or the budget is spent.
///
/// A chain that never identifies is reported as `ChipModel::Unknown` with zero chips rather than
/// being dropped, so the plan can refuse explicitly and the API can show why.
pub fn probe_chain<B: DetectionBackend>(
backend: &mut B,
chain: u8,
budget: ProbeBudget,
) -> Result<ChainReport, B::Error> {
let mut outcome = ProbeOutcome::Silent;
for attempt in 0..budget.attempts.max(1) {
outcome = backend.probe(chain, attempt)?;
if matches!(outcome, ProbeOutcome::Identified { .. }) {
break;
}
}
let (chip, chips_found) = match outcome {
ProbeOutcome::Identified { chip, chips } => (chip, chips),
_ => (ChipModel::Unknown, 0),
};
Ok(ChainReport {
index: chain,
chip,
chips_found,
eeprom: backend.eeprom(chain)?,
response_per_mille: None,
})
}
/// Probe every declared chain port.
pub fn detect_chains<B: DetectionBackend>(
backend: &mut B,
chains: &[u8],
budget: ProbeBudget,
) -> Result<Vec<ChainReport>, B::Error> {
let mut reports = Vec::with_capacity(chains.len());
for &chain in chains {
reports.push(probe_chain(backend, chain, budget)?);
}
Ok(reports)
}
/// Everything the caller knows before probing: which ports exist, how hard to try, and how the
/// hashboards report temperature.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DetectionRequest<'a> {
pub chain_ports: &'a [u8],
pub budget: ProbeBudget,
pub sensor: SensorTopology,
pub fan_zones: Vec<FanZone>,
}
/// Why a detection run did not produce a plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DetectionFailure<E> {
Backend(E),
Refused(DetectionError),
NoProfile,
}
/// Detect, select a profile, and decide whether the machine may run.
///
/// The profile is selected by chip, sensor wiring and the number of physical chain ports, so a
/// machine with a dead chain still matches its profile and runs degraded instead of being
/// reclassified as a different model.
pub fn run_detection<B: DetectionBackend>(
backend: &mut B,
db: &crate::profiles::ProfileDb,
request: &DetectionRequest<'_>,
) -> Result<HardwarePlan, DetectionFailure<B::Error>> {
let reports = detect_chains(backend, request.chain_ports, request.budget)
.map_err(DetectionFailure::Backend)?;
let chip = reports
.iter()
.find(|report| report.is_identified())
.map(|report| report.chip)
.ok_or(DetectionFailure::Refused(DetectionError::UnknownChip))?;
let chains = u8::try_from(request.chain_ports.len()).unwrap_or(u8::MAX);
let profile = db
.find(chip, chains, request.sensor)
.ok_or(DetectionFailure::NoProfile)?;
let psu = backend.identify_psu().map_err(DetectionFailure::Backend)?;
plan(&reports, profile, psu.as_ref(), request.fan_zones.clone())
.map_err(DetectionFailure::Refused)
}
#[cfg(test)]
mod tests {
use super::*;
fn profile() -> BoardProfile {
BoardProfile {
name: "s19jpro-bm1362".into(),
chip: ChipModel::Bm1362,
sensor: SensorTopology::Pic,
chains: 3,
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
}
}
fn psu() -> PsuCapability {
PsuCapability {
name: "APW12".into(),
envelope: Envelope {
v_min_mv: 1200,
v_max_mv: 1600,
f_min_mhz: 0,
f_max_mhz: 1000,
},
max_dc_watts: 3600,
}
}
fn chain(index: u8, eeprom: EepromState) -> ChainReport {
ChainReport {
index,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom,
response_per_mille: Some(980),
}
}
#[test]
fn confirmed_plan_uses_verified_ceiling() {
let chains = [chain(
0,
EepromState::Present {
model: "BHB42601".into(),
},
)];
let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan");
assert!(plan.operating_point.confirmed);
assert_eq!(plan.operating_point.voltage_mv, 1500);
assert_eq!(plan.operating_point.frequency_mhz, 700);
assert_eq!(plan.envelope.v_min_mv, 1200);
}
#[test]
fn absent_eeprom_still_yields_a_conservative_plan() {
let chains = [chain(0, EepromState::Absent)];
let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan");
assert!(!plan.operating_point.confirmed);
assert_eq!(plan.operating_point.voltage_mv, plan.envelope.v_min_mv);
assert_eq!(plan.operating_point.frequency_mhz, plan.envelope.f_min_mhz);
}
#[test]
fn unknown_chip_refuses() {
let mut chains = [chain(0, EepromState::Absent)];
chains[0].chip = ChipModel::Unknown;
assert_eq!(
plan(&chains, &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::UnknownChip)
);
}
#[test]
fn wrong_chip_refuses() {
let mut chains = [chain(0, EepromState::Absent)];
chains[0].chip = ChipModel::Bm1366;
assert_eq!(
plan(&chains, &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::ChipProfileMismatch)
);
}
#[test]
fn missing_psu_refuses() {
let chains = [chain(0, EepromState::Absent)];
assert_eq!(
plan(&chains, &profile(), None, Vec::new()),
Err(DetectionError::PsuUnidentified)
);
}
#[test]
fn incompatible_psu_refuses() {
let chains = [chain(0, EepromState::Absent)];
let weak = PsuCapability {
name: "APW3".into(),
envelope: Envelope {
v_min_mv: 700,
v_max_mv: 1090,
f_min_mhz: 0,
f_max_mhz: 1000,
},
max_dc_watts: 1600,
};
assert_eq!(
plan(&chains, &profile(), Some(&weak), Vec::new()),
Err(DetectionError::EnvelopeEmpty)
);
}
#[test]
fn empty_chain_set_refuses() {
assert_eq!(
plan(&[], &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::NoChains)
);
}
#[test]
fn degraded_chains_are_reported_not_fatal() {
let mut silent = chain(1, EepromState::Absent);
silent.response_per_mille = Some(0);
let chains = [chain(0, EepromState::Absent), silent];
let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan");
assert_eq!(plan.degraded_chains(126), vec![1]);
}
#[test]
fn fan_zones_are_carried_into_the_plan() {
let chains = [chain(0, EepromState::Absent)];
let zones = vec![FanZone {
fan: 0,
zones: vec![0, 1],
}];
let plan = plan(&chains, &profile(), Some(&psu()), zones.clone()).expect("plan");
assert_eq!(plan.fan_zones, zones);
}
struct ScriptedProbe {
plan: std::collections::VecDeque<ProbeOutcome>,
eeprom: EepromState,
calls: usize,
fail_at: u8,
psu: Option<PsuCapability>,
}
impl ScriptedProbe {
fn new(plan: &[ProbeOutcome], eeprom: EepromState) -> Self {
Self {
plan: plan.iter().copied().collect(),
eeprom,
calls: 0,
fail_at: u8::MAX,
psu: Some(psu()),
}
}
}
impl DetectionBackend for ScriptedProbe {
type Error = ();
fn probe(&mut self, _chain: u8, attempt: u8) -> Result<ProbeOutcome, ()> {
self.calls += 1;
if attempt == self.fail_at {
return Err(());
}
Ok(self.plan.pop_front().unwrap_or(ProbeOutcome::Silent))
}
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
Ok(self.eeprom.clone())
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
Ok(self.psu.clone())
}
}
#[test]
fn probe_retries_until_the_chain_identifies() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Silent,
ProbeOutcome::Garbled,
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
],
EepromState::Absent,
);
let report = probe_chain(&mut backend, 0, ProbeBudget { attempts: 4 }).expect("probe");
assert_eq!(backend.calls, 3);
assert_eq!(report.chip, ChipModel::Bm1362);
assert_eq!(report.chips_found, 126);
assert!(report.is_identified());
}
#[test]
fn probe_exhaustion_is_reported_not_hidden() {
let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent);
let report = probe_chain(&mut backend, 1, ProbeBudget { attempts: 4 }).expect("probe");
assert_eq!(backend.calls, 4);
assert_eq!(report.chip, ChipModel::Unknown);
assert_eq!(report.chips_found, 0);
assert!(!report.is_identified());
}
#[test]
fn probe_keeps_the_eeprom_state_even_when_unidentified() {
let mut backend = ScriptedProbe::new(
&[ProbeOutcome::Garbled; 2],
EepromState::Present {
model: "BHB42601".into(),
},
);
let report = probe_chain(&mut backend, 2, ProbeBudget { attempts: 2 }).expect("probe");
assert_eq!(report.chip, ChipModel::Unknown);
assert_eq!(
report.eeprom,
EepromState::Present {
model: "BHB42601".into()
}
);
}
#[test]
fn detection_covers_every_declared_chain_port() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
],
EepromState::Absent,
);
let reports =
detect_chains(&mut backend, &[0, 1, 2], ProbeBudget::default()).expect("detect");
assert_eq!(reports.len(), 3);
assert_eq!(
reports.iter().map(|r| r.index).collect::<Vec<_>>(),
vec![0, 1, 2]
);
assert!(reports.iter().all(ChainReport::is_identified));
}
#[test]
fn transport_failure_is_not_reported_as_a_silent_port() {
let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent);
backend.fail_at = 1;
assert_eq!(
probe_chain(&mut backend, 0, ProbeBudget::default()),
Err(())
);
assert_eq!(backend.calls, 2);
}
#[test]
fn unidentified_chain_makes_the_plan_refuse() {
let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent);
let reports = detect_chains(&mut backend, &[0], ProbeBudget::default()).expect("detect");
assert_eq!(
plan(&reports, &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::UnknownChip)
);
}
fn db() -> crate::profiles::ProfileDb {
crate::profiles::ProfileDb::new(vec![profile()]).expect("db")
}
#[test]
fn run_detection_emits_a_plan_end_to_end() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
],
EepromState::Absent,
);
let request = DetectionRequest {
chain_ports: &[0, 1, 2],
budget: ProbeBudget::default(),
sensor: SensorTopology::Pic,
fan_zones: vec![FanZone {
fan: 0,
zones: vec![0],
}],
};
let plan = run_detection(&mut backend, &db(), &request).expect("plan");
assert_eq!(plan.chains.len(), 3);
assert_eq!(plan.psu, "APW12");
assert!(!plan.operating_point.confirmed);
assert_eq!(plan.operating_point.voltage_mv, 1200);
}
#[test]
fn run_detection_refuses_when_no_profile_matches() {
let mut backend = ScriptedProbe::new(
&[ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
}],
EepromState::Absent,
);
let request = DetectionRequest {
chain_ports: &[0],
budget: ProbeBudget::default(),
sensor: SensorTopology::Pic,
fan_zones: Vec::new(),
};
assert_eq!(
run_detection(&mut backend, &db(), &request),
Err(DetectionFailure::NoProfile)
);
}
#[test]
fn run_detection_runs_degraded_with_a_dead_chain() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Silent,
ProbeOutcome::Silent,
ProbeOutcome::Silent,
ProbeOutcome::Silent,
],
EepromState::Absent,
);
let request = DetectionRequest {
chain_ports: &[0, 1, 2],
budget: ProbeBudget::default(),
sensor: SensorTopology::Pic,
fan_zones: Vec::new(),
};
let plan = run_detection(&mut backend, &db(), &request).expect("plan");
assert_eq!(plan.degraded_chains(126), vec![2]);
}
#[test]
fn voltage_follows_frequency_and_clamps_outside_the_envelope() {
let envelope = Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
};
assert_eq!(envelope.voltage_for(200), 1100);
assert_eq!(envelope.voltage_for(300), 1100);
assert_eq!(envelope.voltage_for(500), 1300);
assert_eq!(envelope.voltage_for(700), 1500);
assert_eq!(envelope.voltage_for(900), 1500);
}
#[test]
fn a_single_frequency_envelope_reports_its_floor() {
let envelope = Envelope {
v_min_mv: 1200,
v_max_mv: 1400,
f_min_mhz: 500,
f_max_mhz: 500,
};
assert_eq!(envelope.voltage_for(500), 1200);
assert_eq!(envelope.voltage_for(600), 1400);
}
}
-469
View File
@@ -1,469 +0,0 @@
// SPDX-License-Identifier: MIT
//! Active fan-to-thermal-zone mapping.
//!
//! Antminer chassis wire fans to zones in a way that is not reported by the hardware: a fan may
//! cool one hashboard heavily and another barely, and the front/back, top/bottom labels are
//! physical. The mapping is learned by stepping one fan at a time and watching which zone's
//! temperature responds, which is why this module takes measurements rather than configuration.
use crate::detect::FanZone;
/// One sensor reading taken while a fan was held at a given duty.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ZoneReading {
pub zone: u8,
pub temp_mc: i32,
}
/// One measurement step: a fan duty and the temperatures observed during it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProbeSample {
pub fan: u8,
pub pwm: u8,
pub readings: Vec<ZoneReading>,
}
/// Thresholds that decide when a response is real.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MapThresholds {
/// Minimum cooling (millidegrees) between the low and high duty to count as a response.
pub min_drop_mc: i32,
/// Minimum margin over the next-best fan, in parts per thousand of the best response.
pub min_margin_per_mille: u16,
}
impl Default for MapThresholds {
fn default() -> Self {
Self {
min_drop_mc: 500,
min_margin_per_mille: 250,
}
}
}
/// The learned mapping.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct FanMap {
pub assignments: Vec<FanZone>,
/// Zones whose response was ambiguous and were therefore left unassigned.
pub unresolved: Vec<u8>,
/// Per assigned zone, the margin over the runner-up in parts per thousand.
pub confidence_per_mille: Vec<u16>,
}
impl FanMap {
/// Zones a fan was confidently assigned to.
pub fn zones_for(&self, fan: u8) -> Vec<u8> {
self.assignments
.iter()
.find(|assignment| assignment.fan == fan)
.map(|assignment| assignment.zones.clone())
.unwrap_or_default()
}
}
/// Response per (fan, zone): positive means the zone cooled when that fan sped up.
fn responses(samples: &[ProbeSample], zones: &[u8]) -> Vec<(u8, Vec<(u8, i32)>)> {
let mut fans: Vec<u8> = samples.iter().map(|sample| sample.fan).collect();
fans.sort_unstable();
fans.dedup();
let mut out = Vec::new();
for fan in fans {
let fan_samples: Vec<&ProbeSample> =
samples.iter().filter(|sample| sample.fan == fan).collect();
let min_pwm = fan_samples.iter().map(|sample| sample.pwm).min();
let max_pwm = fan_samples.iter().map(|sample| sample.pwm).max();
let (Some(low), Some(high)) = (min_pwm, max_pwm) else {
continue;
};
if low == high {
continue;
}
let mut per_zone = Vec::with_capacity(zones.len());
for &zone in zones {
let mean_at = |pwm: u8| -> Option<i32> {
let values: Vec<i32> = fan_samples
.iter()
.filter(|sample| sample.pwm == pwm)
.flat_map(|sample| {
sample
.readings
.iter()
.filter(|reading| reading.zone == zone)
.map(|reading| reading.temp_mc)
})
.collect();
if values.is_empty() {
return None;
}
let sum: i64 = values.iter().map(|value| *value as i64).sum();
Some((sum / values.len() as i64) as i32)
};
// Duty goes up, temperature should come down: response = warm-run minus fast-run.
if let (Some(slow_temp), Some(fast_temp)) = (mean_at(low), mean_at(high)) {
per_zone.push((zone, slow_temp - fast_temp));
}
}
out.push((fan, per_zone));
}
out
}
/// Learn which fans cool which zones from a stepped measurement run.
///
/// Every zone goes to the fan with the strongest cooling response, provided that response clears
/// `min_drop_mc` and beats the runner-up by `min_margin_per_mille`. Anything weaker stays
/// unresolved instead of being guessed, so a noisy run cannot invent a fan map.
pub fn map_fans(samples: &[ProbeSample], zones: &[u8], thresholds: MapThresholds) -> FanMap {
let responses = responses(samples, zones);
let mut map = FanMap::default();
for &zone in zones {
let mut ranked: Vec<(i32, u8)> = responses
.iter()
.filter_map(|(fan, per_zone)| {
per_zone
.iter()
.find(|(candidate, _)| *candidate == zone)
.map(|(_, drop)| (*drop, *fan))
})
.collect();
ranked.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.0));
let Some(&(best_drop, best_fan)) = ranked.first() else {
map.unresolved.push(zone);
continue;
};
let runner_up = ranked.get(1).map(|(drop, _)| *drop).unwrap_or(0);
let margin = best_drop - runner_up.max(0);
let margin_per_mille = if best_drop > 0 {
((margin as i64 * 1000) / best_drop as i64) as u16
} else {
0
};
if best_drop < thresholds.min_drop_mc || margin_per_mille < thresholds.min_margin_per_mille
{
map.unresolved.push(zone);
continue;
}
match map
.assignments
.iter_mut()
.find(|assignment| assignment.fan == best_fan)
{
Some(assignment) => assignment.zones.push(zone),
None => map.assignments.push(FanZone {
fan: best_fan,
zones: vec![zone],
}),
}
map.confidence_per_mille.push(margin_per_mille);
}
map
}
/// Safe limits for a fan-mapping sweep.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SweepConfig {
pub fans: u8,
pub zones: u8,
/// Lowest duty used during probing. Never zero: the boards must keep airflow.
pub low_pwm: u8,
pub high_pwm: u8,
/// Readings taken per (fan, duty) step; the mapper averages them.
pub repeats: u8,
/// Time to wait after a duty change before reading temperatures.
pub settle_ms: u32,
}
impl Default for SweepConfig {
fn default() -> Self {
Self {
fans: 4,
zones: 3,
low_pwm: 40,
high_pwm: 100,
repeats: 2,
settle_ms: 20_000,
}
}
}
/// Minimum duty a sweep may use. Airflow is never removed to make a measurement.
pub const MIN_PROBE_PWM: u8 = 20;
/// Why a sweep did not run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SweepError<E> {
Backend(E),
InvalidConfig(&'static str),
}
/// The two backend actions a sweep needs.
pub trait FanProbe {
type Error;
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error>;
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error>;
}
/// Step every fan between the low and high duty and record what the zones do.
///
/// One fan is moved at a time while the others hold their previous duty, so the response belongs
/// to that fan. The run ends with every fan back at `high_pwm`: leaving a fan low after probing
/// would be a thermal hazard for whatever runs next.
pub fn sweep<B: FanProbe, S: FnMut(u32)>(
backend: &mut B,
config: &SweepConfig,
mut settle: S,
) -> Result<Vec<ProbeSample>, SweepError<B::Error>> {
if config.fans == 0 {
return Err(SweepError::InvalidConfig("no fans to sweep"));
}
if config.zones == 0 {
return Err(SweepError::InvalidConfig("no zones to read"));
}
if config.low_pwm < MIN_PROBE_PWM {
return Err(SweepError::InvalidConfig(
"probe duty below the safe minimum",
));
}
if config.high_pwm > 100 {
return Err(SweepError::InvalidConfig("probe duty above 100 percent"));
}
if config.low_pwm >= config.high_pwm {
return Err(SweepError::InvalidConfig("probe duty range is empty"));
}
if config.repeats == 0 {
return Err(SweepError::InvalidConfig("no readings requested"));
}
let mut samples = Vec::new();
for fan in 0..config.fans {
for pwm in [config.low_pwm, config.high_pwm] {
backend.set_fan(fan, pwm).map_err(SweepError::Backend)?;
settle(config.settle_ms);
for _ in 0..config.repeats {
let mut readings = Vec::with_capacity(config.zones as usize);
for zone in 0..config.zones {
readings.push(ZoneReading {
zone,
temp_mc: backend.read_zone(zone).map_err(SweepError::Backend)?,
});
}
samples.push(ProbeSample { fan, pwm, readings });
}
}
}
for fan in 0..config.fans {
backend
.set_fan(fan, config.high_pwm)
.map_err(SweepError::Backend)?;
}
Ok(samples)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(fan: u8, pwm: u8, zone_temps: &[(u8, i32)]) -> ProbeSample {
ProbeSample {
fan,
pwm,
readings: zone_temps
.iter()
.map(|(zone, temp)| ZoneReading {
zone: *zone,
temp_mc: *temp,
})
.collect(),
}
}
#[test]
fn each_zone_is_assigned_to_the_fan_that_cools_it() {
let samples = vec![
sample(0, 30, &[(0, 70_000), (1, 60_000)]),
sample(0, 100, &[(0, 50_000), (1, 59_000)]),
sample(1, 30, &[(0, 69_000), (1, 60_000)]),
sample(1, 100, &[(0, 68_000), (1, 40_000)]),
];
let map = map_fans(&samples, &[0, 1], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
assert_eq!(map.zones_for(1), vec![1]);
assert!(map.unresolved.is_empty());
}
#[test]
fn ambiguity_leaves_a_zone_unresolved() {
let samples = vec![
sample(0, 30, &[(0, 70_000)]),
sample(0, 100, &[(0, 60_000)]),
sample(1, 30, &[(0, 70_500)]),
sample(1, 100, &[(0, 60_500)]),
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert!(map.assignments.is_empty());
assert_eq!(map.unresolved, vec![0]);
}
#[test]
fn a_fan_that_does_not_change_temperature_is_not_assigned() {
let samples = vec![
sample(0, 30, &[(0, 60_000)]),
sample(0, 100, &[(0, 59_900)]),
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert!(map.assignments.is_empty());
assert_eq!(map.unresolved, vec![0]);
}
#[test]
fn a_fan_without_duty_range_is_skipped() {
let samples = vec![sample(0, 50, &[(0, 60_000)]), sample(0, 50, &[(0, 60_000)])];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert!(map.assignments.is_empty());
assert_eq!(map.unresolved, vec![0]);
}
#[test]
fn one_fan_can_own_several_zones() {
let samples = vec![
sample(0, 30, &[(0, 70_000), (1, 71_000), (2, 55_000)]),
sample(0, 100, &[(0, 55_000), (1, 56_000), (2, 54_000)]),
sample(1, 30, &[(0, 70_000), (1, 71_000), (2, 54_000)]),
sample(1, 100, &[(0, 69_000), (1, 70_000), (2, 50_000)]),
];
let map = map_fans(&samples, &[0, 1, 2], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0, 1]);
assert_eq!(map.zones_for(1), vec![2]);
}
struct ThermalMock {
duty: Vec<u8>,
owners: Vec<(u8, u8)>,
fail: bool,
}
impl ThermalMock {
fn new(owners: &[(u8, u8)]) -> Self {
let fans = owners.iter().map(|(fan, _)| *fan).max().unwrap_or(0) + 1;
Self {
duty: vec![100; fans as usize],
owners: owners.to_vec(),
fail: false,
}
}
}
impl FanProbe for ThermalMock {
type Error = &'static str;
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> {
if self.fail {
return Err("fan bus down");
}
self.duty[fan as usize] = pwm;
Ok(())
}
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error> {
if self.fail {
return Err("sensor bus down");
}
let owner = self
.owners
.iter()
.find(|(_, candidate)| *candidate == zone)
.map(|(fan, _)| *fan)
.expect("zone has an owner");
let cooled = self.duty[owner as usize] >= 100;
Ok(if cooled { 50_000 } else { 70_000 })
}
}
#[test]
fn sweep_then_map_resolves_each_zone() {
let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]);
let config = SweepConfig {
fans: 2,
zones: 2,
low_pwm: 40,
high_pwm: 100,
repeats: 2,
settle_ms: 0,
};
let samples = sweep(&mut backend, &config, |_| {}).expect("sweep");
assert_eq!(samples.len(), 2 * 2 * 2);
let map = map_fans(&samples, &[0, 1], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
assert_eq!(map.zones_for(1), vec![1]);
assert!(map.unresolved.is_empty());
}
#[test]
fn sweep_restores_every_fan_to_high_duty() {
let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]);
let config = SweepConfig {
fans: 2,
zones: 2,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
};
sweep(&mut backend, &config, |_| {}).expect("sweep");
assert_eq!(backend.duty, vec![100, 100]);
}
#[test]
fn sweep_refuses_an_unsafe_duty() {
let mut backend = ThermalMock::new(&[(0, 0)]);
let config = SweepConfig {
fans: 1,
zones: 1,
low_pwm: 10,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
};
assert_eq!(
sweep(&mut backend, &config, |_| {}),
Err(SweepError::InvalidConfig(
"probe duty below the safe minimum"
))
);
}
#[test]
fn sweep_refuses_an_empty_range_and_zero_reads() {
let mut backend = ThermalMock::new(&[(0, 0)]);
let flat = SweepConfig {
fans: 1,
zones: 1,
low_pwm: 60,
high_pwm: 60,
repeats: 1,
settle_ms: 0,
};
assert!(matches!(
sweep(&mut backend, &flat, |_| {}),
Err(SweepError::InvalidConfig(_))
));
let no_reads = SweepConfig { repeats: 0, ..flat };
assert!(matches!(
sweep(&mut backend, &no_reads, |_| {}),
Err(SweepError::InvalidConfig(_))
));
}
#[test]
fn sweep_propagates_backend_failures() {
let mut backend = ThermalMock::new(&[(0, 0)]);
backend.fail = true;
let config = SweepConfig::default();
assert_eq!(
sweep(&mut backend, &config, |_| {}),
Err(SweepError::Backend("fan bus down"))
);
}
}
-318
View File
@@ -1,318 +0,0 @@
// SPDX-License-Identifier: MIT
//! Persisting the learned fan map.
//!
//! Mapping fans means heating and cooling the machine deliberately, so it is done once, stored, and
//! reused until the fan or sensor set changes. A stored map that does not match the current set is
//! ignored rather than trusted: silently applying a map learned on four fans to a machine with two
//! would mis-control thermals.
use crate::detect::FanZone;
use crate::fanmap::{map_fans, sweep, FanMap, FanProbe, MapThresholds, SweepConfig, SweepError};
use serde_json::{json, Value};
use std::fs;
use std::io;
use std::path::Path;
/// A stored map together with the hardware it was learned on.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredMap {
pub fans: u8,
pub zones: u8,
pub assignments: Vec<FanZone>,
pub unresolved: Vec<u8>,
}
impl StoredMap {
pub fn from_map(map: &FanMap, fans: u8, zones: u8) -> Self {
Self {
fans,
zones,
assignments: map.assignments.clone(),
unresolved: map.unresolved.clone(),
}
}
pub fn to_map(&self) -> FanMap {
FanMap {
assignments: self.assignments.clone(),
unresolved: self.unresolved.clone(),
confidence_per_mille: vec![0; self.assignments.len()],
}
}
/// True when this map was learned on the same fan and zone counts.
pub fn matches(&self, fans: u8, zones: u8) -> bool {
self.fans == fans && self.zones == zones
}
pub fn to_json(&self) -> String {
json!({
"schema": 1,
"fans": self.fans,
"zones": self.zones,
"assignments": self.assignments.iter().map(|zone| json!({
"fan": zone.fan,
"zones": zone.zones,
})).collect::<Vec<_>>(),
"unresolved": self.unresolved,
})
.to_string()
}
pub fn from_json(text: &str) -> Option<Self> {
let root: Value = serde_json::from_str(text).ok()?;
if root.get("schema")?.as_u64()? != 1 {
return None;
}
let fans = u8::try_from(root.get("fans")?.as_u64()?).ok()?;
let zones = u8::try_from(root.get("zones")?.as_u64()?).ok()?;
let assignments = root
.get("assignments")?
.as_array()?
.iter()
.map(|entry| {
Some(FanZone {
fan: u8::try_from(entry.get("fan")?.as_u64()?).ok()?,
zones: entry
.get("zones")?
.as_array()?
.iter()
.map(|zone| u8::try_from(zone.as_u64()?).ok())
.collect::<Option<Vec<u8>>>()?,
})
})
.collect::<Option<Vec<FanZone>>>()?;
let unresolved = root
.get("unresolved")?
.as_array()?
.iter()
.map(|zone| u8::try_from(zone.as_u64()?).ok())
.collect::<Option<Vec<u8>>>()?;
Some(Self {
fans,
zones,
assignments,
unresolved,
})
}
}
/// Why mapping did not produce a stored map.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StoreError<E> {
Sweep(SweepError<E>),
Io(&'static str),
}
/// Read a stored map, if one exists and parses.
pub fn load(path: &Path) -> Option<StoredMap> {
let text = fs::read_to_string(path).ok()?;
StoredMap::from_json(&text)
}
/// Write a map, creating the parent directory when needed.
pub fn save(path: &Path, stored: &StoredMap) -> io::Result<()> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)?;
}
}
fs::write(path, stored.to_json())
}
/// Return the stored map when it matches this machine, otherwise sweep, map, and store the result.
pub fn ensure_map<B: FanProbe, S: FnMut(u32)>(
backend: &mut B,
config: &SweepConfig,
thresholds: MapThresholds,
path: &Path,
settle: S,
) -> Result<FanMap, StoreError<B::Error>> {
if let Some(stored) = load(path) {
if stored.matches(config.fans, config.zones) {
return Ok(stored.to_map());
}
}
let zones: Vec<u8> = (0..config.zones).collect();
let samples = sweep(backend, config, settle).map_err(StoreError::Sweep)?;
let map = map_fans(&samples, &zones, thresholds);
let stored = StoredMap::from_map(&map, config.fans, config.zones);
save(path, &stored).map_err(|_| StoreError::Io("cannot write the fan map"))?;
Ok(map)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::{ProbeSample, ZoneReading};
struct CountingBackend {
duty: Vec<u8>,
owners: Vec<(u8, u8)>,
calls: usize,
}
impl FanProbe for CountingBackend {
type Error = ();
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), ()> {
self.calls += 1;
self.duty[fan as usize] = pwm;
Ok(())
}
fn read_zone(&mut self, zone: u8) -> Result<i32, ()> {
// Zones without an explicit owner follow fan 0, which keeps the mock usable when a
// test asks for more zones than the fixture declares.
let owner = self
.owners
.iter()
.find(|(_, candidate)| *candidate == zone)
.map(|(fan, _)| *fan)
.unwrap_or(0);
Ok(if self.duty[owner as usize] >= 100 {
50_000
} else {
70_000
})
}
}
fn backend() -> CountingBackend {
CountingBackend {
duty: vec![100, 100],
owners: vec![(0, 0), (1, 1)],
calls: 0,
}
}
fn config(zones: u8) -> SweepConfig {
SweepConfig {
fans: 2,
zones,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
}
}
fn path(name: &str) -> std::path::PathBuf {
let mut dir = std::env::temp_dir();
dir.push(format!("alkane-fanmap-{}-{name}.json", std::process::id()));
dir
}
#[test]
fn a_stored_map_round_trips() {
let map = FanMap {
assignments: vec![FanZone {
fan: 0,
zones: vec![0, 1],
}],
unresolved: vec![2],
confidence_per_mille: vec![900],
};
let stored = StoredMap::from_map(&map, 4, 3);
let text = stored.to_json();
assert_eq!(StoredMap::from_json(&text).expect("parse"), stored);
let back = stored.to_map();
assert_eq!(back.assignments, map.assignments);
assert_eq!(back.unresolved, map.unresolved);
}
#[test]
fn corrupt_or_foreign_json_is_ignored() {
assert!(StoredMap::from_json("not json").is_none());
assert!(StoredMap::from_json(r#"{"schema":2}"#).is_none());
assert!(StoredMap::from_json(r#"{"schema":1,"fans":2}"#).is_none());
}
#[test]
fn a_matching_map_is_reused_without_sweeping() {
let file = path("reuse");
let first = ensure_map(
&mut backend(),
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("first");
assert_eq!(first.zones_for(0), vec![0]);
let mut reuse = backend();
let second = ensure_map(
&mut reuse,
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("second");
assert_eq!(second.zones_for(0), vec![0]);
assert_eq!(reuse.calls, 0, "a stored map must not cause another sweep");
let _ = std::fs::remove_file(&file);
}
#[test]
fn a_changed_sensor_set_forces_a_new_sweep() {
let file = path("changed");
ensure_map(
&mut backend(),
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("first");
let mut fresh = backend();
let map = ensure_map(
&mut fresh,
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("second");
assert_eq!(map.zones_for(1), vec![1]);
// The stored file describes two zones; asking for three must not reuse it.
let mut three = CountingBackend {
duty: vec![100, 100],
owners: vec![(0, 0), (1, 1)],
calls: 0,
};
let _ = ensure_map(
&mut three,
&config(3),
MapThresholds::default(),
&file,
|_| {},
);
assert!(three.calls > 0);
let _ = std::fs::remove_file(&file);
}
#[test]
fn samples_from_a_sweep_still_map_correctly() {
let samples = vec![
ProbeSample {
fan: 0,
pwm: 40,
readings: vec![ZoneReading {
zone: 0,
temp_mc: 70_000,
}],
},
ProbeSample {
fan: 0,
pwm: 100,
readings: vec![ZoneReading {
zone: 0,
temp_mc: 50_000,
}],
},
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
}
}
-332
View File
@@ -1,332 +0,0 @@
// SPDX-License-Identifier: MIT
//! Fault-tolerance supervisor.
//!
//! The goal is to keep hashing with as many dead chips or chains as possible. Faults therefore
//! escalate in steps (retry, disable chip, disable chain) and only irreversible conditions stop the
//! machine. This module owns that ladder; it does not talk to hardware and it does not choose
//! thermal limits, which come from the profile envelope.
/// A single health observation from the mining loop.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FaultEvent {
/// A chain accepted work and reported nonces for it.
NoncesReported { chain: u8, per_mille: u16 },
/// A chain returned an error for a frame, reset or work dispatch.
ChainError { chain: u8 },
/// A chain produced nothing for a full observation window.
ChainSilent { chain: u8 },
/// One chip on a chain failed its identification or stopped responding.
ChipFault { chain: u8, chip: u16 },
/// A temperature reading left the profile envelope.
TemperatureFault { zone: u8 },
}
/// What the caller should do next.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FaultAction {
/// Keep hashing; nothing changed.
None,
/// Retry the chain before treating the fault as permanent.
Retry { chain: u8 },
/// Keep the machine running without this chain.
DisableChain { chain: u8 },
/// Keep the machine running without this chip.
DisableChip { chain: u8, chip: u16 },
/// Stop hashing entirely; the reason is carried for the API.
Stop { reason: StopReason },
}
/// Why the machine stopped.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StopReason {
Temperature,
NoChainsLeft,
}
/// Thresholds for escalation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FaultPolicy {
/// Consecutive errors tolerated before the chain is disabled (retries included).
pub retries: u8,
/// Nonce-response ratio below which a chain is considered stalled.
pub min_response_per_mille: u16,
/// Consecutive weak windows before a stalled chain is disabled.
pub weak_windows: u8,
}
impl Default for FaultPolicy {
fn default() -> Self {
Self {
retries: 2,
min_response_per_mille: 100,
weak_windows: 3,
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct ChainHealth {
chain: u8,
errors: u8,
weak: u8,
disabled: bool,
}
/// Escalation state for one machine.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FaultSupervisor {
policy: FaultPolicy,
chains: Vec<ChainHealth>,
stopped: Option<StopReason>,
}
impl FaultSupervisor {
pub fn new(chains: &[u8], policy: FaultPolicy) -> Self {
Self {
policy,
chains: chains
.iter()
.map(|&chain| ChainHealth {
chain,
..ChainHealth::default()
})
.collect(),
stopped: None,
}
}
pub fn is_stopped(&self) -> bool {
self.stopped.is_some()
}
pub fn stop_reason(&self) -> Option<StopReason> {
self.stopped
}
/// Chains the miner may still dispatch work to.
pub fn active_chains(&self) -> Vec<u8> {
self.chains
.iter()
.filter(|health| !health.disabled)
.map(|health| health.chain)
.collect()
}
/// Apply one observation and return the escalation step it implies.
pub fn observe(&mut self, event: FaultEvent) -> FaultAction {
if self.stopped.is_some() {
return FaultAction::None;
}
match event {
FaultEvent::NoncesReported { chain, per_mille } => {
let min_response = self.policy.min_response_per_mille;
let weak_windows = self.policy.weak_windows;
let Some(health) = self.health_mut(chain) else {
return FaultAction::None;
};
health.errors = 0;
if per_mille >= min_response {
health.weak = 0;
return FaultAction::None;
}
health.weak = health.weak.saturating_add(1);
if health.weak >= weak_windows {
health.disabled = true;
self.maybe_stop(chain)
} else {
FaultAction::None
}
}
FaultEvent::ChainError { chain } | FaultEvent::ChainSilent { chain } => {
let policy = self.policy;
let Some(health) = self.health_mut(chain) else {
return FaultAction::None;
};
if health.disabled {
return FaultAction::None;
}
health.errors = health.errors.saturating_add(1);
if health.errors > policy.retries {
health.disabled = true;
self.maybe_stop(chain)
} else {
FaultAction::Retry { chain }
}
}
FaultEvent::ChipFault { chain, chip } => FaultAction::DisableChip { chain, chip },
FaultEvent::TemperatureFault { .. } => {
self.stopped = Some(StopReason::Temperature);
FaultAction::Stop {
reason: StopReason::Temperature,
}
}
}
}
fn health_mut(&mut self, chain: u8) -> Option<&mut ChainHealth> {
self.chains.iter_mut().find(|health| health.chain == chain)
}
fn maybe_stop(&mut self, chain: u8) -> FaultAction {
if self.chains.iter().all(|health| health.disabled) {
self.stopped = Some(StopReason::NoChainsLeft);
return FaultAction::Stop {
reason: StopReason::NoChainsLeft,
};
}
FaultAction::DisableChain { chain }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn supervisor() -> FaultSupervisor {
FaultSupervisor::new(&[0, 1, 2], FaultPolicy::default())
}
#[test]
fn transient_errors_retry_then_disable_the_chain() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 1 }),
FaultAction::Retry { chain: 1 }
);
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 1 }),
FaultAction::Retry { chain: 1 }
);
assert_eq!(
faults.observe(FaultEvent::ChainSilent { chain: 1 }),
FaultAction::DisableChain { chain: 1 }
);
assert_eq!(faults.active_chains(), vec![0, 2]);
}
#[test]
fn healthy_nonces_reset_the_error_count() {
let mut faults = supervisor();
faults.observe(FaultEvent::ChainError { chain: 0 });
faults.observe(FaultEvent::ChainError { chain: 0 });
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 900
}),
FaultAction::None
);
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 0 }),
FaultAction::Retry { chain: 0 }
);
}
#[test]
fn a_stalled_chain_is_disabled_after_repeated_weak_windows() {
let mut faults = supervisor();
for _ in 0..2 {
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 2,
per_mille: 10
}),
FaultAction::None
);
}
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 2,
per_mille: 10
}),
FaultAction::DisableChain { chain: 2 }
);
assert_eq!(faults.active_chains(), vec![0, 1]);
}
#[test]
fn one_good_window_clears_weak_history() {
let mut faults = supervisor();
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 900,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10
}),
FaultAction::DisableChain { chain: 0 }
);
}
#[test]
fn a_chip_fault_disables_only_that_chip() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::ChipFault { chain: 1, chip: 42 }),
FaultAction::DisableChip { chain: 1, chip: 42 }
);
assert_eq!(faults.active_chains(), vec![0, 1, 2]);
}
#[test]
fn temperature_fault_stops_the_machine() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::TemperatureFault { zone: 2 }),
FaultAction::Stop {
reason: StopReason::Temperature
}
);
assert!(faults.is_stopped());
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 0 }),
FaultAction::None
);
}
#[test]
fn losing_every_chain_stops_instead_of_hanging() {
let mut faults = FaultSupervisor::new(
&[0],
FaultPolicy {
retries: 0,
..FaultPolicy::default()
},
);
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 0 }),
FaultAction::Stop {
reason: StopReason::NoChainsLeft
}
);
assert_eq!(faults.active_chains(), Vec::<u8>::new());
}
#[test]
fn unknown_chains_are_ignored() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 9 }),
FaultAction::None
);
assert_eq!(faults.active_chains(), vec![0, 1, 2]);
}
}
-218
View File
@@ -1,218 +0,0 @@
// SPDX-License-Identifier: MIT
//! HAL conformance checks.
//!
//! A family backend is only useful if it answers the contract the OS expects. This module walks the
//! contract in order and reports each check separately, so a backend author sees exactly which
//! opcode is missing or wrong instead of a single opaque failure.
//!
//! Every check uses a fresh connection: a backend that desynchronises one exchange must not make
//! the following checks meaningless.
use crate::hal_wire::{HalClient, CAP_CHAIN_PROBE, CAP_FREQUENCY, CAP_POWER, CAP_PSU_IDENTITY};
use crate::HardwareBackend;
use std::path::Path;
/// One check and its outcome.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Check {
pub name: &'static str,
pub passed: bool,
pub detail: String,
}
impl Check {
fn pass(name: &'static str, detail: impl Into<String>) -> Self {
Self {
name,
passed: true,
detail: detail.into(),
}
}
fn fail(name: &'static str, detail: impl Into<String>) -> Self {
Self {
name,
passed: false,
detail: detail.into(),
}
}
}
/// Run the contract checks against a backend socket.
pub fn run(socket: &Path) -> Vec<Check> {
vec![
check_capabilities(socket),
check_probe(socket),
check_eeprom(socket),
check_psu(socket),
check_frequency_and_temperature(socket),
check_power(socket),
check_fan(socket),
]
}
fn connect(socket: &Path) -> Result<HalClient, String> {
HalClient::connect(socket).map_err(|error| format!("{error:?}"))
}
fn check_capabilities(socket: &Path) -> Check {
const NAME: &str = "capabilities";
match connect(socket)
.and_then(|mut client| client.capabilities().map_err(|error| format!("{error:?}")))
{
Ok(mask) if mask & CAP_CHAIN_PROBE == 0 => {
Check::fail(NAME, format!("mask {mask:#x} lacks chain probing"))
}
Ok(mask) => Check::pass(NAME, format!("mask {mask:#x}")),
Err(error) => Check::fail(NAME, error),
}
}
fn check_probe(socket: &Path) -> Check {
const NAME: &str = "probe chain 0";
match connect(socket) {
Ok(mut client) => match client.probe_chain(0, 0) {
Ok(outcome) => Check::pass(NAME, format!("{outcome:?}")),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_eeprom(socket: &Path) -> Check {
const NAME: &str = "read EEPROM chain 0";
match connect(socket) {
Ok(mut client) => match client.read_eeprom(0) {
Ok(state) => Check::pass(NAME, format!("{state:?}")),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_psu(socket: &Path) -> Check {
const NAME: &str = "identify PSU";
match connect(socket) {
Ok(mut client) => match client.capabilities() {
Ok(mask) if mask & CAP_PSU_IDENTITY == 0 => {
Check::fail(NAME, "backend does not advertise PSU identity")
}
Ok(_) => match client.identify_psu() {
Ok(psu) if psu.envelope.v_min_mv <= psu.envelope.v_max_mv => {
Check::pass(NAME, format!("{} {} mV", psu.name, psu.envelope.v_max_mv))
}
Ok(psu) => Check::fail(NAME, format!("inverted envelope from {}", psu.name)),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_frequency_and_temperature(socket: &Path) -> Check {
const NAME: &str = "frequency and temperature";
match connect(socket) {
Ok(mut client) => {
let caps = match client.capabilities() {
Ok(mask) => mask,
Err(error) => return Check::fail(NAME, format!("{error:?}")),
};
if caps & CAP_FREQUENCY == 0 {
return Check::fail(NAME, "backend does not advertise frequency control");
}
if let Err(error) = client.set_chain_frequency(0, 500) {
return Check::fail(NAME, format!("set frequency: {error:?}"));
}
match client.read_temperature_mc(0) {
Ok(value) if (-40_000..=150_000).contains(&value) => {
Check::pass(NAME, format!("500 MHz, {} mC", value))
}
Ok(value) => Check::fail(NAME, format!("implausible temperature {value} mC")),
Err(error) => Check::fail(NAME, format!("read temperature: {error:?}")),
}
}
Err(error) => Check::fail(NAME, error),
}
}
fn check_power(socket: &Path) -> Check {
const NAME: &str = "read power";
match connect(socket) {
Ok(mut client) => match client.capabilities() {
Ok(mask) if mask & CAP_POWER == 0 => {
Check::fail(NAME, "backend does not advertise power telemetry")
}
Ok(_) => {
// Ask for a known operating point first: a backend that always reports 0 W would
// otherwise pass a range check while being useless to a power-target loop.
if let Err(error) = client.set_chain_frequency(0, 500) {
return Check::fail(NAME, format!("set frequency: {error:?}"));
}
std::thread::sleep(std::time::Duration::from_millis(50));
match client.read_power_w() {
Ok(0) => Check::fail(NAME, "reports 0 W at 500 MHz"),
Ok(watts) if watts <= 10_000 => {
Check::pass(NAME, format!("{watts} W at 500 MHz"))
}
Ok(watts) => Check::fail(NAME, format!("implausible power {watts} W")),
Err(error) => Check::fail(NAME, format!("{error:?}")),
}
}
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_fan(socket: &Path) -> Check {
const NAME: &str = "fan target";
match connect(socket) {
Ok(mut client) => match client.set_fan_target(0, 100) {
Ok(()) => Check::pass(NAME, "100 percent accepted"),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hal_sim::{serve, SimConfig};
fn socket(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("alkane-conf-{}-{name}.sock", std::process::id()))
}
#[test]
fn the_reference_server_passes_every_check() {
let path = socket("ok");
let server_path = path.clone();
let server = std::thread::spawn(move || {
let _ = serve(&server_path, SimConfig::default());
});
// The reference server binds inside serve(); wait for the socket to exist.
for _ in 0..100 {
if path.exists() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
let checks = run(&path);
let failed: Vec<&Check> = checks.iter().filter(|check| !check.passed).collect();
assert!(failed.is_empty(), "reference server failed: {failed:?}");
assert_eq!(checks.len(), 7);
let _ = std::fs::remove_file(&path);
// The server thread is left to exit when the socket disappears.
drop(server);
}
#[test]
fn an_unreachable_socket_fails_every_check() {
let path = socket("missing");
let checks = run(&path);
assert_eq!(checks.len(), 7);
assert!(checks.iter().all(|check| !check.passed));
}
}
-255
View File
@@ -1,255 +0,0 @@
// SPDX-License-Identifier: MIT
//! Reference HAL server.
//!
//! Speaks the same ALKH contract a family backend serves on a real board, but answers from a fixed
//! description of a machine. Two uses: it lets the whole OS path run on any development machine, and
//! it shows a backend author exactly what each opcode must return.
use std::io::{self, Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
const MAGIC: [u8; 4] = *b"ALKH";
const VERSION: u8 = 1;
const RESPONSE: u16 = 1;
const HEADER_LEN: usize = 16;
const SEND_FRAME: u8 = 1;
const RECEIVE_FRAME: u8 = 2;
const SET_CHAIN_RESET: u8 = 3;
const SET_FAN_TARGET: u8 = 4;
const READ_TEMPERATURE: u8 = 5;
const SET_PSU_ENABLED: u8 = 6;
const CAPABILITIES: u8 = 7;
const PROBE_CHAIN: u8 = 8;
const READ_EEPROM: u8 = 9;
const IDENTIFY_PSU: u8 = 10;
const SET_CHAIN_FREQUENCY: u8 = 11;
const READ_POWER: u8 = 12;
const CAP_ALL: u32 = (1 << 5) - 1;
/// What the simulated machine looks like.
#[derive(Clone, Debug)]
pub struct SimConfig {
/// Chains that identify. Chains beyond this answer silent.
pub chains: u8,
/// Chips reported per chain.
pub chips: u16,
/// Chip identifier on the wire (1 = bm1362).
pub chip: u8,
/// Report a working EEPROM instead of an absent one.
pub eeprom: bool,
/// PSU name and envelope, or `None` to fail identification.
pub psu: Option<(String, u16, u16, u16, u16, u16)>,
/// Fans on the simulated chassis; zones are distributed over them.
pub fans: u8,
}
impl Default for SimConfig {
fn default() -> Self {
Self {
chains: 3,
chips: 126,
chip: 1,
eeprom: false,
psu: Some(("APW12".into(), 1200, 1600, 0, 1000, 3600)),
fans: 2,
}
}
}
struct State {
config: SimConfig,
frequency_mhz: u16,
/// Duty per fan, so a zone can respond to the fan that actually cools it.
fan_pwm: [u8; 4],
}
impl State {
/// Which fan cools a zone. Zones are distributed over the fans round-robin.
fn owner(&self, zone: u8) -> usize {
let fans = usize::from(self.config.fans.max(1));
usize::from(zone) % fans
}
}
/// Serve one socket path until the program exits.
pub fn serve(path: &Path, config: SimConfig) -> io::Result<()> {
let _ = std::fs::remove_file(path);
let listener = UnixListener::bind(path)?;
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let mut state = State {
config: config.clone(),
frequency_mhz: 0,
fan_pwm: [100; 4],
};
let _ = serve_connection(stream, &mut state);
}
Ok(())
}
fn serve_connection(mut stream: UnixStream, state: &mut State) -> io::Result<()> {
loop {
let mut header = [0_u8; HEADER_LEN];
if stream.read_exact(&mut header).is_err() {
return Ok(());
}
if header[..4] != MAGIC {
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad HAL magic"));
}
let opcode = header[5];
let sequence = header[8..12].to_vec();
let length = u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && stream.read_exact(&mut payload).is_err() {
return Ok(());
}
let body = respond(opcode, &payload, state);
let mut out = [0_u8; HEADER_LEN];
out[..4].copy_from_slice(&MAGIC);
out[4] = VERSION;
out[5] = opcode;
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
stream.write_all(&out)?;
stream.write_all(&body)?;
stream.flush()?;
}
}
fn respond(opcode: u8, payload: &[u8], state: &mut State) -> Vec<u8> {
match opcode {
CAPABILITIES => {
let mut body = vec![0_u8];
body.extend_from_slice(&CAP_ALL.to_le_bytes());
body
}
PROBE_CHAIN => {
let chain = payload.first().copied().unwrap_or(0);
if chain >= state.config.chains {
return vec![0, 1, 0, 0, 0]; // silent
}
let chips = state.config.chips.to_le_bytes();
vec![0, 0, state.config.chip, chips[0], chips[1]]
}
READ_EEPROM => {
if state.config.eeprom {
let mut body = vec![0_u8, 0];
body.extend_from_slice(b"BHB42601");
body
} else {
vec![0, 1]
}
}
IDENTIFY_PSU => match &state.config.psu {
Some((name, v_min, v_max, f_min, f_max, watts)) => {
let mut body = vec![0_u8, name.len() as u8];
body.extend_from_slice(name.as_bytes());
for word in [*v_min, *v_max, *f_min, *f_max, *watts] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
None => vec![1],
},
SET_CHAIN_FREQUENCY => {
if let Some(mhz) = payload.get(1..3) {
state.frequency_mhz = u16::from_le_bytes([mhz[0], mhz[1]]);
}
vec![0]
}
SET_FAN_TARGET => {
let fan = usize::from(payload.first().copied().unwrap_or(0)).min(3);
state.fan_pwm[fan] = payload.get(1).copied().unwrap_or(0);
vec![0]
}
READ_TEMPERATURE => {
// Temperature rises with frequency so the tuner has something to regulate, and falls
// when the fan that owns the zone is fast so the fan sweep can learn the mapping.
let zone = payload.first().copied().unwrap_or(0);
let rise = i32::from(state.frequency_mhz) * 20;
let airflow = if state.fan_pwm[state.owner(zone)] >= 100 {
0
} else {
20_000
};
let mut body = vec![0_u8];
body.extend_from_slice(&(45_000 + rise + airflow).to_le_bytes());
body
}
READ_POWER => {
// Four watts per MHz, so a power target has something to regulate.
let watts = u16::try_from(u32::from(state.frequency_mhz) * 4).unwrap_or(u16::MAX);
let mut body = vec![0_u8];
body.extend_from_slice(&watts.to_le_bytes());
body
}
SET_CHAIN_RESET | SET_PSU_ENABLED => vec![0],
SEND_FRAME => vec![0],
RECEIVE_FRAME => {
// No nonce traffic in the reference backend.
let count: u16 = 0;
let mut body = vec![0_u8];
body.extend_from_slice(&count.to_le_bytes());
body
}
_ => vec![1],
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::FanProbe;
use crate::hal_wire::HalClient;
use crate::HardwareBackend;
#[test]
fn a_client_can_detect_against_the_reference_server() {
let path = std::env::temp_dir().join(format!("alkane-sim-hal-{}.sock", std::process::id()));
// Bind before spawning so the client cannot race the socket into existence.
let listener = UnixListener::bind(&path).expect("bind");
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
let mut state = State {
config: SimConfig::default(),
frequency_mhz: 0,
fan_pwm: [100; 4],
};
let _ = serve_connection(stream, &mut state);
});
let mut client = HalClient::connect(&path).expect("connect");
assert_eq!(client.capabilities().expect("caps"), CAP_ALL);
match client.probe_chain(0, 0).expect("probe") {
crate::detect::ProbeOutcome::Identified { chip, chips } => {
assert_eq!(chip, crate::detect::ChipModel::Bm1362);
assert_eq!(chips, 126);
}
other => panic!("unexpected probe: {other:?}"),
}
assert_eq!(
client.read_eeprom(0).expect("eeprom"),
crate::detect::EepromState::Absent
);
let psu = client.identify_psu().expect("psu");
assert_eq!(psu.name, "APW12");
client.set_chain_frequency(0, 512).expect("freq");
assert_eq!(client.read_power_w().expect("power"), 512 * 4);
// Zone 1 is owned by fan 1: slowing fan 1 must heat zone 1 and not zone 0.
let baseline_0 = client.read_temperature_mc(0).expect("temp");
let baseline_1 = client.read_temperature_mc(1).expect("temp");
client.set_fan(1, 40).expect("fan");
assert_eq!(client.read_temperature_mc(0).expect("temp"), baseline_0);
assert!(client.read_temperature_mc(1).expect("temp") > baseline_1);
assert_eq!(
client.read_temperature_mc(0).expect("temp"),
45_000 + 512 * 20
);
drop(client);
let _ = std::fs::remove_file(&path);
server.join().expect("server");
}
}
-286
View File
@@ -1,9 +1,6 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//! Versioned local wire contract between Alkane OS and an SDK hardware backend. //! Versioned local wire contract between Alkane OS and an SDK hardware backend.
use crate::detect::{
ChipModel, DetectionBackend, EepromState, Envelope, ProbeOutcome, PsuCapability,
};
use crate::HardwareBackend; use crate::HardwareBackend;
use std::fmt; use std::fmt;
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
@@ -27,27 +24,6 @@ const SET_CHAIN_RESET: u8 = 3;
const SET_FAN_TARGET: u8 = 4; const SET_FAN_TARGET: u8 = 4;
const READ_TEMPERATURE: u8 = 5; const READ_TEMPERATURE: u8 = 5;
const SET_PSU_ENABLED: u8 = 6; const SET_PSU_ENABLED: u8 = 6;
const CAPABILITIES: u8 = 7;
const PROBE_CHAIN: u8 = 8;
const READ_EEPROM: u8 = 9;
const IDENTIFY_PSU: u8 = 10;
const SET_CHAIN_FREQUENCY: u8 = 11;
const READ_POWER: u8 = 12;
/// Backend feature bits reported by `CAPABILITIES`.
pub const CAP_CHAIN_PROBE: u32 = 1 << 0;
pub const CAP_EEPROM: u32 = 1 << 1;
pub const CAP_PSU_IDENTITY: u32 = 1 << 2;
pub const CAP_FREQUENCY: u32 = 1 << 3;
pub const CAP_POWER: u32 = 1 << 4;
const PROBE_IDENTIFIED: u8 = 0;
const PROBE_SILENT: u8 = 1;
const PROBE_GARBLED: u8 = 2;
const EEPROM_PRESENT: u8 = 0;
const EEPROM_ABSENT: u8 = 1;
const EEPROM_INVALID: u8 = 2;
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
compile_error!("Alkane HAL sockets require Linux"); compile_error!("Alkane HAL sockets require Linux");
@@ -361,156 +337,6 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
Ok(stream) Ok(stream)
} }
impl HalClient {
/// Feature mask advertised by the backend. Old backends reject the opcode, which surfaces as
/// a protocol error rather than a silent zero.
pub fn capabilities(&mut self) -> Result<u32, HalError> {
let body = self.exchange(CAPABILITIES, &[])?;
let bytes: [u8; 4] = body
.try_into()
.map_err(|_| HalError::Protocol("invalid capability response"))?;
Ok(u32::from_le_bytes(bytes))
}
fn require(&mut self, capability: u32) -> Result<(), HalError> {
if self.capabilities()? & capability == 0 {
return Err(HalError::Protocol("backend lacks a detection capability"));
}
Ok(())
}
pub fn probe_chain(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, HalError> {
self.require(CAP_CHAIN_PROBE)?;
let body = self.exchange(PROBE_CHAIN, &[chain, attempt])?;
if body.len() != 4 {
self.poison();
return Err(HalError::Protocol("invalid probe response"));
}
let chips = u16::from_le_bytes([body[2], body[3]]);
match body[0] {
PROBE_IDENTIFIED => match chip_from_wire(body[1]) {
Some(chip) => Ok(ProbeOutcome::Identified { chip, chips }),
None => {
self.poison();
Err(HalError::Protocol("unknown chip identifier"))
}
},
PROBE_SILENT => Ok(ProbeOutcome::Silent),
PROBE_GARBLED => Ok(ProbeOutcome::Garbled),
_ => {
self.poison();
Err(HalError::Protocol("invalid probe outcome"))
}
}
}
pub fn read_eeprom(&mut self, chain: u8) -> Result<EepromState, HalError> {
self.require(CAP_EEPROM)?;
let body = self.exchange(READ_EEPROM, &[chain])?;
match body.first().copied() {
Some(EEPROM_ABSENT) if body.len() == 1 => Ok(EepromState::Absent),
Some(EEPROM_INVALID) if body.len() == 1 => Ok(EepromState::Invalid),
Some(EEPROM_PRESENT) if body.len() > 1 => {
let model = std::str::from_utf8(&body[1..])
.map_err(|_| HalError::Protocol("invalid EEPROM model text"))?;
Ok(EepromState::Present {
model: model.to_owned(),
})
}
_ => {
self.poison();
Err(HalError::Protocol("invalid EEPROM response"))
}
}
}
/// Apply a chain frequency in MHz. The backend owns the PLL write; the OS owns the decision.
pub fn set_chain_frequency(&mut self, chain: u8, mhz: u16) -> Result<(), HalError> {
self.require(CAP_FREQUENCY)?;
let mut payload = [0_u8; 3];
payload[0] = chain;
payload[1..].copy_from_slice(&mhz.to_le_bytes());
self.empty_reply(SET_CHAIN_FREQUENCY, &payload)
}
/// Measured DC input power in watts, when the board can read its PSU.
pub fn read_power_w(&mut self) -> Result<u16, HalError> {
self.require(CAP_POWER)?;
let body = self.exchange(READ_POWER, &[])?;
if body.len() != 2 {
self.poison();
return Err(HalError::Protocol("invalid power response"));
}
Ok(u16::from_le_bytes([body[0], body[1]]))
}
pub fn identify_psu(&mut self) -> Result<PsuCapability, HalError> {
self.require(CAP_PSU_IDENTITY)?;
let body = self.exchange(IDENTIFY_PSU, &[])?;
let name_len = *body
.first()
.ok_or(HalError::Protocol("empty PSU response"))? as usize;
if body.len() != name_len + 1 + 10 {
self.poison();
return Err(HalError::Protocol("invalid PSU response"));
}
let name = std::str::from_utf8(&body[1..1 + name_len])
.map_err(|_| HalError::Protocol("invalid PSU name"))?
.to_owned();
let at = 1 + name_len;
let word = |offset: usize| u16::from_le_bytes([body[at + offset], body[at + offset + 1]]);
Ok(PsuCapability {
name,
envelope: Envelope {
v_min_mv: word(0),
v_max_mv: word(2),
f_min_mhz: word(4),
f_max_mhz: word(6),
},
max_dc_watts: word(8),
})
}
}
impl DetectionBackend for HalClient {
type Error = HalError;
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error> {
self.probe_chain(chain, attempt)
}
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error> {
self.read_eeprom(chain)
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error> {
self.identify_psu().map(Some)
}
}
impl crate::fanmap::FanProbe for HalClient {
type Error = HalError;
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> {
self.set_fan_target(fan, pwm)
}
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error> {
self.read_temperature_mc(zone)
}
}
fn chip_from_wire(value: u8) -> Option<ChipModel> {
match value {
1 => Some(ChipModel::Bm1362),
2 => Some(ChipModel::Bm1366),
3 => Some(ChipModel::Bm1368),
4 => Some(ChipModel::Bm1370),
5 => Some(ChipModel::Bm1398),
_ => None,
}
}
impl HardwareBackend for HalClient { impl HardwareBackend for HalClient {
type Error = HalError; type Error = HalError;
@@ -577,115 +403,3 @@ impl HardwareBackend for HalClient {
result result
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::FanProbe;
use std::os::unix::net::UnixStream;
fn mock_backend(mut server: UnixStream) {
loop {
let mut header = [0_u8; 16];
if server.read_exact(&mut header).is_err() {
return;
}
let opcode = header[5];
let sequence = [header[8], header[9], header[10], header[11]];
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && server.read_exact(&mut payload).is_err() {
return;
}
let body: Vec<u8> = match opcode {
CAPABILITIES => {
let mut body = vec![0_u8];
body.extend_from_slice(
&(CAP_CHAIN_PROBE
| CAP_EEPROM
| CAP_PSU_IDENTITY
| CAP_FREQUENCY
| CAP_POWER)
.to_le_bytes(),
);
body
}
PROBE_CHAIN => vec![0, PROBE_IDENTIFIED, 1, 126, 0],
READ_EEPROM => {
let mut body = vec![0, EEPROM_PRESENT];
body.extend_from_slice(b"BHB42601");
body
}
IDENTIFY_PSU => {
let name = b"APW12";
let mut body = vec![0_u8];
body.push(name.len() as u8);
body.extend_from_slice(name);
for word in [1200_u16, 1600, 0, 1000, 3600] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
SET_FAN_TARGET | SET_CHAIN_FREQUENCY => vec![0],
READ_POWER => {
let mut body = vec![0_u8];
body.extend_from_slice(&0_u16.to_le_bytes());
body
}
READ_TEMPERATURE => {
let mut body = vec![0_u8];
body.extend_from_slice(&42_000_i32.to_le_bytes());
body
}
_ => vec![1],
};
let mut out = [0_u8; 16];
out[..4].copy_from_slice(&MAGIC);
out[4] = VERSION;
out[5] = opcode;
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
if server.write_all(&out).is_err() || server.write_all(&body).is_err() {
return;
}
}
}
#[test]
fn detection_verbs_round_trip_over_the_wire() {
let (client_stream, server_stream) = UnixStream::pair().expect("socket pair");
let server = std::thread::spawn(move || mock_backend(server_stream));
let mut client = HalClient::from_stream(client_stream).expect("client");
assert_eq!(
client.capabilities().expect("capabilities"),
CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY | CAP_POWER
);
match client.probe_chain(0, 0).expect("probe") {
ProbeOutcome::Identified { chip, chips } => {
assert_eq!(chip, ChipModel::Bm1362);
assert_eq!(chips, 126);
}
other => panic!("unexpected probe outcome: {other:?}"),
}
assert_eq!(
client.read_eeprom(0).expect("eeprom"),
EepromState::Present {
model: "BHB42601".into()
}
);
let psu = client.identify_psu().expect("psu");
assert_eq!(psu.name, "APW12");
assert_eq!(psu.envelope.v_min_mv, 1200);
assert_eq!(psu.envelope.v_max_mv, 1600);
assert_eq!(psu.max_dc_watts, 3600);
client.set_chain_frequency(2, 512).expect("set frequency");
client.set_fan(1, 60).expect("set fan");
assert_eq!(client.read_zone(2).expect("read zone"), 42_000);
drop(client);
server.join().expect("server thread");
}
}
-16
View File
@@ -3,37 +3,21 @@
//! An entry in the target matrix is a development obligation, not a claim that //! An entry in the target matrix is a development obligation, not a claim that
//! the pairing already mines. Hardware backends are supplied by SDK images. //! the pairing already mines. Hardware backends are supplied by SDK images.
pub mod app;
pub mod bm1362; pub mod bm1362;
pub mod bm1366; pub mod bm1366;
pub mod bm1370;
pub mod bm13xx; pub mod bm13xx;
pub mod detect;
pub mod difficulty; pub mod difficulty;
pub mod fanmap;
pub mod fanmap_store;
pub mod fault;
pub mod hal_conformance;
pub mod hal_sim;
pub mod hal_wire; pub mod hal_wire;
pub mod management; pub mod management;
pub mod miner; pub mod miner;
pub mod pow; pub mod pow;
pub mod profiles;
pub mod runtime;
pub mod scrypt_pow; pub mod scrypt_pow;
pub mod split;
pub mod stratum_client; pub mod stratum_client;
pub mod stratum_link;
pub mod stratum_session; pub mod stratum_session;
pub mod stratum_submit; pub mod stratum_submit;
pub mod stratum_v1; pub mod stratum_v1;
pub mod stratum_v2;
pub mod stratum_v2_session;
pub mod stratum_wire; pub mod stratum_wire;
pub mod stratum_work; pub mod stratum_work;
pub mod tuning;
pub mod web;
#[derive(Clone, Copy, Debug, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vendor { pub enum Vendor {
+10 -314
View File
@@ -1,17 +1,9 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
use alkane_os::app;
use alkane_os::detect::{
ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome,
PsuCapability, SensorTopology,
};
use alkane_os::hal_wire::HalClient; use alkane_os::hal_wire::HalClient;
use alkane_os::management::MiningStatus; use alkane_os::management::{bind_local, serve, MiningStatus};
use alkane_os::miner::{Bm1366Miner, ChipModel}; use alkane_os::miner::{Bm1366Miner, ChipModel};
use alkane_os::runtime::{Tick, TickOutcome};
use alkane_os::stratum_client::{PoolConnection, PoolEvent}; use alkane_os::stratum_client::{PoolConnection, PoolEvent};
use alkane_os::target_matrix; use alkane_os::target_matrix;
use alkane_os::tuning::{PidConfig, TuningTarget};
use alkane_os::HardwareBackend;
use std::error::Error; use std::error::Error;
use std::io; use std::io;
use std::net::SocketAddr; use std::net::SocketAddr;
@@ -34,21 +26,14 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
let password = std::env::var("ALKANE_POOL_PASSWORD") let password = std::env::var("ALKANE_POOL_PASSWORD")
.map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?; .map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?;
let status = Arc::new(MiningStatus::new()); let status = Arc::new(MiningStatus::new());
let api = std::env::var("ALKANE_API_LISTEN") if let Ok(bind) = std::env::var("ALKANE_API_LISTEN") {
.ok() let listener = bind_local(bind.parse()?)?;
.map(|bind| bind.parse()) let snapshot = Arc::clone(&status);
.transpose()?; std::thread::spawn(move || {
let web = std::env::var("ALKANE_WEB_LISTEN") if let Err(error) = serve(listener, snapshot) {
.ok() eprintln!("management API stopped: {error}");
.map(|bind| bind.parse()) }
.transpose()?; });
let servers = app::start(Arc::clone(&status), api, web)?;
let (api_address, web_address) = servers.addresses();
if let Some(address) = api_address {
println!("management API on {address}");
}
if let Some(address) = web_address {
println!("web UI on http://{address}/");
} }
// Connect to the pool before enabling power. The SDK HAL server owns the // Connect to the pool before enabling power. The SDK HAL server owns the
@@ -95,214 +80,6 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
} }
} }
/// A backend that answers without hardware, so the boot path can be exercised on any machine.
struct SelfCheckBackend;
impl DetectionBackend for SelfCheckBackend {
type Error = ();
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
Ok(ProbeOutcome::Identified {
chip: DetectedChip::Bm1362,
chips: 126,
})
}
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
Ok(EepromState::Absent)
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
Ok(Some(PsuCapability {
name: "APW12".into(),
envelope: Envelope {
v_min_mv: 1200,
v_max_mv: 1600,
f_min_mhz: 0,
f_max_mhz: 1000,
},
max_dc_watts: 3600,
}))
}
}
/// Run detection, the runtime loop and the API document against the self-check backend.
///
/// This is the smoke test an image can run on a bench machine before any hashboard is attached:
/// it proves the profile database parses, detection produces a plan, the tuner moves within the
/// envelope and the published document is well formed.
fn self_check() -> Result<(), Box<dyn Error>> {
let status = MiningStatus::new();
let config = app::BootConfig {
profile_db_json: include_str!("../profiles.example.json").to_owned(),
chain_ports: vec![0, 1, 2],
sensor: SensorTopology::Pic,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target: TuningTarget::PowerW(2_400.0),
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: Default::default(),
};
let mut backend = SelfCheckBackend;
let mut runtime = app::boot(&mut backend, &config, &status)?;
let start = runtime.operating_point().frequency_mhz;
for _ in 0..20 {
let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz);
runtime.tick(&Tick {
power_w: Some(power),
hashrate_ths: None,
hottest_mc: Some(70_000),
ambient_mc: None,
dt_s: 1.0,
});
}
let end = runtime.operating_point().frequency_mhz;
if end <= start {
return Err("self-check: frequency did not move toward the target".into());
}
if runtime.active_chains().len() != 3 {
return Err("self-check: detection did not expose three chains".into());
}
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
let document = status.hardware_document();
if document["available"] != true {
return Err("self-check: hardware document is not available".into());
}
println!("{}", serde_json::to_string_pretty(&document)?);
Ok(())
}
fn parse_target(text: &str) -> Result<TuningTarget, Box<dyn Error>> {
let (kind, value) = text
.split_once(':')
.ok_or("target must look like power:2400")?;
let value: f32 = value.parse()?;
Ok(match kind {
"power" => TuningTarget::PowerW(value),
"hashrate" => TuningTarget::HashrateThs(value),
"ambient" => TuningTarget::AmbientC {
margin_mc: value as i32,
},
"fan" => TuningTarget::MaxFan {
max_pwm: value as u8,
},
_ => return Err("target must be power, hashrate, ambient or fan".into()),
})
}
/// Boot a real board through the HAL socket, then run a bounded tuning loop.
fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let socket = args.next().ok_or("missing HAL socket")?;
let profiles = args.next().ok_or("missing profile database path")?;
let target = parse_target(&args.next().ok_or("missing target")?)?;
let sensor = match args.next().as_deref() {
Some("nopic") => SensorTopology::NoPic,
Some("pic") | None => SensorTopology::Pic,
Some(_) => return Err("sensor must be pic or nopic".into()),
};
let ticks: usize = args
.next()
.map(|value| value.parse())
.transpose()?
.unwrap_or(30);
let profile_db_json = std::fs::read_to_string(&profiles)?;
let status = Arc::new(MiningStatus::new());
let api = std::env::var("ALKANE_API_LISTEN")
.ok()
.map(|bind| bind.parse())
.transpose()?;
let web = std::env::var("ALKANE_WEB_LISTEN")
.ok()
.map(|bind| bind.parse())
.transpose()?;
let servers = app::start(Arc::clone(&status), api, web)?;
let config = app::BootConfig {
profile_db_json,
chain_ports: vec![0, 1, 2],
sensor,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target,
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: Default::default(),
};
let map_path = std::path::PathBuf::from(
std::env::var("ALKANE_FANMAP").unwrap_or_else(|_| "/var/lib/alkane/fanmap.json".into()),
);
// Fan mapping is opt-in: it perturbs the machine and takes minutes, so a plain boot skips it.
let fans: u8 = std::env::var("ALKANE_FAN_FANS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let zones: u8 = std::env::var("ALKANE_FAN_ZONES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let settings = app::HalBoot {
config: &config,
sweep: alkane_os::fanmap::SweepConfig {
fans,
zones,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: std::env::var("ALKANE_FAN_SETTLE_MS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(20_000),
},
thresholds: Default::default(),
map_path: &map_path,
};
let (mut runtime, _map) =
app::boot_from_hal(std::path::Path::new(&socket), &settings, &status)?;
println!(
"detected {} with {} active chains",
runtime.plan().profile,
runtime.active_chains().len()
);
let mut client = HalClient::connect(std::path::Path::new(&socket))?;
let label = app::target_label(&config.target);
for _ in 0..ticks {
let hottest = client.read_temperature_mc(0).ok();
let power_w = client.read_power_w().ok().map(f32::from);
let outcome = runtime.tick(&Tick {
power_w,
hashrate_ths: None,
hottest_mc: hottest,
ambient_mc: None,
dt_s: 1.0,
});
if let TickOutcome::Run(command) = outcome {
for chain in runtime.active_chains() {
client.set_chain_frequency(chain, command.frequency_mhz)?;
}
if let Some(pwm) = command.fan_pwm {
client.set_fan_target(0, pwm)?;
}
}
// Publish every period: a client watching the API must see the live operating point,
// not the boot-time snapshot.
status.set_hardware(app::snapshot(&runtime, &label));
if let Some(reason) = runtime.stop_reason() {
println!("stopped: {reason:?}");
break;
}
std::thread::sleep(Duration::from_millis(50));
}
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
println!(
"{}",
serde_json::to_string_pretty(&status.hardware_document())?
);
let _ = servers;
Ok(())
}
fn main() { fn main() {
let mut args = std::env::args().skip(1); let mut args = std::env::args().skip(1);
match args.next().as_deref() { match args.next().as_deref() {
@@ -316,84 +93,6 @@ fn main() {
} }
} }
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")), Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
Some("--boot") => {
if let Err(error) = boot_hal(args) {
eprintln!("boot failed: {error}");
std::process::exit(1);
}
}
Some("--sim-hal") => {
let socket = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --sim-hal SOCKET");
std::process::exit(2);
}
};
if let Err(error) = alkane_os::hal_sim::serve(
std::path::Path::new(&socket),
alkane_os::hal_sim::SimConfig::default(),
) {
eprintln!("reference HAL stopped: {error}");
std::process::exit(1);
}
}
Some("--check-profiles") => {
let path = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --check-profiles PATH");
std::process::exit(2);
}
};
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
eprintln!("cannot read {path}: {error}");
std::process::exit(1);
}
};
match alkane_os::profiles::ProfileDb::from_json(&text) {
Ok(db) => {
println!("{} profiles, schema 1, validated", db.len());
}
Err(error) => {
eprintln!("profile database rejected: {error:?}");
std::process::exit(1);
}
}
}
Some("--check-hal") => {
let socket = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --check-hal SOCKET");
std::process::exit(2);
}
};
let checks = alkane_os::hal_conformance::run(std::path::Path::new(&socket));
let mut failed = 0;
for check in &checks {
println!(
"{:<28} {:<4} {}",
check.name,
if check.passed { "PASS" } else { "FAIL" },
check.detail
);
if !check.passed {
failed += 1;
}
}
if failed > 0 {
std::process::exit(1);
}
}
Some("--self-check") => {
if let Err(error) = self_check() {
eprintln!("self-check failed: {error}");
std::process::exit(1);
}
}
Some("--mine-simulator") => { Some("--mine-simulator") => {
if let Err(error) = sim_mine(args) { if let Err(error) = sim_mine(args) {
eprintln!("simulator mining failed: {error}"); eprintln!("simulator mining failed: {error}");
@@ -401,10 +100,7 @@ fn main() {
} }
} }
_ => { _ => {
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); eprintln!("usage: alkane-os --list-targets | --version | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
eprintln!(
"env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..."
);
std::process::exit(2); std::process::exit(2);
} }
} }
-196
View File
@@ -1,39 +1,23 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//! Bounded, read-only cgminer-style status for a local management client. //! Bounded, read-only cgminer-style status for a local management client.
use crate::detect::{EepromState, HardwarePlan};
use serde_json::{json, Value}; use serde_json::{json, Value};
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream}; use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const MAX_REQUEST_BYTES: usize = 2048; const MAX_REQUEST_BYTES: usize = 2048;
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500); const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
const REQUEST_DEADLINE: Duration = Duration::from_secs(2); const REQUEST_DEADLINE: Duration = Duration::from_secs(2);
/// Everything the extended API exposes beyond share counters.
#[derive(Clone, Debug, PartialEq)]
pub struct HardwareSnapshot {
pub plan: HardwarePlan,
/// Chains the supervisor still allows work on.
pub active_chains: Vec<u8>,
/// `None` while hashing; otherwise why the machine stopped.
pub stopped: Option<&'static str>,
pub frequency_mhz: u16,
/// Operator target in the form `power:3000`, `hashrate:200`, `ambient:20000`, `fan:100`.
pub target: String,
}
#[derive(Debug)] #[derive(Debug)]
pub struct MiningStatus { pub struct MiningStatus {
started: Instant, started: Instant,
running: AtomicBool, running: AtomicBool,
accepted: AtomicU64, accepted: AtomicU64,
rejected: AtomicU64, rejected: AtomicU64,
hardware: Mutex<Option<HardwareSnapshot>>,
} }
impl Default for MiningStatus { impl Default for MiningStatus {
@@ -49,31 +33,9 @@ impl MiningStatus {
running: AtomicBool::new(false), running: AtomicBool::new(false),
accepted: AtomicU64::new(0), accepted: AtomicU64::new(0),
rejected: AtomicU64::new(0), rejected: AtomicU64::new(0),
hardware: Mutex::new(None),
} }
} }
/// Publish the current hardware view for the API.
pub fn set_hardware(&self, snapshot: HardwareSnapshot) {
if let Ok(mut slot) = self.hardware.lock() {
*slot = Some(snapshot);
}
}
/// The `hardware` document, for the on-box UI and local clients.
pub fn hardware_document(&self) -> Value {
hardware_json(self.hardware())
}
/// The `summary` document, for the on-box UI and local clients.
pub fn summary_document(&self) -> Value {
self.response("summary")
}
fn hardware(&self) -> Option<HardwareSnapshot> {
self.hardware.lock().ok().and_then(|slot| slot.clone())
}
pub fn set_running(&self, running: bool) { pub fn set_running(&self, running: bool) {
self.running.store(running, Ordering::Relaxed); self.running.store(running, Ordering::Relaxed);
} }
@@ -110,16 +72,6 @@ impl MiningStatus {
"API": "1.0" "API": "1.0"
}]}), }]}),
), ),
"hardware" => (
"S",
"Hardware",
json!({"HARDWARE": [hardware_json(self.hardware())]}),
),
"stats" => (
"S",
"Stats",
json!({"STATS": [stats_json(self.hardware())]}),
),
_ => ("E", "Unknown command", json!({})), _ => ("E", "Unknown command", json!({})),
}; };
let mut response = json!({"STATUS": [{ let mut response = json!({"STATUS": [{
@@ -137,69 +89,6 @@ impl MiningStatus {
} }
} }
fn eeprom_json(state: &EepromState) -> Value {
match state {
EepromState::Present { model } => json!({"state": "present", "model": model}),
EepromState::Absent => json!({"state": "absent"}),
EepromState::Invalid => json!({"state": "invalid"}),
}
}
fn hardware_json(snapshot: Option<HardwareSnapshot>) -> Value {
let Some(snapshot) = snapshot else {
return json!({"available": false});
};
let plan = &snapshot.plan;
json!({
"available": true,
"profile": plan.profile,
"chip": plan.chip.name(),
"psu": plan.psu,
"envelope": {
"v_min_mv": plan.envelope.v_min_mv,
"v_max_mv": plan.envelope.v_max_mv,
"f_min_mhz": plan.envelope.f_min_mhz,
"f_max_mhz": plan.envelope.f_max_mhz,
},
"operating_point": {
"voltage_mv": plan.envelope.voltage_for(snapshot.frequency_mhz),
"frequency_mhz": snapshot.frequency_mhz,
"confirmed": plan.operating_point.confirmed,
},
"chains": plan.chains.iter().map(|chain| json!({
"index": chain.index,
"chip": chain.chip.name(),
"chips_found": chain.chips_found,
"eeprom": eeprom_json(&chain.eeprom),
"response_per_mille": chain.response_per_mille,
})).collect::<Vec<_>>(),
"fan_zones": plan.fan_zones.iter().map(|zone| json!({
"fan": zone.fan,
"zones": zone.zones,
})).collect::<Vec<_>>(),
"active_chains": snapshot.active_chains,
"stopped": snapshot.stopped,
"target": snapshot.target,
"frequency_mhz": snapshot.frequency_mhz,
})
}
fn stats_json(snapshot: Option<HardwareSnapshot>) -> Value {
let Some(snapshot) = snapshot else {
return json!({"available": false});
};
json!({
"Profile": snapshot.plan.profile,
"Chip": snapshot.plan.chip.name(),
"PSU": snapshot.plan.psu,
"FrequencyMHz": snapshot.frequency_mhz,
"VoltageMV": snapshot.plan.envelope.voltage_for(snapshot.frequency_mhz),
"Target": snapshot.target,
"ActiveChains": snapshot.active_chains.len(),
"Stopped": snapshot.stopped,
})
}
fn request_command(bytes: &[u8]) -> Option<&str> { fn request_command(bytes: &[u8]) -> Option<&str> {
let request = std::str::from_utf8(bytes).ok()?.trim(); let request = std::str::from_utf8(bytes).ok()?.trim();
if request.starts_with('{') { if request.starts_with('{') {
@@ -208,16 +97,12 @@ fn request_command(bytes: &[u8]) -> Option<&str> {
match command { match command {
"summary" => Some("summary"), "summary" => Some("summary"),
"version" => Some("version"), "version" => Some("version"),
"hardware" => Some("hardware"),
"stats" => Some("stats"),
_ => Some("unknown"), _ => Some("unknown"),
} }
} else { } else {
match request { match request {
"summary" => Some("summary"), "summary" => Some("summary"),
"version" => Some("version"), "version" => Some("version"),
"hardware" => Some("hardware"),
"stats" => Some("stats"),
_ => Some("unknown"), _ => Some("unknown"),
} }
} }
@@ -361,85 +246,4 @@ mod tests {
assert!(parsed.get("SUMMARY").is_some()); assert!(parsed.get("SUMMARY").is_some());
worker.join().unwrap(); worker.join().unwrap();
} }
fn snapshot() -> HardwareSnapshot {
HardwareSnapshot {
plan: HardwarePlan {
profile: "s19jpro-bm1362-pic".into(),
chip: crate::detect::ChipModel::Bm1362,
chains: vec![crate::detect::ChainReport {
index: 0,
chip: crate::detect::ChipModel::Bm1362,
chips_found: 126,
eeprom: EepromState::Absent,
response_per_mille: Some(950),
}],
envelope: crate::detect::Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
operating_point: crate::detect::OperatingPoint {
voltage_mv: 1200,
frequency_mhz: 500,
confirmed: false,
},
psu: "APW12".into(),
fan_zones: vec![crate::detect::FanZone {
fan: 0,
zones: vec![0, 1],
}],
},
active_chains: vec![0],
stopped: None,
frequency_mhz: 512,
target: "power:3000".into(),
}
}
#[test]
fn hardware_is_unavailable_until_published() {
let status = MiningStatus::new();
let reply = status.response("hardware");
assert_eq!(reply["HARDWARE"][0]["available"], false);
}
#[test]
fn hardware_command_exposes_detection_and_fault_state() {
let status = MiningStatus::new();
status.set_hardware(snapshot());
let reply = status.response("hardware");
let hardware = &reply["HARDWARE"][0];
assert_eq!(hardware["available"], true);
assert_eq!(hardware["profile"], "s19jpro-bm1362-pic");
assert_eq!(hardware["chip"], "bm1362");
assert_eq!(hardware["psu"], "APW12");
assert_eq!(hardware["chains"][0]["chips_found"], 126);
assert_eq!(hardware["chains"][0]["eeprom"]["state"], "absent");
assert_eq!(hardware["operating_point"]["confirmed"], false);
assert_eq!(hardware["active_chains"][0], 0);
assert_eq!(hardware["target"], "power:3000");
assert_eq!(hardware["fan_zones"][0]["zones"][1], 1);
}
#[test]
fn stats_command_keeps_cgminer_shape() {
let status = MiningStatus::new();
status.set_hardware(snapshot());
let reply = status.response("stats");
let stats = &reply["STATS"][0];
assert_eq!(stats["Profile"], "s19jpro-bm1362-pic");
assert_eq!(stats["FrequencyMHz"], 512);
assert_eq!(stats["VoltageMV"], 1312);
assert_eq!(stats["ActiveChains"], 1);
assert!(stats["Stopped"].is_null());
}
#[test]
fn unknown_commands_still_refuse() {
let status = MiningStatus::new();
let reply = status.response("reboot");
assert_eq!(reply["STATUS"][0]["STATUS"], "E");
}
} }
-236
View File
@@ -1,236 +0,0 @@
// SPDX-License-Identifier: MIT
//! Board profile database.
//!
//! Profiles carry the safe voltage/frequency envelope a chip/board combination may run inside.
//! Detection may only use what this database provides: if a combination is absent, the answer is
//! "refuse", never "assume a number". Entries are data, so they can be filled from captures
//! without touching code.
use crate::detect::{BoardProfile, ChipModel, Envelope, SensorTopology};
use serde_json::Value;
/// Why a profile database was rejected.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProfileError {
InvalidJson,
UnsupportedSchema,
MissingProfiles,
UnknownChip(String),
UnknownSensor(String),
InvalidEnvelope(String),
DuplicateName(String),
}
/// A validated set of profiles.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ProfileDb {
profiles: Vec<BoardProfile>,
}
impl ProfileDb {
/// Validate and keep a set of profiles.
pub fn new(profiles: Vec<BoardProfile>) -> Result<Self, ProfileError> {
for (index, profile) in profiles.iter().enumerate() {
if profiles[..index]
.iter()
.any(|other| other.name == profile.name)
{
return Err(ProfileError::DuplicateName(profile.name.clone()));
}
if profile.chains == 0 {
return Err(ProfileError::InvalidEnvelope(profile.name.clone()));
}
let envelope = profile.envelope;
if envelope.v_min_mv == 0
|| envelope.v_min_mv > envelope.v_max_mv
|| envelope.f_min_mhz > envelope.f_max_mhz
{
return Err(ProfileError::InvalidEnvelope(profile.name.clone()));
}
}
Ok(Self { profiles })
}
/// Parse the schema-1 profile document.
pub fn from_json(text: &str) -> Result<Self, ProfileError> {
let root: Value = serde_json::from_str(text).map_err(|_| ProfileError::InvalidJson)?;
match root.get("schema").and_then(Value::as_u64) {
Some(1) => {}
Some(_) => return Err(ProfileError::UnsupportedSchema),
None => return Err(ProfileError::UnsupportedSchema),
}
let entries = root
.get("profiles")
.and_then(Value::as_array)
.ok_or(ProfileError::MissingProfiles)?;
let mut profiles = Vec::with_capacity(entries.len());
for entry in entries {
profiles.push(profile_from_value(entry)?);
}
if profiles.is_empty() {
return Err(ProfileError::MissingProfiles);
}
Self::new(profiles)
}
/// Exact lookup: a profile only applies to the chip, chain count and sensor wiring it declares.
pub fn find(
&self,
chip: ChipModel,
chains: u8,
sensor: SensorTopology,
) -> Option<&BoardProfile> {
self.profiles.iter().find(|profile| {
profile.chip == chip && profile.chains == chains && profile.sensor == sensor
})
}
pub fn len(&self) -> usize {
self.profiles.len()
}
pub fn is_empty(&self) -> bool {
self.profiles.is_empty()
}
}
fn profile_from_value(entry: &Value) -> Result<BoardProfile, ProfileError> {
let name = entry
.get("name")
.and_then(Value::as_str)
.ok_or(ProfileError::InvalidJson)?
.to_owned();
let chip_text = entry
.get("chip")
.and_then(Value::as_str)
.ok_or(ProfileError::UnknownChip(name.clone()))?;
let chip = match chip_text {
"bm1362" => ChipModel::Bm1362,
"bm1366" => ChipModel::Bm1366,
"bm1368" => ChipModel::Bm1368,
"bm1370" => ChipModel::Bm1370,
"bm1398" => ChipModel::Bm1398,
other => return Err(ProfileError::UnknownChip(other.to_owned())),
};
let sensor_text = entry
.get("sensor")
.and_then(Value::as_str)
.ok_or(ProfileError::UnknownSensor(name.clone()))?;
let sensor = match sensor_text {
"pic" => SensorTopology::Pic,
"nopic" => SensorTopology::NoPic,
"unknown" => SensorTopology::Unknown,
other => return Err(ProfileError::UnknownSensor(other.to_owned())),
};
let chains = entry
.get("chains")
.and_then(Value::as_u64)
.and_then(|value| u8::try_from(value).ok())
.ok_or(ProfileError::InvalidEnvelope(name.clone()))?;
let envelope = entry
.get("envelope")
.and_then(Value::as_object)
.ok_or(ProfileError::InvalidEnvelope(name.clone()))?;
let field = |key: &str| -> Result<u16, ProfileError> {
envelope
.get(key)
.and_then(Value::as_u64)
.and_then(|value| u16::try_from(value).ok())
.ok_or(ProfileError::InvalidEnvelope(name.clone()))
};
let envelope = Envelope {
v_min_mv: field("v_min_mv")?,
v_max_mv: field("v_max_mv")?,
f_min_mhz: field("f_min_mhz")?,
f_max_mhz: field("f_max_mhz")?,
};
Ok(BoardProfile {
name,
chip,
sensor,
chains,
envelope,
})
}
#[cfg(test)]
mod tests {
use super::*;
const VALID: &str = r#"{
"schema": 1,
"profiles": [
{
"name": "s19jpro-bm1362-pic",
"chip": "bm1362",
"sensor": "pic",
"chains": 3,
"envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700}
}
]
}"#;
#[test]
fn valid_document_loads_and_resolves() {
let db = ProfileDb::from_json(VALID).expect("db");
assert_eq!(db.len(), 1);
let profile = db
.find(ChipModel::Bm1362, 3, SensorTopology::Pic)
.expect("profile");
assert_eq!(profile.name, "s19jpro-bm1362-pic");
assert_eq!(profile.envelope.v_max_mv, 1500);
assert!(db.find(ChipModel::Bm1362, 2, SensorTopology::Pic).is_none());
assert!(db
.find(ChipModel::Bm1362, 3, SensorTopology::NoPic)
.is_none());
}
#[test]
fn unknown_chip_is_rejected() {
let text = VALID.replace("bm1362", "bm9999");
assert_eq!(
ProfileDb::from_json(&text),
Err(ProfileError::UnknownChip("bm9999".into()))
);
}
#[test]
fn inverted_envelope_is_rejected() {
let text = VALID.replace(
"\"v_min_mv\": 1100, \"v_max_mv\": 1500",
"\"v_min_mv\": 1500, \"v_max_mv\": 1100",
);
assert!(matches!(
ProfileDb::from_json(&text),
Err(ProfileError::InvalidEnvelope(_))
));
}
#[test]
fn wrong_schema_is_rejected() {
let text = VALID.replace("\"schema\": 1", "\"schema\": 2");
assert_eq!(
ProfileDb::from_json(&text),
Err(ProfileError::UnsupportedSchema)
);
}
#[test]
fn missing_profiles_are_rejected() {
assert_eq!(
ProfileDb::from_json("{\"schema\": 1}"),
Err(ProfileError::MissingProfiles)
);
}
#[test]
fn duplicate_names_are_rejected() {
let one = VALID.split("\"profiles\": [").nth(1).unwrap();
let entry = one.trim().trim_end_matches("]\n }").trim();
let duplicated = format!("{{\"schema\": 1, \"profiles\": [{entry}, {entry}]}}");
assert!(matches!(
ProfileDb::from_json(&duplicated),
Err(ProfileError::DuplicateName(_))
));
}
}
-287
View File
@@ -1,287 +0,0 @@
// SPDX-License-Identifier: MIT
//! Mining runtime: one state machine over the detection plan, the fault ladder and the tuner.
//!
//! Each tick takes a measurement, lets the tuner move the operating point, and lets the fault
//! supervisor veto the machine. The pieces are tested in isolation elsewhere; this module is the
//! place where their order is decided, and the order matters: a stopped machine must not be tuned,
//! and a disabled chain must not be dispatched to.
use crate::detect::{HardwarePlan, OperatingPoint};
use crate::fault::{FaultAction, FaultEvent, FaultPolicy, FaultSupervisor, StopReason};
use crate::tuning::{Command, Observation, PidConfig, TuningError, TuningLoop, TuningTarget};
/// One control period's measurements.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tick {
pub power_w: Option<f32>,
pub hashrate_ths: Option<f32>,
pub hottest_mc: Option<i32>,
pub ambient_mc: Option<i32>,
pub dt_s: f32,
}
/// What the runtime decided for this period.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TickOutcome {
/// Apply this command to the hardware.
Run(Command),
/// Measurement missing; hold the previous operating point.
Hold(Command),
/// The machine is stopped and must not hash.
Stopped(StopReason),
}
/// Runtime state for one machine.
#[derive(Clone, Debug)]
pub struct MinerRuntime {
plan: HardwarePlan,
faults: FaultSupervisor,
tuning: TuningLoop,
last_command: Command,
}
impl MinerRuntime {
pub fn new(
plan: HardwarePlan,
policy: FaultPolicy,
target: TuningTarget,
pid: PidConfig,
ceiling_mc: i32,
) -> Self {
let chains: Vec<u8> = plan.chains.iter().map(|chain| chain.index).collect();
let last_command = Command {
frequency_mhz: plan.operating_point.frequency_mhz,
fan_pwm: None,
};
Self {
faults: FaultSupervisor::new(&chains, policy),
tuning: TuningLoop::new(target, plan.envelope, pid, ceiling_mc),
plan,
last_command,
}
}
pub fn plan(&self) -> &HardwarePlan {
&self.plan
}
pub fn operating_point(&self) -> OperatingPoint {
OperatingPoint {
voltage_mv: self
.plan
.envelope
.voltage_for(self.last_command.frequency_mhz),
frequency_mhz: self.last_command.frequency_mhz,
confirmed: self.plan.operating_point.confirmed,
}
}
pub fn active_chains(&self) -> Vec<u8> {
self.faults.active_chains()
}
pub fn stop_reason(&self) -> Option<StopReason> {
self.faults.stop_reason()
}
/// Feed one health observation; returns what the supervisor decided.
pub fn on_event(&mut self, event: FaultEvent) -> FaultAction {
self.faults.observe(event)
}
/// Advance one control period.
pub fn tick(&mut self, tick: &Tick) -> TickOutcome {
if let Some(reason) = self.faults.stop_reason() {
return TickOutcome::Stopped(reason);
}
let observation = Observation {
power_w: tick.power_w,
hashrate_ths: tick.hashrate_ths,
hottest_mc: tick.hottest_mc,
ambient_mc: tick.ambient_mc,
};
match self.tuning.step(observation, tick.dt_s) {
Ok(command) => {
self.last_command = command;
TickOutcome::Run(command)
}
Err(TuningError::NoMeasurement) => TickOutcome::Hold(self.last_command),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::{ChainReport, ChipModel, EepromState, Envelope, FanZone};
fn plan() -> HardwarePlan {
HardwarePlan {
profile: "s19jpro-bm1362-pic".into(),
chip: ChipModel::Bm1362,
chains: (0..3)
.map(|index| ChainReport {
index,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom: EepromState::Absent,
response_per_mille: Some(950),
})
.collect(),
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
operating_point: OperatingPoint {
voltage_mv: 1200,
frequency_mhz: 300,
confirmed: false,
},
psu: "APW12".into(),
fan_zones: vec![FanZone {
fan: 0,
zones: vec![0],
}],
}
}
fn runtime() -> MinerRuntime {
MinerRuntime::new(
plan(),
FaultPolicy::default(),
TuningTarget::PowerW(2_400.0),
PidConfig {
kp: 0.2,
ki: 0.05,
kd: 0.0,
out_min: 0.0,
out_max: 0.0,
max_step_per_s: 50.0,
deadband: 0.0,
},
95_000,
)
}
fn tick(power: f32) -> Tick {
Tick {
power_w: Some(power),
hashrate_ths: None,
hottest_mc: Some(70_000),
ambient_mc: None,
dt_s: 1.0,
}
}
#[test]
fn a_fresh_runtime_exposes_every_chain() {
assert_eq!(runtime().active_chains(), vec![0, 1, 2]);
assert_eq!(runtime().stop_reason(), None);
}
#[test]
fn ticks_move_frequency_inside_the_envelope() {
let mut runtime = runtime();
let mut frequency = 300;
for _ in 0..60 {
let power = 4.0 * f32::from(frequency);
if let TickOutcome::Run(command) = runtime.tick(&tick(power)) {
frequency = command.frequency_mhz;
assert!((300..=700).contains(&frequency));
}
}
assert!(frequency > 300, "frequency never moved: {frequency}");
}
#[test]
fn a_missing_measurement_holds_the_last_command() {
let mut runtime = runtime();
let empty = Tick {
power_w: None,
hashrate_ths: None,
hottest_mc: None,
ambient_mc: None,
dt_s: 1.0,
};
match runtime.tick(&empty) {
TickOutcome::Hold(command) => assert_eq!(command.frequency_mhz, 300),
other => panic!("unexpected outcome: {other:?}"),
}
}
#[test]
fn a_dead_chain_is_removed_from_dispatch_without_stopping_the_machine() {
let mut runtime = runtime();
assert_eq!(
runtime.on_event(FaultEvent::ChainError { chain: 1 }),
FaultAction::Retry { chain: 1 }
);
assert_eq!(
runtime.on_event(FaultEvent::ChainError { chain: 1 }),
FaultAction::Retry { chain: 1 }
);
assert_eq!(
runtime.on_event(FaultEvent::ChainError { chain: 1 }),
FaultAction::DisableChain { chain: 1 }
);
assert_eq!(runtime.active_chains(), vec![0, 2]);
assert!(matches!(runtime.tick(&tick(2_000.0)), TickOutcome::Run(_)));
}
#[test]
fn a_temperature_fault_stops_the_machine_for_good() {
let mut runtime = runtime();
assert_eq!(
runtime.on_event(FaultEvent::TemperatureFault { zone: 1 }),
FaultAction::Stop {
reason: StopReason::Temperature
}
);
assert_eq!(
runtime.tick(&tick(2_400.0)),
TickOutcome::Stopped(StopReason::Temperature)
);
assert_eq!(
runtime.tick(&tick(2_400.0)),
TickOutcome::Stopped(StopReason::Temperature)
);
}
#[test]
fn losing_every_chain_stops_the_machine() {
let mut runtime = MinerRuntime::new(
plan(),
FaultPolicy {
retries: 0,
..FaultPolicy::default()
},
TuningTarget::PowerW(2_400.0),
PidConfig::default(),
95_000,
);
for chain in 0..3 {
runtime.on_event(FaultEvent::ChainError { chain });
}
assert_eq!(runtime.stop_reason(), Some(StopReason::NoChainsLeft));
assert!(runtime.active_chains().is_empty());
}
#[test]
fn the_operating_point_reflects_the_last_command() {
let mut runtime = runtime();
for _ in 0..10 {
runtime.tick(&tick(1_500.0));
}
let point = runtime.operating_point();
assert!(point.frequency_mhz > 300);
assert!(!point.confirmed);
// Voltage follows the frequency across the envelope instead of staying at the boot value.
assert_eq!(
point.voltage_mv,
runtime.plan().envelope.voltage_for(point.frequency_mhz)
);
assert!(point.voltage_mv > 1100);
}
}
-172
View File
@@ -1,172 +0,0 @@
// SPDX-License-Identifier: MIT
//! Hashrate splitting across pools.
//!
//! Splitting is per work slot: each dispatched job comes from exactly one pool, and the router
//! hands out slots in proportion to the configured weights. Smooth weighted round-robin is used
//! because it keeps the mix correct at every prefix, not just over a long run, which matters when
//! a miner only has a handful of chains.
/// Why a split configuration was rejected.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SplitError {
Empty,
NoWeight,
InvalidNumber,
TooManyPools,
}
/// Per-pool weights, `50,50` style.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SplitWeights {
weights: Vec<u32>,
}
impl SplitWeights {
/// Parse a comma-separated weight list such as `"60,40"`.
pub fn parse(text: &str) -> Result<Self, SplitError> {
let mut weights = Vec::new();
for part in text.split(',') {
let trimmed = part.trim();
if trimmed.is_empty() {
return Err(SplitError::InvalidNumber);
}
let weight: u32 = trimmed.parse().map_err(|_| SplitError::InvalidNumber)?;
weights.push(weight);
}
Self::new(weights)
}
pub fn new(weights: Vec<u32>) -> Result<Self, SplitError> {
if weights.is_empty() {
return Err(SplitError::Empty);
}
if weights.len() > 16 {
return Err(SplitError::TooManyPools);
}
if weights.iter().all(|weight| *weight == 0) {
return Err(SplitError::NoWeight);
}
Ok(Self { weights })
}
pub fn pools(&self) -> usize {
self.weights.len()
}
pub fn weight(&self, pool: usize) -> u32 {
self.weights.get(pool).copied().unwrap_or(0)
}
/// Split `slots` work slots across the pools and return how many each receives.
pub fn allocate(&self, slots: usize) -> Vec<usize> {
let mut router = WorkRouter::new(self.clone());
let mut counts = vec![0_usize; self.pools()];
for _ in 0..slots {
counts[router.next_pool()] += 1;
}
counts
}
}
/// Smooth weighted round-robin state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkRouter {
weights: SplitWeights,
current: Vec<i64>,
total: i64,
}
impl WorkRouter {
pub fn new(weights: SplitWeights) -> Self {
let current = vec![0_i64; weights.pools()];
let total: i64 = weights
.weights
.iter()
.map(|weight| i64::from(*weight))
.sum();
Self {
weights,
current,
total,
}
}
/// Which pool supplies the next work slot.
///
/// A pool with weight 0 never receives a slot. The winner's running score is reduced by the
/// total weight, which is what keeps the distribution proportional at every prefix.
pub fn next_pool(&mut self) -> usize {
let mut winner = 0;
for pool in 0..self.weights.pools() {
self.current[pool] += i64::from(self.weights.weight(pool));
if self.current[pool] > self.current[winner] {
winner = pool;
}
}
self.current[winner] -= self.total;
winner
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_weights_split_evenly() {
let weights = SplitWeights::parse("50,50").expect("weights");
assert_eq!(weights.allocate(10), vec![5, 5]);
assert_eq!(weights.allocate(4), vec![2, 2]);
}
#[test]
fn unequal_weights_split_proportionally() {
let weights = SplitWeights::parse("1,2").expect("weights");
assert_eq!(weights.allocate(9), vec![3, 6]);
assert_eq!(weights.allocate(3), vec![1, 2]);
}
#[test]
fn rounding_is_exact_at_every_prefix() {
let weights = SplitWeights::parse("1,1,1").expect("weights");
assert_eq!(weights.allocate(10), vec![4, 3, 3]);
assert_eq!(weights.allocate(3), vec![1, 1, 1]);
assert_eq!(weights.allocate(1), vec![1, 0, 0]);
}
#[test]
fn zero_weight_pools_never_receive_work() {
let weights = SplitWeights::parse("100,0,100").expect("weights");
assert_eq!(weights.allocate(6), vec![3, 0, 3]);
}
#[test]
fn a_single_pool_takes_everything() {
let weights = SplitWeights::parse("100").expect("weights");
assert_eq!(weights.allocate(5), vec![5]);
}
#[test]
fn malformed_configurations_are_rejected() {
assert_eq!(SplitWeights::parse(""), Err(SplitError::InvalidNumber));
assert_eq!(
SplitWeights::parse("50,abc"),
Err(SplitError::InvalidNumber)
);
assert_eq!(SplitWeights::parse("0,0"), Err(SplitError::NoWeight));
assert_eq!(SplitWeights::new(Vec::new()), Err(SplitError::Empty));
let many = vec![1_u32; 17];
assert_eq!(SplitWeights::new(many), Err(SplitError::TooManyPools));
}
#[test]
fn the_router_is_deterministic_for_the_same_input() {
let weights = SplitWeights::parse("60,40").expect("weights");
let first = weights.allocate(50);
let second = weights.allocate(50);
assert_eq!(first, second);
assert_eq!(first.iter().sum::<usize>(), 50);
assert_eq!(first[0], 30);
assert_eq!(first[1], 20);
}
}
-385
View File
@@ -1,385 +0,0 @@
// SPDX-License-Identifier: MIT
//! Stratum V2 transport and version selection.
//!
//! `TcpLink` turns a TCP stream into the framed messages the session expects: it buffers partial
//! reads and hands out one frame at a time, so a frame split across packets is not a protocol
//! error. The selection policy decides when a miner may fall back to Stratum V1.
use crate::stratum_v2::{Frame, V2Error};
use crate::stratum_v2_session::V2Link;
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::time::Duration;
const READ_CHUNK: usize = 4096;
/// A framed connection over TCP.
pub struct TcpLink {
stream: TcpStream,
buffer: Vec<u8>,
}
impl TcpLink {
pub fn connect(address: SocketAddr, timeout: Duration) -> io::Result<Self> {
let stream = TcpStream::connect_timeout(&address, timeout)?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
stream.set_nodelay(true)?;
Ok(Self {
stream,
buffer: Vec::new(),
})
}
pub fn from_stream(stream: TcpStream) -> io::Result<Self> {
stream.set_nodelay(true)?;
Ok(Self {
stream,
buffer: Vec::new(),
})
}
/// Bytes received but not yet consumed, for diagnostics.
pub fn buffered(&self) -> usize {
self.buffer.len()
}
}
impl V2Link for TcpLink {
type Error = io::Error;
fn send(&mut self, frame: &Frame) -> io::Result<()> {
let mut wire = Vec::with_capacity(frame.payload.len() + 6);
frame.encode(&mut wire);
self.stream.write_all(&wire)?;
self.stream.flush()
}
fn recv(&mut self) -> io::Result<Frame> {
loop {
if !self.buffer.is_empty() {
match Frame::decode(&self.buffer) {
Ok((frame, consumed)) => {
self.buffer.drain(..consumed);
return Ok(frame);
}
Err(V2Error::Truncated) => {}
Err(error) => {
self.buffer.clear();
return Err(io::Error::new(io::ErrorKind::InvalidData, error));
}
}
}
let mut chunk = [0_u8; READ_CHUNK];
let count = self.stream.read(&mut chunk)?;
if count == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"stratum v2 stream closed",
));
}
self.buffer.extend_from_slice(&chunk[..count]);
}
}
}
/// Which protocol the miner speaks.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StratumVersion {
V1,
V2,
}
/// Why an attempt failed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FailureKind {
/// The server refused the connection or the setup message.
Refused,
/// No mutually supported version.
Unsupported,
/// The connection could not be established or dropped.
Transport,
/// The server did not answer in time.
Timeout,
}
/// Operator preference.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Preference {
pub primary: StratumVersion,
pub allow_v1_fallback: bool,
}
impl Default for Preference {
fn default() -> Self {
Self {
primary: StratumVersion::V2,
allow_v1_fallback: true,
}
}
}
/// The protocol to try next, or `None` when there is nothing left.
///
/// V1 is attempted only when the operator allowed it and the failure is not a transport-level
/// problem: a dead route or a dropped stream will fail identically on V1, so falling back would
/// only delay the operator-visible error.
pub fn fallback(
preference: Preference,
failed: StratumVersion,
kind: FailureKind,
) -> Option<StratumVersion> {
match (preference.primary, failed) {
(StratumVersion::V2, StratumVersion::V2)
if preference.allow_v1_fallback && kind != FailureKind::Transport =>
{
Some(StratumVersion::V1)
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
#[test]
fn a_frame_arrives_intact_over_tcp() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
let mut wire = Vec::new();
Frame::new(0x00, vec![1, 2, 3, 4]).encode(&mut wire);
stream.write_all(&wire).expect("write");
});
let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect");
let frame = link.recv().expect("recv");
assert_eq!(frame.msg_type, 0x00);
assert_eq!(frame.payload, vec![1, 2, 3, 4]);
server.join().expect("join");
}
#[test]
fn a_frame_split_across_reads_is_reassembled() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
let mut wire = Vec::new();
Frame::new(0x10, vec![9; 40]).encode(&mut wire);
stream.write_all(&wire[..5]).expect("first");
std::thread::sleep(Duration::from_millis(20));
stream.write_all(&wire[5..]).expect("rest");
});
let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect");
let frame = link.recv().expect("recv");
assert_eq!(frame.msg_type, 0x10);
assert_eq!(frame.payload.len(), 40);
server.join().expect("join");
}
#[test]
fn two_frames_in_one_read_are_returned_one_at_a_time() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
let mut wire = Vec::new();
Frame::new(0x01, vec![1]).encode(&mut wire);
Frame::new(0x02, vec![2]).encode(&mut wire);
stream.write_all(&wire).expect("write");
});
let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect");
assert_eq!(link.recv().expect("first").msg_type, 0x01);
assert_eq!(link.recv().expect("second").msg_type, 0x02);
server.join().expect("join");
}
#[test]
fn a_closed_stream_is_an_error_not_an_empty_frame() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let server = std::thread::spawn(move || {
let (_stream, _) = listener.accept().expect("accept");
});
let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect");
let error = link.recv().expect_err("closed stream");
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
server.join().expect("join");
}
#[test]
fn v1_fallback_requires_permission_and_a_non_transport_failure() {
let allowed = Preference {
primary: StratumVersion::V2,
allow_v1_fallback: true,
};
assert_eq!(
fallback(allowed, StratumVersion::V2, FailureKind::Refused),
Some(StratumVersion::V1)
);
assert_eq!(
fallback(allowed, StratumVersion::V2, FailureKind::Unsupported),
Some(StratumVersion::V1)
);
assert_eq!(
fallback(allowed, StratumVersion::V2, FailureKind::Timeout),
Some(StratumVersion::V1)
);
assert_eq!(
fallback(allowed, StratumVersion::V2, FailureKind::Transport),
None
);
}
#[test]
fn v1_fallback_can_be_disabled_and_v1_failures_do_not_loop() {
let denied = Preference {
primary: StratumVersion::V2,
allow_v1_fallback: false,
};
assert_eq!(
fallback(denied, StratumVersion::V2, FailureKind::Refused),
None
);
let allowed = Preference::default();
assert_eq!(
fallback(allowed, StratumVersion::V1, FailureKind::Refused),
None
);
}
fn mock_pool() -> std::net::SocketAddr {
use crate::stratum_v2::{
NewMiningJob, OpenStandardMiningChannelSuccess, SetNewPrevHash, SetupConnectionSuccess,
OPEN_STANDARD_MINING_CHANNEL, OPEN_STANDARD_MINING_CHANNEL_SUCCESS, SETUP_CONNECTION,
SETUP_CONNECTION_SUCCESS, SET_NEW_PREV_HASH, SUBMIT_SHARES_SUCCESS,
};
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
// Publish the address through a channel so the test can connect after binding.
let (tx, rx) = std::sync::mpsc::channel();
tx.send(address).expect("send address");
std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
let mut link = TcpLink::from_stream(stream).expect("link");
let setup = link.recv().expect("setup");
assert_eq!(setup.msg_type, SETUP_CONNECTION);
link.send(&Frame::new(
SETUP_CONNECTION_SUCCESS,
SetupConnectionSuccess {
used_version: 2,
flags: 0,
}
.encode(),
))
.expect("setup success");
let open = link.recv().expect("open");
assert_eq!(open.msg_type, OPEN_STANDARD_MINING_CHANNEL);
link.send(&Frame::new(
OPEN_STANDARD_MINING_CHANNEL_SUCCESS,
OpenStandardMiningChannelSuccess {
request_id: 1,
channel_id: 7,
target: [0x7f; 32],
extranonce_prefix: vec![9, 9],
group_channel_id: 0,
}
.encode(),
))
.expect("channel success");
link.send(&Frame::new(
SET_NEW_PREV_HASH,
SetNewPrevHash {
channel_id: 7,
job_id: 41,
prev_hash: [0x11; 32],
ntime_start: 1_700_000_000,
nbits: 0x1707_0000,
}
.encode(),
))
.expect("prev hash");
link.send(&Frame::new(
NEW_MINING_JOB_TYPE,
NewMiningJob {
channel_id: 7,
job_id: 42,
ntime_start: Some(1_700_000_100),
version: 0x2000_0000,
merkle_root: [0x22; 32],
}
.encode(),
))
.expect("job");
let share = link.recv().expect("share");
assert_eq!(share.msg_type, SUBMIT_SHARES_STANDARD_TYPE);
let mut body = Vec::new();
body.extend_from_slice(&7_u32.to_le_bytes());
body.extend_from_slice(&1_u32.to_le_bytes());
body.extend_from_slice(&1_u32.to_le_bytes());
body.extend_from_slice(&0_u64.to_le_bytes());
link.send(&Frame::new(SUBMIT_SHARES_SUCCESS, body))
.expect("share success");
});
rx.recv().expect("address")
}
const NEW_MINING_JOB_TYPE: u8 = 0x15;
const SUBMIT_SHARES_STANDARD_TYPE: u8 = 0x1a;
#[test]
fn a_session_runs_against_a_socket_pool() {
use crate::stratum_v2_session::{handshake, V2Config, V2Event, V2Session};
let address = mock_pool();
let mut link = TcpLink::connect(address, Duration::from_secs(3)).expect("connect");
let config = V2Config {
host: "pool.test".into(),
port: 3333,
flags: 0,
user_identity: "worker".into(),
nominal_hash_rate: 1.0e14,
max_target: [0xff; 32],
vendor: "alkane".into(),
hardware: "bench".into(),
firmware: "alkane-os".into(),
device_id: "b1".into(),
};
let channel = handshake(&mut link, &config).expect("handshake");
assert_eq!(channel.channel_id, 7);
assert_eq!(channel.extranonce_prefix, vec![9, 9]);
let mut session = V2Session::new(channel);
let prev = session
.on_frame(&link.recv().expect("prev"))
.expect("prev event");
assert!(matches!(prev, V2Event::PrevHash { job_id: 41, .. }));
let job = session
.on_frame(&link.recv().expect("job"))
.expect("job event");
match job {
V2Event::Job(parsed) => {
assert_eq!(parsed.job_id, 42);
assert_eq!(parsed.prev_hash, Some([0x11; 32]));
assert_eq!(parsed.ntime_start, Some(1_700_000_100));
}
other => panic!("unexpected event: {other:?}"),
}
let sequence = session
.submit(&mut link, 42, 0xdead_beef, 1_700_000_100, 0x2000_0000)
.expect("submit");
assert_eq!(sequence, 1);
let ack = session
.on_frame(&link.recv().expect("ack"))
.expect("ack event");
assert_eq!(
ack,
V2Event::ShareAccepted {
last_sequence: 1,
accepted: 1
}
);
}
}
-631
View File
@@ -1,631 +0,0 @@
// SPDX-License-Identifier: MIT
//! Stratum V2 mining-protocol codec.
//!
//! Covers the client half of the mining sub-protocol: connection setup, opening a standard
//! channel, and the job/share messages that follow. Layouts follow the published specification
//! (framing in 03-Protocol-Overview 3.2, message types in 08-Message-Types, payloads in
//! 05-Mining-Protocol 5.3).
//!
//! Everything is little-endian. `U256` is carried as the raw 32 bytes of the little-endian
//! integer, which for a SHA-256 digest is the digest's own byte order.
use std::fmt;
pub const EXTENSION_TYPE_CORE: u16 = 0;
pub const SETUP_CONNECTION: u8 = 0x00;
pub const SETUP_CONNECTION_SUCCESS: u8 = 0x01;
pub const SETUP_CONNECTION_ERROR: u8 = 0x02;
pub const OPEN_STANDARD_MINING_CHANNEL: u8 = 0x10;
pub const OPEN_STANDARD_MINING_CHANNEL_SUCCESS: u8 = 0x11;
pub const OPEN_MINING_CHANNEL_ERROR: u8 = 0x12;
pub const NEW_MINING_JOB: u8 = 0x15;
pub const SUBMIT_SHARES_STANDARD: u8 = 0x1a;
pub const SUBMIT_SHARES_SUCCESS: u8 = 0x1c;
pub const SUBMIT_SHARES_ERROR: u8 = 0x1d;
pub const SET_NEW_PREV_HASH: u8 = 0x20;
pub const SET_TARGET: u8 = 0x21;
const HEADER_LEN: usize = 6;
const MAX_FRAME: usize = 1 << 20;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum V2Error {
Truncated,
Length,
String,
NonFiniteRate,
UnknownMessage(u8),
}
impl fmt::Display for V2Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Truncated => f.write_str("stratum v2 message is truncated"),
Self::Length => f.write_str("stratum v2 length field is invalid"),
Self::String => f.write_str("stratum v2 string field is invalid"),
Self::NonFiniteRate => {
f.write_str("stratum v2 hashrate is not a finite positive number")
}
Self::UnknownMessage(kind) => {
write!(f, "unsupported stratum v2 message type {kind:#x}")
}
}
}
}
impl std::error::Error for V2Error {}
/// One framed message: 6-byte header plus payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Frame {
pub extension_type: u16,
pub msg_type: u8,
pub payload: Vec<u8>,
}
impl Frame {
pub fn new(msg_type: u8, payload: Vec<u8>) -> Self {
Self {
extension_type: EXTENSION_TYPE_CORE,
msg_type,
payload,
}
}
pub fn encode(&self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.extension_type.to_le_bytes());
out.push(self.msg_type);
let length = self.payload.len() as u32;
out.extend_from_slice(&length.to_le_bytes()[..3]);
out.extend_from_slice(&self.payload);
}
/// Decode one frame from `buf`, returning it and how many bytes it consumed.
pub fn decode(buf: &[u8]) -> Result<(Self, usize), V2Error> {
if buf.len() < HEADER_LEN {
return Err(V2Error::Truncated);
}
let extension_type = u16::from_le_bytes([buf[0], buf[1]]);
let msg_type = buf[2];
let length = u32::from_le_bytes([buf[3], buf[4], buf[5], 0]) as usize;
if length > MAX_FRAME {
return Err(V2Error::Length);
}
let end = HEADER_LEN + length;
if buf.len() < end {
return Err(V2Error::Truncated);
}
Ok((
Self {
extension_type,
msg_type,
payload: buf[HEADER_LEN..end].to_vec(),
},
end,
))
}
}
/// `SetupConnection` for the mining sub-protocol.
#[derive(Clone, Debug, PartialEq)]
pub struct SetupConnection {
pub protocol: u8,
pub min_version: u16,
pub max_version: u16,
pub flags: u32,
pub endpoint_host: String,
pub endpoint_port: u16,
pub vendor: String,
pub hardware_version: String,
pub firmware: String,
pub device_id: String,
}
impl SetupConnection {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
out.push(self.protocol);
put_u16(&mut out, self.min_version);
put_u16(&mut out, self.max_version);
put_u32(&mut out, self.flags);
put_str(&mut out, &self.endpoint_host);
put_u16(&mut out, self.endpoint_port);
put_str(&mut out, &self.vendor);
put_str(&mut out, &self.hardware_version);
put_str(&mut out, &self.firmware);
put_str(&mut out, &self.device_id);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
Ok(Self {
protocol: reader.u8()?,
min_version: reader.u16()?,
max_version: reader.u16()?,
flags: reader.u32()?,
endpoint_host: reader.string()?,
endpoint_port: reader.u16()?,
vendor: reader.string()?,
hardware_version: reader.string()?,
firmware: reader.string()?,
device_id: reader.string()?,
})
}
}
/// `SetupConnection.Success`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SetupConnectionSuccess {
pub used_version: u16,
pub flags: u32,
}
impl SetupConnectionSuccess {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
put_u16(&mut out, self.used_version);
put_u32(&mut out, self.flags);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
Ok(Self {
used_version: reader.u16()?,
flags: reader.u32()?,
})
}
}
/// `OpenStandardMiningChannel`.
#[derive(Clone, Debug, PartialEq)]
pub struct OpenStandardMiningChannel {
pub request_id: u32,
pub user_identity: String,
pub nominal_hash_rate: f32,
pub max_target: [u8; 32],
}
impl OpenStandardMiningChannel {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
put_u32(&mut out, self.request_id);
put_str(&mut out, &self.user_identity);
out.extend_from_slice(&self.nominal_hash_rate.to_le_bytes());
out.extend_from_slice(&self.max_target);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
let request_id = reader.u32()?;
let user_identity = reader.string()?;
let nominal_hash_rate = reader.f32()?;
if !nominal_hash_rate.is_finite() || nominal_hash_rate < 0.0 {
return Err(V2Error::NonFiniteRate);
}
Ok(Self {
request_id,
user_identity,
nominal_hash_rate,
max_target: reader.u256()?,
})
}
}
/// `OpenStandardMiningChannel.Success`.
#[derive(Clone, Debug, PartialEq)]
pub struct OpenStandardMiningChannelSuccess {
pub request_id: u32,
pub channel_id: u32,
pub target: [u8; 32],
pub extranonce_prefix: Vec<u8>,
pub group_channel_id: u32,
}
impl OpenStandardMiningChannelSuccess {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
put_u32(&mut out, self.request_id);
put_u32(&mut out, self.channel_id);
out.extend_from_slice(&self.target);
put_bytes(&mut out, &self.extranonce_prefix);
put_u32(&mut out, self.group_channel_id);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
Ok(Self {
request_id: reader.u32()?,
channel_id: reader.u32()?,
target: reader.u256()?,
extranonce_prefix: reader.bytes(32)?,
group_channel_id: reader.u32()?,
})
}
}
/// `NewMiningJob` on a standard channel.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NewMiningJob {
pub channel_id: u32,
pub job_id: u32,
/// `None` means a future job, activated by the matching `SetNewPrevHash`.
pub ntime_start: Option<u32>,
pub version: u32,
pub merkle_root: [u8; 32],
}
impl NewMiningJob {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
put_u32(&mut out, self.channel_id);
put_u32(&mut out, self.job_id);
match self.ntime_start {
Some(ntime) => {
out.push(1);
put_u32(&mut out, ntime);
}
None => out.push(0),
}
put_u32(&mut out, self.version);
out.extend_from_slice(&self.merkle_root);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
let channel_id = reader.u32()?;
let job_id = reader.u32()?;
let ntime_start = reader.option_u32()?;
Ok(Self {
channel_id,
job_id,
ntime_start,
version: reader.u32()?,
merkle_root: reader.u256()?,
})
}
}
/// `SetNewPrevHash`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SetNewPrevHash {
pub channel_id: u32,
pub job_id: u32,
pub prev_hash: [u8; 32],
pub ntime_start: u32,
pub nbits: u32,
}
impl SetNewPrevHash {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
put_u32(&mut out, self.channel_id);
put_u32(&mut out, self.job_id);
out.extend_from_slice(&self.prev_hash);
put_u32(&mut out, self.ntime_start);
put_u32(&mut out, self.nbits);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
Ok(Self {
channel_id: reader.u32()?,
job_id: reader.u32()?,
prev_hash: reader.u256()?,
ntime_start: reader.u32()?,
nbits: reader.u32()?,
})
}
}
/// `SubmitSharesStandard`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SubmitSharesStandard {
pub channel_id: u32,
pub sequence_number: u32,
pub job_id: u32,
pub nonce: u32,
pub ntime: u32,
pub version: u32,
}
impl SubmitSharesStandard {
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
put_u32(&mut out, self.channel_id);
put_u32(&mut out, self.sequence_number);
put_u32(&mut out, self.job_id);
put_u32(&mut out, self.nonce);
put_u32(&mut out, self.ntime);
put_u32(&mut out, self.version);
out
}
pub fn decode(payload: &[u8]) -> Result<Self, V2Error> {
let mut reader = Reader::new(payload);
Ok(Self {
channel_id: reader.u32()?,
sequence_number: reader.u32()?,
job_id: reader.u32()?,
nonce: reader.u32()?,
ntime: reader.u32()?,
version: reader.u32()?,
})
}
}
fn put_u16(out: &mut Vec<u8>, value: u16) {
out.extend_from_slice(&value.to_le_bytes());
}
fn put_u32(out: &mut Vec<u8>, value: u32) {
out.extend_from_slice(&value.to_le_bytes());
}
fn put_str(out: &mut Vec<u8>, text: &str) {
let bytes = text.as_bytes();
let length = bytes.len().min(255);
out.push(length as u8);
out.extend_from_slice(&bytes[..length]);
}
fn put_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
let length = bytes.len().min(255);
out.push(length as u8);
out.extend_from_slice(&bytes[..length]);
}
struct Reader<'a> {
buf: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn new(buf: &'a [u8]) -> Self {
Self { buf, at: 0 }
}
fn take(&mut self, count: usize) -> Result<&'a [u8], V2Error> {
let end = self.at.checked_add(count).ok_or(V2Error::Length)?;
if end > self.buf.len() {
return Err(V2Error::Truncated);
}
let slice = &self.buf[self.at..end];
self.at = end;
Ok(slice)
}
fn u8(&mut self) -> Result<u8, V2Error> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<u16, V2Error> {
let bytes = self.take(2)?;
Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}
fn u32(&mut self) -> Result<u32, V2Error> {
let bytes = self.take(4)?;
Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}
fn f32(&mut self) -> Result<f32, V2Error> {
Ok(f32::from_bits(self.u32()?))
}
fn u256(&mut self) -> Result<[u8; 32], V2Error> {
let bytes = self.take(32)?;
let mut out = [0_u8; 32];
out.copy_from_slice(bytes);
Ok(out)
}
fn string(&mut self) -> Result<String, V2Error> {
let length = self.u8()? as usize;
let bytes = self.take(length)?;
String::from_utf8(bytes.to_vec()).map_err(|_| V2Error::String)
}
fn bytes(&mut self, max: usize) -> Result<Vec<u8>, V2Error> {
let length = self.u8()? as usize;
if length > max {
return Err(V2Error::Length);
}
Ok(self.take(length)?.to_vec())
}
fn option_u32(&mut self) -> Result<Option<u32>, V2Error> {
match self.u8()? {
0 => Ok(None),
1 => Ok(Some(self.u32()?)),
_ => Err(V2Error::Length),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hash(byte: u8) -> [u8; 32] {
[byte; 32]
}
#[test]
fn frame_header_matches_the_specification() {
let mut wire = Vec::new();
Frame::new(SETUP_CONNECTION, vec![1, 2, 3]).encode(&mut wire);
assert_eq!(&wire[..3], &[0x00, 0x00, 0x00]);
assert_eq!(&wire[3..6], &[0x03, 0x00, 0x00]);
let (frame, consumed) = Frame::decode(&wire).expect("frame");
assert_eq!(consumed, wire.len());
assert_eq!(frame.msg_type, SETUP_CONNECTION);
assert_eq!(frame.payload, vec![1, 2, 3]);
}
#[test]
fn a_truncated_frame_is_rejected() {
assert_eq!(Frame::decode(&[0, 0, 0x00]), Err(V2Error::Truncated));
let mut wire = Vec::new();
Frame::new(SETUP_CONNECTION, vec![9; 10]).encode(&mut wire);
assert_eq!(Frame::decode(&wire[..8]), Err(V2Error::Truncated));
}
#[test]
fn setup_connection_round_trips() {
let message = SetupConnection {
protocol: 0,
min_version: 2,
max_version: 2,
flags: 0b1011,
endpoint_host: "pool.example".into(),
endpoint_port: 3333,
vendor: "alkane".into(),
hardware_version: "s19jpro-bm1362".into(),
firmware: "alkane-os/0.1.0".into(),
device_id: "bench-169".into(),
};
let wire = message.encode();
assert_eq!(SetupConnection::decode(&wire).expect("decode"), message);
}
#[test]
fn setup_connection_success_round_trips() {
let message = SetupConnectionSuccess {
used_version: 2,
flags: 0,
};
assert_eq!(
SetupConnectionSuccess::decode(&message.encode()).expect("decode"),
message
);
}
#[test]
fn open_standard_channel_round_trips() {
let message = OpenStandardMiningChannel {
request_id: 7,
user_identity: "bc1q.example".into(),
nominal_hash_rate: 95_000_000_000_000.0,
max_target: hash(0xff),
};
assert_eq!(
OpenStandardMiningChannel::decode(&message.encode()).expect("decode"),
message
);
}
#[test]
fn a_non_finite_hashrate_is_a_protocol_error() {
let message = OpenStandardMiningChannel {
request_id: 1,
user_identity: "x".into(),
nominal_hash_rate: f32::NAN,
max_target: hash(0),
};
assert_eq!(
OpenStandardMiningChannel::decode(&message.encode()),
Err(V2Error::NonFiniteRate)
);
let negative = OpenStandardMiningChannel {
nominal_hash_rate: -1.0,
..message
};
assert_eq!(
OpenStandardMiningChannel::decode(&negative.encode()),
Err(V2Error::NonFiniteRate)
);
}
#[test]
fn channel_success_carries_the_extranonce_prefix() {
let message = OpenStandardMiningChannelSuccess {
request_id: 7,
channel_id: 11,
target: hash(0x7f),
extranonce_prefix: vec![0xde, 0xad, 0xbe, 0xef],
group_channel_id: 0,
};
assert_eq!(
OpenStandardMiningChannelSuccess::decode(&message.encode()).expect("decode"),
message
);
}
#[test]
fn new_job_round_trips_both_ntime_forms() {
let active = NewMiningJob {
channel_id: 1,
job_id: 2,
ntime_start: Some(1_700_000_000),
version: 0x2000_0000,
merkle_root: hash(0x11),
};
assert_eq!(
NewMiningJob::decode(&active.encode()).expect("decode"),
active
);
let future = NewMiningJob {
ntime_start: None,
..active
};
assert_eq!(
NewMiningJob::decode(&future.encode()).expect("decode"),
future
);
}
#[test]
fn set_new_prev_hash_round_trips() {
let message = SetNewPrevHash {
channel_id: 1,
job_id: 2,
prev_hash: hash(0x22),
ntime_start: 1_700_000_100,
nbits: 0x1707_0000,
};
assert_eq!(
SetNewPrevHash::decode(&message.encode()).expect("decode"),
message
);
}
#[test]
fn submit_shares_round_trips() {
let message = SubmitSharesStandard {
channel_id: 3,
sequence_number: 99,
job_id: 4,
nonce: 0xdead_beef,
ntime: 1_700_000_200,
version: 0x2000_0000,
};
assert_eq!(
SubmitSharesStandard::decode(&message.encode()).expect("decode"),
message
);
}
#[test]
fn a_short_payload_is_rejected_rather_than_padded() {
let wire = SubmitSharesStandard {
channel_id: 3,
sequence_number: 99,
job_id: 4,
nonce: 0,
ntime: 0,
version: 0,
}
.encode();
assert_eq!(
SubmitSharesStandard::decode(&wire[..8]),
Err(V2Error::Truncated)
);
}
}
-553
View File
@@ -1,553 +0,0 @@
// SPDX-License-Identifier: MIT
//! Stratum V2 session: handshake, channel, jobs and share submission.
//!
//! The codec in `stratum_v2` owns bytes; this module owns order. It drives the client half of a
//! mining connection and refuses to invent state: a job received before any `SetNewPrevHash` is
//! reported with no previous hash rather than with a zero one, and a rejected setup surfaces the
//! server's code.
use crate::stratum_v2::{
Frame, NewMiningJob, OpenStandardMiningChannel, SetNewPrevHash, SetupConnection,
SetupConnectionSuccess, SubmitSharesStandard, NEW_MINING_JOB, OPEN_MINING_CHANNEL_ERROR,
OPEN_STANDARD_MINING_CHANNEL, OPEN_STANDARD_MINING_CHANNEL_SUCCESS, SETUP_CONNECTION,
SETUP_CONNECTION_ERROR, SETUP_CONNECTION_SUCCESS, SET_NEW_PREV_HASH, SET_TARGET,
SUBMIT_SHARES_ERROR, SUBMIT_SHARES_STANDARD, SUBMIT_SHARES_SUCCESS,
};
/// A connection that carries whole frames.
pub trait V2Link {
type Error;
fn send(&mut self, frame: &Frame) -> Result<(), Self::Error>;
fn recv(&mut self) -> Result<Frame, Self::Error>;
}
/// What the client declares when it connects.
#[derive(Clone, Debug, PartialEq)]
pub struct V2Config {
pub host: String,
pub port: u16,
pub flags: u32,
pub user_identity: String,
pub nominal_hash_rate: f32,
pub max_target: [u8; 32],
pub vendor: String,
pub hardware: String,
pub firmware: String,
pub device_id: String,
}
/// An opened standard channel.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct V2Channel {
pub channel_id: u32,
pub target: [u8; 32],
pub extranonce_prefix: Vec<u8>,
pub group_channel_id: u32,
}
/// A job the miner may work on.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct V2Job {
pub job_id: u32,
pub version: u32,
pub merkle_root: [u8; 32],
pub ntime_start: Option<u32>,
pub prev_hash: Option<[u8; 32]>,
pub nbits: Option<u32>,
}
/// Something the server told us.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum V2Event {
Job(V2Job),
PrevHash {
job_id: u32,
prev_hash: [u8; 32],
ntime_start: u32,
nbits: u32,
},
Target {
channel_id: u32,
target: [u8; 32],
},
ShareAccepted {
last_sequence: u32,
accepted: u32,
},
ShareRejected {
last_sequence: u32,
},
Ignored,
}
/// A protocol-level failure, without a link error inside it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SessionError {
Protocol(&'static str),
Rejected(String),
}
/// A failure that may have come from the transport.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ConnectError<E> {
Link(E),
Session(SessionError),
}
/// Run the client handshake and return the opened channel.
pub fn handshake<L: V2Link>(
link: &mut L,
config: &V2Config,
) -> Result<V2Channel, ConnectError<L::Error>> {
let setup = SetupConnection {
protocol: 0,
min_version: 2,
max_version: 2,
flags: config.flags,
endpoint_host: config.host.clone(),
endpoint_port: config.port,
vendor: config.vendor.clone(),
hardware_version: config.hardware.clone(),
firmware: config.firmware.clone(),
device_id: config.device_id.clone(),
};
link.send(&Frame::new(SETUP_CONNECTION, setup.encode()))
.map_err(ConnectError::Link)?;
let reply = link.recv().map_err(ConnectError::Link)?;
match reply.msg_type {
SETUP_CONNECTION_SUCCESS => {
let _ = SetupConnectionSuccess::decode(&reply.payload)
.map_err(|_| ConnectError::Session(SessionError::Protocol("bad setup success")))?;
}
SETUP_CONNECTION_ERROR => {
return Err(ConnectError::Session(SessionError::Rejected(
setup_error_text(&reply.payload),
)))
}
_ => {
return Err(ConnectError::Session(SessionError::Protocol(
"unexpected message before setup success",
)))
}
}
let open = OpenStandardMiningChannel {
request_id: 1,
user_identity: config.user_identity.clone(),
nominal_hash_rate: config.nominal_hash_rate,
max_target: config.max_target,
};
link.send(&Frame::new(OPEN_STANDARD_MINING_CHANNEL, open.encode()))
.map_err(ConnectError::Link)?;
let reply = link.recv().map_err(ConnectError::Link)?;
match reply.msg_type {
OPEN_STANDARD_MINING_CHANNEL_SUCCESS => {
let success =
crate::stratum_v2::OpenStandardMiningChannelSuccess::decode(&reply.payload)
.map_err(|_| {
ConnectError::Session(SessionError::Protocol("bad channel success"))
})?;
if success.request_id != 1 {
return Err(ConnectError::Session(SessionError::Protocol(
"channel response does not match the request",
)));
}
Ok(V2Channel {
channel_id: success.channel_id,
target: success.target,
extranonce_prefix: success.extranonce_prefix,
group_channel_id: success.group_channel_id,
})
}
OPEN_MINING_CHANNEL_ERROR => Err(ConnectError::Session(SessionError::Rejected(
setup_error_text(&reply.payload),
))),
_ => Err(ConnectError::Session(SessionError::Protocol(
"unexpected message while opening a channel",
))),
}
}
fn setup_error_text(payload: &[u8]) -> String {
// Error messages are a U32 flag mask followed by a STR0_255 code.
if payload.len() < 5 {
return String::from("unspecified");
}
let length = payload[4] as usize;
payload
.get(5..5 + length)
.and_then(|bytes| std::str::from_utf8(bytes).ok())
.unwrap_or("unspecified")
.to_owned()
}
/// Session state after the handshake.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct V2Session {
channel: V2Channel,
prev_hash: Option<[u8; 32]>,
nbits: Option<u32>,
sequence: u32,
}
impl V2Session {
pub fn new(channel: V2Channel) -> Self {
Self {
channel,
prev_hash: None,
nbits: None,
sequence: 0,
}
}
pub fn channel(&self) -> &V2Channel {
&self.channel
}
/// Interpret one server frame.
pub fn on_frame(&mut self, frame: &Frame) -> Result<V2Event, SessionError> {
match frame.msg_type {
NEW_MINING_JOB => {
let job = NewMiningJob::decode(&frame.payload)
.map_err(|_| SessionError::Protocol("bad NewMiningJob"))?;
Ok(V2Event::Job(V2Job {
job_id: job.job_id,
version: job.version,
merkle_root: job.merkle_root,
ntime_start: job.ntime_start,
prev_hash: self.prev_hash,
nbits: self.nbits,
}))
}
SET_NEW_PREV_HASH => {
let message = SetNewPrevHash::decode(&frame.payload)
.map_err(|_| SessionError::Protocol("bad SetNewPrevHash"))?;
self.prev_hash = Some(message.prev_hash);
self.nbits = Some(message.nbits);
Ok(V2Event::PrevHash {
job_id: message.job_id,
prev_hash: message.prev_hash,
ntime_start: message.ntime_start,
nbits: message.nbits,
})
}
SET_TARGET => {
if frame.payload.len() != 4 + 32 {
return Err(SessionError::Protocol("bad SetTarget"));
}
let channel_id = u32::from_le_bytes([
frame.payload[0],
frame.payload[1],
frame.payload[2],
frame.payload[3],
]);
let mut target = [0_u8; 32];
target.copy_from_slice(&frame.payload[4..36]);
Ok(V2Event::Target { channel_id, target })
}
SUBMIT_SHARES_SUCCESS => {
if frame.payload.len() < 20 {
return Err(SessionError::Protocol("bad SubmitShares.Success"));
}
let last_sequence = u32::from_le_bytes([
frame.payload[4],
frame.payload[5],
frame.payload[6],
frame.payload[7],
]);
let accepted = u32::from_le_bytes([
frame.payload[8],
frame.payload[9],
frame.payload[10],
frame.payload[11],
]);
Ok(V2Event::ShareAccepted {
last_sequence,
accepted,
})
}
SUBMIT_SHARES_ERROR => {
let last_sequence = if frame.payload.len() >= 8 {
u32::from_le_bytes([
frame.payload[0],
frame.payload[1],
frame.payload[2],
frame.payload[3],
])
} else {
0
};
Ok(V2Event::ShareRejected { last_sequence })
}
_ => Ok(V2Event::Ignored),
}
}
/// Submit one standard share; returns the sequence number used.
pub fn submit<L: V2Link>(
&mut self,
link: &mut L,
job_id: u32,
nonce: u32,
ntime: u32,
version: u32,
) -> Result<u32, ConnectError<L::Error>> {
self.sequence = self.sequence.wrapping_add(1);
let share = SubmitSharesStandard {
channel_id: self.channel.channel_id,
sequence_number: self.sequence,
job_id,
nonce,
ntime,
version,
};
link.send(&Frame::new(SUBMIT_SHARES_STANDARD, share.encode()))
.map_err(ConnectError::Link)?;
Ok(self.sequence)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::VecDeque;
struct Scripted {
incoming: VecDeque<Frame>,
sent: Vec<Frame>,
}
impl Scripted {
fn new(incoming: Vec<Frame>) -> Self {
Self {
incoming: incoming.into(),
sent: Vec::new(),
}
}
}
impl V2Link for Scripted {
type Error = ();
fn send(&mut self, frame: &Frame) -> Result<(), ()> {
self.sent.push(frame.clone());
Ok(())
}
fn recv(&mut self) -> Result<Frame, ()> {
self.incoming.pop_front().ok_or(())
}
}
fn config() -> V2Config {
V2Config {
host: "pool.example".into(),
port: 3333,
flags: 0,
user_identity: "worker".into(),
nominal_hash_rate: 1.0e14,
max_target: [0xff; 32],
vendor: "alkane".into(),
hardware: "bench".into(),
firmware: "alkane-os".into(),
device_id: "bench-1".into(),
}
}
fn setup_success() -> Frame {
Frame::new(
SETUP_CONNECTION_SUCCESS,
SetupConnectionSuccess {
used_version: 2,
flags: 0,
}
.encode(),
)
}
fn channel_success() -> Frame {
Frame::new(
OPEN_STANDARD_MINING_CHANNEL_SUCCESS,
crate::stratum_v2::OpenStandardMiningChannelSuccess {
request_id: 1,
channel_id: 9,
target: [0x7f; 32],
extranonce_prefix: vec![1, 2],
group_channel_id: 0,
}
.encode(),
)
}
#[test]
fn handshake_sends_setup_then_open_and_returns_the_channel() {
let mut link = Scripted::new(vec![setup_success(), channel_success()]);
let channel = handshake(&mut link, &config()).expect("handshake");
assert_eq!(channel.channel_id, 9);
assert_eq!(channel.extranonce_prefix, vec![1, 2]);
assert_eq!(link.sent.len(), 2);
assert_eq!(link.sent[0].msg_type, SETUP_CONNECTION);
assert_eq!(link.sent[1].msg_type, OPEN_STANDARD_MINING_CHANNEL);
let open = OpenStandardMiningChannel::decode(&link.sent[1].payload).expect("open");
assert_eq!(open.user_identity, "worker");
assert_eq!(open.request_id, 1);
}
#[test]
fn a_setup_error_surfaces_the_server_code() {
let mut payload = 0_u32.to_le_bytes().to_vec();
payload.push(3);
payload.extend_from_slice(b"bad");
let mut link = Scripted::new(vec![Frame::new(SETUP_CONNECTION_ERROR, payload)]);
assert_eq!(
handshake(&mut link, &config()),
Err(ConnectError::Session(SessionError::Rejected("bad".into())))
);
}
#[test]
fn an_unexpected_message_during_setup_is_a_protocol_error() {
let mut link = Scripted::new(vec![Frame::new(NEW_MINING_JOB, vec![0; 44])]);
assert_eq!(
handshake(&mut link, &config()),
Err(ConnectError::Session(SessionError::Protocol(
"unexpected message before setup success"
)))
);
}
#[test]
fn a_job_before_any_prev_hash_has_no_prev_hash() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let job = NewMiningJob {
channel_id: 9,
job_id: 1,
ntime_start: Some(1_700_000_000),
version: 0x2000_0000,
merkle_root: [0x11; 32],
};
let event = session
.on_frame(&Frame::new(NEW_MINING_JOB, job.encode()))
.expect("job");
match event {
V2Event::Job(parsed) => {
assert_eq!(parsed.job_id, 1);
assert_eq!(parsed.prev_hash, None);
assert_eq!(parsed.nbits, None);
}
other => panic!("unexpected event: {other:?}"),
}
}
#[test]
fn prev_hash_is_remembered_for_later_jobs() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let prev = SetNewPrevHash {
channel_id: 9,
job_id: 1,
prev_hash: [0x22; 32],
ntime_start: 1_700_000_100,
nbits: 0x1707_0000,
};
session
.on_frame(&Frame::new(SET_NEW_PREV_HASH, prev.encode()))
.expect("prev hash");
let job = NewMiningJob {
channel_id: 9,
job_id: 2,
ntime_start: None,
version: 0x2000_0000,
merkle_root: [0x33; 32],
};
match session
.on_frame(&Frame::new(NEW_MINING_JOB, job.encode()))
.expect("job")
{
V2Event::Job(parsed) => {
assert_eq!(parsed.prev_hash, Some([0x22; 32]));
assert_eq!(parsed.nbits, Some(0x1707_0000));
assert_eq!(parsed.ntime_start, None);
}
other => panic!("unexpected event: {other:?}"),
}
}
#[test]
fn submissions_use_the_channel_and_increasing_sequence_numbers() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let mut link = Scripted::new(Vec::new());
assert_eq!(
session
.submit(&mut link, 1, 0xabcd, 1_700_000_000, 0x2000_0000)
.expect("submit"),
1
);
assert_eq!(
session
.submit(&mut link, 1, 0xabce, 1_700_000_000, 0x2000_0000)
.expect("submit"),
2
);
assert_eq!(link.sent.len(), 2);
let first = SubmitSharesStandard::decode(&link.sent[0].payload).expect("share");
assert_eq!(first.channel_id, 9);
assert_eq!(first.sequence_number, 1);
assert_eq!(first.nonce, 0xabcd);
}
#[test]
fn share_success_reports_the_last_sequence() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let mut payload = Vec::new();
payload.extend_from_slice(&9_u32.to_le_bytes());
payload.extend_from_slice(&7_u32.to_le_bytes());
payload.extend_from_slice(&3_u32.to_le_bytes());
payload.extend_from_slice(&0_u64.to_le_bytes());
assert_eq!(
session
.on_frame(&Frame::new(SUBMIT_SHARES_SUCCESS, payload))
.expect("event"),
V2Event::ShareAccepted {
last_sequence: 7,
accepted: 3
}
);
}
#[test]
fn an_unknown_message_is_ignored_not_fatal() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
assert_eq!(
session
.on_frame(&Frame::new(0x7e, vec![0; 4]))
.expect("event"),
V2Event::Ignored
);
}
}
-506
View File
@@ -1,506 +0,0 @@
// SPDX-License-Identifier: MIT
//! Adaptive tuning.
//!
//! The miner targets a power draw, a hashrate, or an operating point chosen for the ambient
//! temperature. Rather than picking a preset, a bounded PID moves the chain frequency inside the
//! profile envelope each control period, and a thermal guard can always override it downward.
//!
//! The controller is deliberately conservative: bounded output, rate limit, deadband, derivative
//! on the measurement (no setpoint kick) and conditional integration (no windup while saturated).
use crate::detect::Envelope;
/// What the operator asked for.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TuningTarget {
/// Hold this DC power draw; efficiency follows from the power point.
PowerW(f32),
/// Maximise hashrate up to this value.
HashrateThs(f32),
/// Hold the hottest sensor this far above the measured ambient: efficiency at that ambient.
AmbientC { margin_mc: i32 },
/// Pin the fan at this duty and maximise hashrate under it.
MaxFan { max_pwm: u8 },
}
/// Controller tuning.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PidConfig {
pub kp: f32,
pub ki: f32,
pub kd: f32,
pub out_min: f32,
pub out_max: f32,
/// Maximum output change per second.
pub max_step_per_s: f32,
/// Errors inside this band are ignored.
pub deadband: f32,
}
impl Default for PidConfig {
fn default() -> Self {
Self {
kp: 0.5,
ki: 0.1,
kd: 0.0,
out_min: 0.0,
out_max: 1_000.0,
max_step_per_s: 50.0,
deadband: 1.0,
}
}
}
/// A bounded PID with anti-windup and rate limiting.
#[derive(Clone, Debug)]
pub struct Pid {
config: PidConfig,
integral: f32,
last_measurement: Option<f32>,
output: f32,
}
impl Pid {
pub fn new(config: PidConfig, initial_output: f32) -> Self {
Self {
config,
integral: 0.0,
last_measurement: None,
output: initial_output.clamp(config.out_min, config.out_max),
}
}
pub fn output(&self) -> f32 {
self.output
}
/// Force the output (used by ramp modes and the thermal guard).
pub fn set_output(&mut self, value: f32) {
self.output = value.clamp(self.config.out_min, self.config.out_max);
}
/// Advance one control period and return the new output.
pub fn update(&mut self, setpoint: f32, measurement: f32, dt_s: f32) -> f32 {
if !dt_s.is_finite() || dt_s <= 0.0 {
return self.output;
}
let error = setpoint - measurement;
if error.abs() <= self.config.deadband {
self.last_measurement = Some(measurement);
return self.output;
}
let derivative = match self.last_measurement {
Some(previous) => -(measurement - previous) / dt_s,
None => 0.0,
};
let candidate = self.config.kp * error + self.integral + self.config.kd * derivative;
let saturated = candidate > self.config.out_max || candidate < self.config.out_min;
// Conditional integration: never accumulate while the actuator is pinned in the direction
// of the error, or the loop unwinds slowly after a saturation episode.
let pinning = (candidate > self.config.out_max && error > 0.0)
|| (candidate < self.config.out_min && error < 0.0);
if !saturated || !pinning {
self.integral += self.config.ki * error * dt_s;
}
let mut desired = self.config.kp * error + self.integral + self.config.kd * derivative;
desired = desired.clamp(self.config.out_min, self.config.out_max);
let max_step = self.config.max_step_per_s * dt_s;
let step = (desired - self.output).clamp(-max_step, max_step);
self.output = (self.output + step).clamp(self.config.out_min, self.config.out_max);
self.last_measurement = Some(measurement);
self.output
}
}
/// What the loop needs to know each period.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Observation {
pub power_w: Option<f32>,
pub hashrate_ths: Option<f32>,
/// Hottest sensor in millidegrees, when telemetry is available.
pub hottest_mc: Option<i32>,
/// Intake/enclosure temperature in millidegrees, for the ambient target.
pub ambient_mc: Option<i32>,
}
/// What the loop wants applied this period.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Command {
pub frequency_mhz: u16,
/// `Some` only when the target owns the fan (max-fan mode).
pub fan_pwm: Option<u8>,
}
/// Why the loop could not produce a command.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TuningError {
/// The measurement the target needs is missing this period.
NoMeasurement,
}
/// The tuning loop: one PID over chain frequency, bounded by the profile envelope.
#[derive(Clone, Debug)]
pub struct TuningLoop {
pid: Pid,
envelope: Envelope,
target: TuningTarget,
ceiling_mc: i32,
}
impl TuningLoop {
/// Start from the conservative floor of the envelope.
pub fn new(target: TuningTarget, envelope: Envelope, pid: PidConfig, ceiling_mc: i32) -> Self {
let config = PidConfig {
out_min: f32::from(envelope.f_min_mhz),
out_max: f32::from(envelope.f_max_mhz),
..pid
};
let start = f32::from(envelope.f_min_mhz);
Self {
pid: Pid::new(config, start),
envelope,
target,
ceiling_mc,
}
}
pub fn frequency_mhz(&self) -> u16 {
self.pid.output().round() as u16
}
/// Fan duty implied by the target, if the target owns the fan.
fn target_fan(&self) -> Option<u8> {
match self.target {
TuningTarget::MaxFan { max_pwm } => Some(max_pwm),
_ => None,
}
}
fn command(&self) -> Command {
Command {
frequency_mhz: self.frequency_mhz(),
fan_pwm: self.target_fan(),
}
}
/// One control period. Returns the command to apply, inside the envelope.
pub fn step(&mut self, observation: Observation, dt_s: f32) -> Result<Command, TuningError> {
// Thermal guard: a hot sensor always derates, whatever the target says.
if let Some(hottest) = observation.hottest_mc {
if hottest >= self.ceiling_mc {
let derated = (self.pid.output() - 25.0).max(f32::from(self.envelope.f_min_mhz));
self.pid = Pid::new(
PidConfig {
out_min: f32::from(self.envelope.f_min_mhz),
out_max: f32::from(self.envelope.f_max_mhz),
..self.pid.config
},
derated,
);
return Ok(self.command());
}
}
match self.target {
TuningTarget::PowerW(setpoint) => {
let measurement = observation.power_w.ok_or(TuningError::NoMeasurement)?;
self.pid.update(setpoint, measurement, dt_s);
}
TuningTarget::HashrateThs(setpoint) => {
let measurement = observation.hashrate_ths.ok_or(TuningError::NoMeasurement)?;
self.pid.update(setpoint, measurement, dt_s);
}
TuningTarget::AmbientC { margin_mc } => {
let ambient = observation.ambient_mc.ok_or(TuningError::NoMeasurement)?;
let hottest = observation.hottest_mc.ok_or(TuningError::NoMeasurement)?;
let setpoint = ambient as f32 + margin_mc as f32;
self.pid.update(setpoint, hottest as f32, dt_s);
}
TuningTarget::MaxFan { .. } => {
// No setpoint loop here: ramp toward the envelope ceiling and let the thermal
// guard be the only thing that stops it.
let step = self.pid.config.max_step_per_s * dt_s;
let next = (self.pid.output() + step).min(f32::from(self.envelope.f_max_mhz));
self.pid.set_output(next);
}
}
Ok(self.command())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn envelope() -> Envelope {
Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
}
}
fn observation(hottest: i32) -> Observation {
Observation {
power_w: None,
hashrate_ths: None,
hottest_mc: Some(hottest),
ambient_mc: None,
}
}
#[test]
fn pid_drives_the_plant_to_the_setpoint() {
let mut pid = Pid::new(
PidConfig {
kp: 0.02,
ki: 0.01,
kd: 0.0,
out_min: 0.0,
out_max: 700.0,
max_step_per_s: 1_000.0,
deadband: 0.0,
},
0.0,
);
// Plant: 5 W per MHz, so 3 kW needs 600 MHz, inside the controller ceiling.
let mut power = 0.0_f32;
for _ in 0..400 {
let freq = pid.update(3_000.0, power, 1.0);
power = 5.0 * freq;
}
assert!((power - 3_000.0).abs() < 50.0, "power settled at {power}");
}
#[test]
fn output_is_rate_limited() {
let mut pid = Pid::new(
PidConfig {
kp: 1.0,
ki: 0.0,
kd: 0.0,
out_min: 0.0,
out_max: 1_000.0,
max_step_per_s: 10.0,
deadband: 0.0,
},
0.0,
);
assert!((pid.update(1_000.0, 0.0, 1.0) - 10.0).abs() < f32::EPSILON);
assert!((pid.update(1_000.0, 0.0, 1.0) - 20.0).abs() < f32::EPSILON);
}
#[test]
fn deadband_holds_the_output() {
let mut pid = Pid::new(
PidConfig {
kp: 1.0,
ki: 0.1,
kd: 0.0,
out_min: 0.0,
out_max: 1_000.0,
max_step_per_s: 100.0,
deadband: 5.0,
},
100.0,
);
let before = pid.output();
assert!((pid.update(102.0, 100.0, 1.0) - before).abs() < f32::EPSILON);
}
#[test]
fn saturation_does_not_wind_up_the_integral() {
let mut pid = Pid::new(
PidConfig {
kp: 1.0,
ki: 1.0,
kd: 0.0,
out_min: 0.0,
out_max: 100.0,
max_step_per_s: 1_000.0,
deadband: 0.0,
},
0.0,
);
for _ in 0..100 {
pid.update(1_000.0, 0.0, 1.0);
}
assert!((pid.output() - 100.0).abs() < 0.01);
for _ in 0..5 {
pid.update(0.0, 200.0, 1.0);
}
assert!(
pid.output() < 99.0,
"output stuck at the rail: {}",
pid.output()
);
}
#[test]
fn power_target_moves_frequency_inside_the_envelope() {
let mut loop_ = TuningLoop::new(
TuningTarget::PowerW(2_400.0),
envelope(),
PidConfig {
kp: 0.2,
ki: 0.05,
kd: 0.0,
out_min: 0.0,
out_max: 0.0,
max_step_per_s: 50.0,
deadband: 0.0,
},
95_000,
);
let mut freq = loop_.frequency_mhz();
for _ in 0..100 {
let power = 4.0 * f32::from(freq);
let mut obs = observation(70_000);
obs.power_w = Some(power);
freq = loop_.step(obs, 1.0).expect("step").frequency_mhz;
assert!((300..=700).contains(&freq), "out of envelope: {freq}");
}
let power = 4.0 * f32::from(freq);
assert!((power - 2_400.0).abs() < 200.0, "power settled at {power}");
}
#[test]
fn thermal_guard_derates_regardless_of_target() {
let mut loop_ = TuningLoop::new(
TuningTarget::HashrateThs(200.0),
envelope(),
PidConfig::default(),
90_000,
);
for _ in 0..50 {
let mut obs = observation(60_000);
obs.hashrate_ths = Some(10.0);
loop_.step(obs, 1.0).expect("step");
}
let hot = loop_.frequency_mhz();
let mut obs = observation(91_000);
obs.hashrate_ths = Some(10.0);
let derated = loop_.step(obs, 1.0).expect("step").frequency_mhz;
assert!(
derated < hot,
"thermal guard did not derate: {derated} vs {hot}"
);
}
#[test]
fn missing_measurement_is_an_error() {
let mut loop_ = TuningLoop::new(
TuningTarget::PowerW(3_000.0),
envelope(),
PidConfig::default(),
95_000,
);
let mut obs = observation(50_000);
obs.hashrate_ths = Some(1.0);
assert_eq!(loop_.step(obs, 1.0), Err(TuningError::NoMeasurement));
}
#[test]
fn zero_dt_holds_the_output() {
let mut pid = Pid::new(PidConfig::default(), 42.0);
assert!((pid.update(100.0, 0.0, 0.0) - 42.0).abs() < f32::EPSILON);
}
#[test]
fn ambient_target_holds_the_hottest_sensor_near_ambient_plus_margin() {
let mut loop_ = TuningLoop::new(
TuningTarget::AmbientC { margin_mc: 20_000 },
envelope(),
PidConfig {
kp: 0.5,
ki: 0.05,
kd: 0.0,
out_min: 0.0,
out_max: 0.0,
max_step_per_s: 50.0,
deadband: 0.0,
},
200_000,
);
// Plant: hottest = ambient + 50 mC per MHz.
let ambient = 40_000;
let mut freq = loop_.frequency_mhz();
for _ in 0..300 {
let hottest = ambient + 50 * i32::from(freq);
let obs = Observation {
power_w: None,
hashrate_ths: None,
hottest_mc: Some(hottest),
ambient_mc: Some(ambient),
};
freq = loop_.step(obs, 1.0).expect("step").frequency_mhz;
}
let hottest = ambient + 50 * i32::from(freq);
assert!(
(hottest - (ambient + 20_000)).abs() < 2_000,
"hottest settled at {hottest}"
);
}
#[test]
fn ambient_target_needs_an_ambient_sensor() {
let mut loop_ = TuningLoop::new(
TuningTarget::AmbientC { margin_mc: 20_000 },
envelope(),
PidConfig::default(),
95_000,
);
assert_eq!(
loop_.step(observation(50_000), 1.0),
Err(TuningError::NoMeasurement)
);
}
#[test]
fn max_fan_mode_pins_the_fan_and_ramps_frequency() {
let ramp = PidConfig {
kp: 1.0,
ki: 0.0,
kd: 0.0,
out_min: 0.0,
out_max: 0.0,
max_step_per_s: 50.0,
deadband: 0.0,
};
let mut loop_ = TuningLoop::new(
TuningTarget::MaxFan { max_pwm: 100 },
envelope(),
ramp,
120_000,
);
let start = loop_.frequency_mhz();
let mut last = start;
for _ in 0..20 {
let command = loop_.step(observation(70_000), 1.0).expect("step");
assert_eq!(command.fan_pwm, Some(100));
last = command.frequency_mhz;
}
assert!(last > start, "frequency did not ramp: {last} vs {start}");
assert!(
last == 700,
"ramp did not reach the envelope ceiling: {last}"
);
}
#[test]
fn max_fan_mode_still_respects_the_temperature_ceiling() {
let mut loop_ = TuningLoop::new(
TuningTarget::MaxFan { max_pwm: 100 },
envelope(),
PidConfig::default(),
80_000,
);
for _ in 0..50 {
loop_.step(observation(70_000), 1.0).expect("step");
}
let hot = loop_.frequency_mhz();
let command = loop_.step(observation(85_000), 1.0).expect("step");
assert!(command.frequency_mhz < hot);
assert_eq!(command.fan_pwm, Some(100));
}
}
-248
View File
@@ -1,248 +0,0 @@
// SPDX-License-Identifier: MIT
//! On-box web UI.
//!
//! A small HTTP surface served by the miner itself: a single page that polls the JSON API, plus
//! the API routes it uses. The API stays the interface of record; the page is a convenience, so a
//! client that only speaks JSON loses nothing.
//!
//! No framework and no dependency: the request parser is bounded, only `GET` is accepted, and every
//! response closes the connection.
use crate::management::MiningStatus;
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::Arc;
use std::time::Duration;
const MAX_REQUEST_BYTES: usize = 2048;
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
const PAGE: &str = r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Alkane miner</title>
<style>
body{font:14px/1.4 system-ui,sans-serif;margin:2rem;color:#1b1b1b}
h1{font-size:1.2rem;margin:0 0 1rem}
table{border-collapse:collapse;min-width:28rem}
th,td{text-align:left;padding:.35rem .6rem;border-bottom:1px solid #ddd}
th{width:11rem;color:#555;font-weight:600}
.bad{color:#a11}
</style>
</head>
<body>
<h1>Alkane miner</h1>
<table id="t"><tbody><tr><td>loading</td><td></td></tr></tbody></table>
<script>
async function refresh(){
const t=document.getElementById('t').tBodies[0];
try{
const h=await (await fetch('/api/hardware')).json();
const d=h.HARDWARE[0];
if(!d.available){t.innerHTML='<tr><td>hardware</td><td class="bad">not detected yet</td></tr>';return}
const rows=[
['profile',d.profile],['chip',d.chip],['PSU',d.psu],
['frequency',d.frequency_mhz+' MHz'],
['voltage',d.operating_point.voltage_mv+' mV'],
['confirmed',d.operating_point.confirmed?'yes':'no (conservative)'],
['chains',d.chains.length],['active chains',d.active_chains.length],
['target',d.target],
['stopped',d.stopped||'no']
];
t.innerHTML=rows.map(r=>'<tr><th>'+r[0]+'</th><td>'+r[1]+'</td></tr>').join('')
+d.chains.map(c=>'<tr><th>chain '+c.index+'</th><td>'+c.chip+', '+c.chips_found+
' chips, EEPROM '+c.eeprom.state+'</td></tr>').join('');
}catch(e){t.innerHTML='<tr><td>error</td><td class="bad">'+e+'</td></tr>'}
}
refresh();setInterval(refresh,5000);
</script>
</body>
</html>
"#;
/// Bind and serve until the listener fails.
pub fn serve(bind: SocketAddr, status: Arc<MiningStatus>) -> io::Result<()> {
let listener = TcpListener::bind(bind)?;
serve_listener(listener, status)
}
/// Serve on an already-bound listener.
pub fn serve_listener(listener: TcpListener, status: Arc<MiningStatus>) -> io::Result<()> {
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let status = Arc::clone(&status);
// Each connection is short, bounded and closes itself.
std::thread::spawn(move || {
let _ = handle(stream, &status);
});
}
Ok(())
}
/// Handle one HTTP request.
pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> {
stream.set_read_timeout(Some(CLIENT_TIMEOUT))?;
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
let mut request = Vec::new();
let mut chunk = [0_u8; 512];
loop {
let count = stream.read(&mut chunk)?;
if count == 0 {
break;
}
request.extend_from_slice(&chunk[..count]);
if request.len() > MAX_REQUEST_BYTES {
return respond(&mut stream, 431, "text/plain", b"request too large");
}
if request.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
let head = String::from_utf8_lossy(&request);
let mut parts = head.lines().next().unwrap_or("").split_whitespace();
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("");
if method != "GET" {
return respond(&mut stream, 405, "text/plain", b"method not allowed");
}
match path {
"/" | "/index.html" => respond(
&mut stream,
200,
"text/html; charset=utf-8",
PAGE.as_bytes(),
),
"/api/hardware" => {
let body = status.hardware_document().to_string();
respond(&mut stream, 200, "application/json", body.as_bytes())
}
"/api/summary" => {
let body = status.summary_document().to_string();
respond(&mut stream, 200, "application/json", body.as_bytes())
}
_ => respond(&mut stream, 404, "text/plain", b"not found"),
}
}
fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> io::Result<()> {
let reason = match code {
200 => "OK",
404 => "Not Found",
405 => "Method Not Allowed",
431 => "Request Header Fields Too Large",
_ => "Error",
};
let header = format!(
"HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n",
body.len()
);
stream.write_all(header.as_bytes())?;
stream.write_all(body)?;
stream.flush()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::{
ChainReport, ChipModel, EepromState, Envelope, HardwarePlan, OperatingPoint,
};
use crate::management::HardwareSnapshot;
use std::net::TcpStream as Client;
fn status() -> Arc<MiningStatus> {
let status = MiningStatus::new();
status.set_hardware(HardwareSnapshot {
plan: HardwarePlan {
profile: "s19jpro-bm1362-pic".into(),
chip: ChipModel::Bm1362,
chains: vec![ChainReport {
index: 0,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom: EepromState::Absent,
response_per_mille: Some(950),
}],
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
operating_point: OperatingPoint {
voltage_mv: 1200,
frequency_mhz: 500,
confirmed: false,
},
psu: "APW12".into(),
fan_zones: Vec::new(),
},
active_chains: vec![0],
stopped: None,
frequency_mhz: 512,
target: "power:3000".into(),
});
Arc::new(status)
}
fn request(path: &str) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let status = status();
let worker = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
handle(stream, &status).expect("handle");
});
let mut client = Client::connect(address).expect("connect");
client
.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())
.expect("write");
let mut reply = String::new();
client.read_to_string(&mut reply).expect("read");
worker.join().expect("join");
reply
}
#[test]
fn the_page_is_served_at_root() {
let reply = request("/");
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("text/html"));
assert!(reply.contains("Alkane miner"));
}
#[test]
fn the_api_returns_the_hardware_document() {
let reply = request("/api/hardware");
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("application/json"));
assert!(reply.contains("s19jpro-bm1362-pic"));
assert!(reply.contains("bm1362"));
}
#[test]
fn unknown_paths_are_404() {
let reply = request("/nope");
assert!(reply.starts_with("HTTP/1.1 404 Not Found"));
}
#[test]
fn only_get_is_accepted() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("addr");
let status = status();
let worker = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
handle(stream, &status).expect("handle");
});
let mut client = Client::connect(address).expect("connect");
client
.write_all(b"POST / HTTP/1.1\r\nHost: miner\r\nContent-Length: 0\r\n\r\n")
.expect("write");
let mut reply = String::new();
client.read_to_string(&mut reply).expect("read");
worker.join().expect("join");
assert!(reply.starts_with("HTTP/1.1 405 Method Not Allowed"));
}
}