Compare commits

..
Author SHA1 Message Date
noah 7d398caa66 Reserve ASIC work IDs until hardware flush and fault on failed shutdown
next-build / build (push) Successful in 16s
2026-10-15 13:04:14 -06:00
noah 96dd7bf6d2 Clean OS CI outputs after build and release
next-build / build (push) Canceled after 0s
2026-10-15 11:48:14 -06:00
noah 59249d44d3 Verify BM1362 capture through shared miner work path
next-build / build (push) Canceled after 0s
2026-10-15 05:50:00 -06:00
noah f011557cd5 Add MIT Litecoin Scrypt share verifier
next-build / build (push) Canceled after 0s
2026-10-15 04:56:39 -06:00
noah d52996c02a Accept captured BM1362 share through strict pool
next-build / build (push) Canceled after 0s
2026-10-15 04:28:46 -06:00
noah b59aa8d9c1 Verify BM1362 captured share through HAL replay
next-build / build (push) Canceled after 0s
2026-10-15 04:20:29 -06:00
noah 523ec5fd0b Replay 33 captured BM1366 shares through pool
next-build / build (push) Canceled after 0s
2026-10-15 04:11:00 -06:00
noah a1d8e34390 Flush ASIC work before recycling job IDs
next-build / build (push) Canceled after 0s
2026-10-15 03:55:13 -06:00
noah 2d6233cdc7 Verify captured BM1366 share through strict pool replay
next-build / build (push) Canceled after 0s
2026-10-15 03:47:59 -06:00
noah eb9dcf830b Calibrate microbenchmarks and measure quality grade
next-build / build (push) Canceled after 0s
2026-10-15 03:17:58 -06:00
noah af49d4905d Require Git tag for completed release
next-build / build (push) Canceled after 0s
2026-10-15 03:09:11 -06:00
noah 8fa9e5d9e6 Bind share evidence to Stratum work and improve pool polling
next-build / build (push) Canceled after 0s
2026-10-15 03:07:16 -06:00
noah 492fe68c9e Verify release artifacts and keep uploads draft until complete
next-build / build (push) Canceled after 0s
2026-10-15 02:49:03 -06:00
noah f215cb3196 Fail closed on pool and HAL faults and bind release evidence to CI run
next-build / build (push) Canceled after 0s
2026-10-15 02:33:33 -06:00
noah 6e3b798273 Cross-check release evidence against built target matrix
next-build / build (push) Canceled after 0s
2026-10-15 02:16:34 -06:00
noah 16b55b58e3 Bound pool share replies and advance mining cycle
next-build / build (push) Canceled after 0s
2026-10-15 02:12:19 -06:00
noah 90a2fe12d5 Track pool jobs and share replies in connection
next-build / build (push) Canceled after 0s
2026-10-15 01:56:55 -06:00
noah bc38a4a787 Negotiate pool extensions and authorize over bounded transport
next-build / build (push) Canceled after 0s
2026-10-15 01:44:12 -06:00
noah 654b205e00 Add bounded Stratum TCP transport and request frames
next-build / build (push) Canceled after 0s
2026-10-15 01:31:33 -06:00
noah ece32ef55f Track Stratum jobs across ASIC work IDs
next-build / build (push) Canceled after 0s
2026-10-15 01:16:19 -06:00
noah 5cd77eb5de Convert pool difficulty to exact share targets
next-build / build (push) Successful in 11s
2026-10-15 01:00:53 -06:00
noah e7a23faa5a Decode Stratum pool control notifications
next-build / build (push) Canceled after 0s
2026-10-15 00:49:35 -06:00
noah e0f9b1ab50 Vendor pinned Rust dependencies for offline SDK builds
next-build / build (push) Canceled after 0s
2026-10-15 00:15:24 -06:00
noah 323e45ab0e Decode bounded Stratum V1 pool jobs
next-build / build (push) Canceled after 0s
2026-10-15 00:05:19 -06:00
noah 6fd329e047 Format mask-checked Stratum V1 share submissions
next-build / build (push) Canceled after 0s
2026-10-15 00:00:22 -06:00
noah 7d602d2f03 Keep in-flight ASIC work across pool job changes
next-build / build (push) Canceled after 0s
2026-10-14 20:57:56 -06:00
noah 78b9416985 Use Gitea-compatible pinned artifact uploads
next-build / build (push) Canceled after 0s
2026-10-14 20:51:16 -06:00
noah d2afef19a9 Construct SHA-256 Stratum work headers for BM1366
next-build / build (push) Canceled after 0s
2026-10-14 20:24:34 -06:00
noah e67ffcd204 Record private per-commit OS benchmark history
next-build / build (push) Canceled after 0s
2026-10-14 20:17:31 -06:00
noah 6cf9ed1620 Publish measured OS badges to private branch
next-build / build (push) Canceled after 0s
2026-10-14 20:11:09 -06:00
noah 4f21677ae5 Ignore cancelled runs in completed CI badge
next-build / build (push) Canceled after 0s
2026-10-14 19:58:25 -06:00
noah 9f7d8ebb51 Add fail-safe BM1366 mining session
next-build / build (push) Canceled after 0s
2026-10-14 19:53:40 -06:00
noah 81d726cca2 Publish branch badges from completed CI runs
next-build / build (push) Successful in 11s
2026-10-14 19:47:07 -06:00
noah 74ba049b5c Add reusable BM1366 work and report codec
next-build / build (push) Successful in 10s
2026-10-14 19:43:06 -06:00
noah 46a4f58019 Verify captured ASIC shares and probe SDK simulator
next-build / build (push) Successful in 13s
2026-10-14 19:37:38 -06:00
noah e9d7200a05 Keep bounded HAL connections dependency free
next-build / build (push) Canceled after 0s
2026-10-14 19:19:37 -06:00
noah 544711885e Bound HAL socket exchanges and validate errors
next-build / build (push) Canceled after 0s
2026-10-14 19:17:12 -06:00
noah 7d3cebea79 Add versioned SDK HAL socket client
next-build / build (push) Canceled after 0s
2026-10-14 19:10:17 -06:00
noah 1ce22d9d9f Merge branch 'main' into next
next-build / build (push) Successful in 9s
2026-10-13 11:59:47 -06:00
noah 4eef88b5df Point next CI badge at next attempts
next-build / build (push) Successful in 8s
2026-10-13 11:46:20 -06:00
32 changed files with 250 additions and 1420 deletions
-37
View File
@@ -1,37 +0,0 @@
name: public-benchmark-pages
on:
workflow_run:
workflows: [main-release-gate]
types: [completed]
workflow_dispatch:
concurrency:
group: alkane-os-public-benchmark-pages
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-pages
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: |
if ! command -v ssh >/dev/null 2>&1; then
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
fi
- name: Render measured benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py render
- name: Publish public benchmark page
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
run: python3 ci/publish-bench-pages.py os
- name: Clean generated page
if: always()
run: python3 ci/cleanup-generated.py
+2 -7
View File
@@ -4,21 +4,16 @@ on:
workflow_run:
workflows: [main-release-gate, next-build]
types: [completed]
workflow_dispatch:
concurrency:
group: alkane-os-completed-ci-badge
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-fast
runs-on: alkane-ci
permissions:
actions: read
contents: write
steps:
- uses: actions/checkout@v4
- name: Publish last completed attempts
- name: Publish last completed attempt
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/last-attempt-badge.py
-54
View File
@@ -1,54 +0,0 @@
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
+4 -23
View File
@@ -4,10 +4,6 @@ on:
push:
branches: [main]
concurrency:
group: alkane-os-main
cancel-in-progress: false
jobs:
verify-and-release:
runs-on: alkane-ci
@@ -20,12 +16,6 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Pages SSH client
run: |
if ! command -v ssh >/dev/null 2>&1; then
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
fi
- name: Install Rust quality tools
run: rustup component add rustfmt clippy
- name: Formatting
@@ -43,9 +33,7 @@ jobs:
- name: CI cleanup containment checks
run: python3 ci/test-cleanup-generated.py
- name: Quality
run: |
cargo clippy --all-targets --locked -- -D warnings
printf '{"format":true,"clippy_warnings_denied":true}\n' > quality-current.json
run: cargo clippy --all-targets --locked -- -D warnings
- name: Build
run: cargo build --release --locked
- name: Unit and workflow tests
@@ -56,18 +44,12 @@ jobs:
run: |
set -o pipefail
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
run: |
rustup component add llvm-tools-preview
if [ "$(cargo llvm-cov --version 2>/dev/null || true)" != 'cargo-llvm-cov 0.8.7' ]; then
cargo install --locked --force cargo-llvm-cov --version 0.8.7
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
cargo install --locked cargo-llvm-cov --version 0.8.7
fi
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
- name: Unit test coverage
run: |
mkdir -p coverage
@@ -85,13 +67,12 @@ jobs:
run: |
python3 ci/metrics.py --tests-output tests-current.txt \
--tests-coverage coverage/tests.json --bench-output bench-current.txt \
--bench-coverage coverage/bench.json --quality-gate quality-current.json
--bench-coverage coverage/bench.json
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-os-metrics
path: |
badges/metrics.json
quality-current.json
coverage/tests.json
coverage/bench.json
bench-current.txt
+1 -6
View File
@@ -4,16 +4,11 @@ on:
push:
branches: [next]
concurrency:
group: alkane-os-next
cancel-in-progress: false
jobs:
build:
runs-on: alkane-fast
runs-on: alkane-ci
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
steps:
- uses: actions/checkout@v4
with:
-1
View File
@@ -3,5 +3,4 @@
- Keep the project MIT-licensed and preserve third-party licenses in vendored dependencies.
- Use run-scoped Cargo output for one-off work. In CI, set `CARGO_TARGET_DIR=target` and remove generated target, coverage, benchmark, and release staging after artifact publication, including failed runs.
- Keep the main release gate on all seven boards, all 64 same-vendor pairings, unmodified stock firmware evidence, and genuine pool acceptance from real captured silicon nonces. Do not promote host-only probes to board conformance.
- Keep mining, tuning, HAL, API, protocol parsing, and on-device runtime logic in Rust. Use Python only for host tests, CI, release work, and disposable diagnostics unless a documented interface requires it.
- No emojis in files or persisted text.
+118 -39
View File
@@ -1,6 +1,6 @@
# Alkane OS
[![CI](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-os/actions)
[![CI](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/next.svg)](https://gitea.bluefla.re/blueflare/alkane-os/actions)
![tests](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/tests.svg)
![coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/coverage.svg)
![bench](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench.svg)
@@ -10,53 +10,132 @@
![code quality](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/quality.svg)
![license](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/license.svg)
Rust mining and tuning core for Alkane control boards. The
[SDK](https://gitea.bluefla.re/blueflare/alkane-sdk) builds board images and
provides the hardware backend. The miner has no on-board web frontend.
Portable mining, tuning, and management logic for Alkane control boards. The
source is MIT licensed. `alkane-sdk` owns the board images and supplies the
hardware backend at build time. This repository has no on-board web frontend;
the intended management surfaces are SSH, cgminer-compatible port 4028, and a
minimal API.
## Status
The host miner supports BM1362 and BM1366 through the SDK's simulator HAL and
Stratum V1. Tests have replayed 33 captured BM1366 shares and one BM1362
share to a loopback pool with matching ACCEPT responses. Production board
control is still under development.
This is an early mining core and release tooling, not a complete daemon. A
target in the matrix is an obligation to implement and validate, not a claim
of support. All 64 theoretical same-vendor controller/chip pairings are in
scope: 52 Bitmain and 12 WhatsMiner. For pairings a stock image rejects, the
simulator must record the first genuine rejection gate and Alkane OS must mine.
No live board is required by CI. Bench devices supply captures and independent
validation of the simulator.
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
power lease, watchdog, and validated temperature limits. SHA-256d and
Litecoin Scrypt proof verification are implemented; Scrypt chip report
handling and mining remain open.
The current executable lists target obligations (`alkane-os --list-targets`)
and its version. It does not start a miner or a network service. The library
now includes a versioned local Unix-socket client for the SDK hardware
backend, with bounded frames, two-second I/O timeouts, and fail-closed
response validation. The matching SDK server framing library exists, but no
board adapter is installed in an image yet.
The library can also verify an ASIC-reported SHA-256d share against an exact
pool target, including BM13xx version rolling. Host probes check captured
BM1362 and BM1366 nonces through the SDK's C/Python HAL replay server. From
this repository, run `cargo run --example simulator_replay_probe -- SOCKET_PATH
BM1362` or use `BM1366` after starting the corresponding SDK server. This
checks shared work/report framing and share validation for those two chips;
it does not initialize a physical chip chain.
The first BM1366 mining session sequences fan, temperature, PSU, reset,
work submission, and nonce polling through the HAL. It rejects stale work IDs,
malformed reports, and hashes above the caller's pool target. A sensor fault
requests PSU shutdown. A transport fault closes the HAL socket; the backend
must end its power lease on disconnect and have an independent hardware
watchdog. No production board backend meets that gate yet. The caller must
provide a board-validated temperature limit.
The library now formats verified shares as Stratum V1 `mining.submit` requests.
For negotiated BIP310 version rolling, it includes the sixth version-bits
parameter and rejects ASIC versions that the current pool mask cannot
represent. The pool transport bounds newline frames and uses absolute socket
deadlines. It can negotiate BIP310 extensions, subscribe, and authorize a
worker over a live TCP connection while retaining early notifications in wire
order. It has loopback tests; no live pool acceptance has been observed yet.
The pool connection applies difficulty and job messages in stream order,
dispatches work to the BM1366 mining session, and tracks up to 32 verified
share submissions by request ID. It counts accepted and rejected pool replies
separately. Continuous scheduling and live pool acceptance remain unverified.
The SDK's strict loopback pool replay test reconstructs 33 cv.106 BM1366
captured jobs from Stratum subscription and notify fields. It delivers those
jobs through the OS pool client and HAL simulator, replays the real ASIC
nonces, verifies each proof of work independently, and receives 33 matching
pool ACCEPT responses. The 33rd job also exercises the chain reset before
hardware work ID reuse. This is host-only evidence, not a stock-firmware
boot or a production board adapter.
The same strict pool fixture reconstructs one BM1362 job with an empty
extranonce2 and independently verifies its captured share before returning
ACCEPT. This extends the host pool path to a second chip family; physical
chain initialization and stock firmware remain unverified. A separate Rust
integration test feeds the pinned BM1362 header and 11-byte report through
the mining controller's work encoder, report decoder, and proof check.
The core also validates a supplied Litecoin Scrypt header using the fixed
N=1024, r=1, p=1 algorithm. Its output matches Litecoin's
[published block 29255 proof-of-work vector](https://github.com/litecoin-project/litecoin/wiki/Scrypt-proof-of-work)
and has a dedicated microbenchmark. This is a
share-verification primitive only; BM1489/BM1491 report decoding, pool
difficulty conventions, physical chain control, and L7/L9 acceptance remain
open.
Its cycle helper reads one pool event, drains up to 256 ASIC reports, and sends
verified shares when present. A share reply unanswered for 30 seconds closes
the connection so a caller can reconnect instead of filling the pending
queue indefinitely. Terminal pool errors request miner shutdown, and pool
reads use 1 ms slices after the handshake so ASIC polling continues. Partial
pool lines have a 2-second deadline and pool writes have a 100 ms deadline.
When the 32 hardware work IDs are exhausted, the client checks temperature,
resets the chain, discards old reports, and only then reuses an ID for the next
job. A reset failure requests PSU shutdown. A host test dispatches 33 jobs
and checks the reset boundary; sustained board operation is still unverified.
The executable still lacks a board adapter and run loop.
The Stratum V1 decoder bounds and validates `mining.subscribe` responses,
nine-field Bitcoin `mining.notify` jobs, difficulty and extranonce changes,
and negotiated BIP310 version-mask updates. Exact decimal difficulty values
become 256-bit pool targets without floating point rounding. Pool job
bookkeeping keeps earlier work tied to its original target and extranonce,
invalidates old work on `clean_jobs`, and rechecks a reported share before
formatting it for submission. It does not reuse ASIC work IDs until the caller
confirms a hardware reset. Hardware job dispatch and share reply tracking are
library-only so far; continuous mining remains to be implemented.
The exact Rust dependency sources are under `vendor/` with Cargo checksums,
so SDK board builds can compile offline. Dependencies retain the license terms
in their vendored manifests and license files.
Run `alkane-os --list-targets` for the target matrix. Set `POOL_PASSWORD` to
the pool password, then mine with a simulator HAL socket and Stratum V1 pool:
```sh
ALKANE_POOL_PASSWORD="$POOL_PASSWORD" alkane-os --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1366
```
Use `BM1362` for that chip. Set `ALKANE_API_LISTEN=127.0.0.1:4028` for
read-only `summary` and `version` commands; reach it remotely through SSH.
## Release gate
`main` runs tests, benchmarks, and conformance before release; `next` builds
release candidates. The release gate is red. It requires all 64 same-vendor
pairings (52 Bitmain, 12 WhatsMiner), unmodified stock firmware, captured
silicon nonces, difficulty-1 pool acceptance, and bench-validated models.
Stock firmware may faithfully reject a pairing; Alkane OS must mine it.
See the [evidence contract](ci/CONFORMANCE.md).
Badges cover host code, not board conformance. See the public
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/os/).
The `main` branch has full tests and a conformance gate; releases are created
only after every required cell passes. `next` runs a build check and produces
release candidates. `ci/version-x.txt` is the manually edited major version.
For this repository, Y changes when the mining protocol, HAL contract, tuning
policy or API changes; Z changes for compatible fixes and packaging updates.
## Local checks
```sh
CARGO_TARGET_DIR=/var/tmp/alkane-os-target cargo test --locked
export CARGO_TARGET_DIR=/var/tmp/alkane-os-target
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
cargo build --release --locked
GITHUB_RUN_ID=123 python3 ci/check-conformance.py
```
Use an executable target directory if the source mount is `noexec`.
Use an executable local `CARGO_TARGET_DIR` when the workspace mount strips
executable bits. Replace `123` with the numeric ID of the CI run that
generated its evidence. The last command currently fails because simulator
and device evidence are still pending. It cross-checks the matrix against the built binary's
targets and requires per-cell reports from the current CI run, bound to the
source commit and binary digest. Referenced artifacts are opened and hashed;
SHA-256 captured shares must satisfy a difficulty-one-or-harder target and
carry a matching pool ACCEPT response. Scrypt and Equihash verification is
pending. It is a release gate, not a unit test. The simulator
runner that produces this evidence has not yet been implemented.
The required artifact contract is in [ci/CONFORMANCE.md](ci/CONFORMANCE.md).
## License
[MIT](LICENSE). Vendored dependencies keep their own licenses.
The badges record measured host-side checks for this initial core. They do
not imply that any board image or mining target has passed conformance.
CI and metric badges are served from a private, machine-maintained branch.
The CI badge shows the last completed attempt for this source branch while
newer runs are queued; main CI refreshes measured metrics before conformance.
Microbenchmarks report the median of seven calibrated samples and compare
only with an earlier commit measured on the same CPU class. The code-quality
letter requires warnings-denied Clippy to pass and uses measured test line
coverage: A at 90%, B at 80%, C at 70%, D at 60%, and F below 60%.
+2 -6
View File
@@ -18,8 +18,7 @@ The report references files under `ci/evidence/` with objects containing
`simulator_model`, `control_capture`, `chip_capture`,
`alkane_share_accept_capture`, and `bench_validation`.
The checker opens and hashes each file. It loads the trace and capture JSON,
checks the current run/image/cell identities, verifies SHA-256d or Litecoin
Scrypt nonces against
checks the current run/image/cell identities, verifies SHA-256d nonces against
a pool target at difficulty 1 or higher, and requires a matching
`mining.submit` and pool ACCEPT response ID. A SHA-256 capture must include
the matching `subscription` (`extranonce1`, `extranonce2_size`), full
@@ -30,10 +29,7 @@ The checker reconstructs
the coinbase, merkle root, and complete submitted header; its 80 bytes and
calculated difficulty target must match the capture. The trace binds
the capture digests.
The Scrypt verifier uses [Litecoin's 80-byte, N=1024, r=1, p=1 proof hash](https://github.com/litecoin-project/litecoin/blob/master/src/crypto/scrypt.cpp).
Equihash proof verification remains pending, so its cells fail closed.
Scrypt cells also remain pending until real silicon reports, stock behavior,
and pool acceptance are captured for those chips.
Scrypt and Equihash share verifiers are pending, so those cells fail closed.
Bench calibration names the physical control-board and chip devices, their
capture digests, and the simulator model digest. It can be reused across OS
commits until the model or a physical capture changes.
+1 -8
View File
@@ -120,7 +120,7 @@ def render_html(index: dict) -> str:
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("prepare", "publish", "render"))
parser.add_argument("action", choices=("prepare", "publish"))
args = parser.parse_args()
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
@@ -135,13 +135,6 @@ def main() -> None:
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
print(f"Loaded {len(baseline)} prior benchmark measurements")
return
if args.action == "render":
if not index["entries"]:
raise ValueError("no measured benchmark history to publish")
Path("bench-site").mkdir(exist_ok=True)
Path("bench-site/index.html").write_text(render_html(index))
print(f"Rendered {len(index['entries'])} measured benchmark commits")
return
metrics = json.loads(Path("badges/metrics.json").read_text())
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
index = updated_index(index, sha, metrics, timestamp)
+2 -10
View File
@@ -149,16 +149,8 @@ def reconstructed_header(capture: dict, params: list[str]) -> tuple[bytes, int]:
return bytes(header), submitted_nonce
def proof_digest(header: bytes, algorithm: str) -> bytes:
if algorithm == "Sha256":
return hashlib.sha256(hashlib.sha256(header).digest()).digest()
if algorithm == "Scrypt":
return hashlib.scrypt(header, salt=header, n=1024, r=1, p=1, dklen=32)
raise ValueError(f"{algorithm} share verifier is not implemented")
def verify_accept(capture: dict, algorithm: str) -> None:
if algorithm not in ("Sha256", "Scrypt"):
if algorithm != "Sha256":
raise ValueError(f"{algorithm} share verifier is not implemented")
if capture.get("nonce_source") != "real_silicon_capture":
raise ValueError("share was not sourced from captured silicon")
@@ -212,7 +204,7 @@ def verify_accept(capture: dict, algorithm: str) -> None:
rebuilt, submitted_nonce = reconstructed_header(capture, params)
if submitted_nonce != nonce or rebuilt != header:
raise ValueError("submitted Stratum job differs from captured header")
hash_bytes = proof_digest(header, algorithm)
hash_bytes = hashlib.sha256(hashlib.sha256(header).digest()).digest()
if int.from_bytes(hash_bytes, "little") > target:
raise ValueError("captured nonce misses the pool target")
+1 -1
View File
@@ -10,7 +10,7 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "coverage", "dist", "bench-site")
FILES = ("tests-current.txt", "bench-current.txt", "quality-current.json")
FILES = ("tests-current.txt", "bench-current.txt")
def cleanup() -> None:
+15 -9
View File
@@ -2,7 +2,9 @@
# SPDX-License-Identifier: MIT
"""Publish the last completed main/next CI result to a private badge branch."""
import json
import os
from pathlib import Path
from urllib.parse import quote, urlencode
from badge_store import publish_file, request_json
@@ -55,18 +57,22 @@ def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None:
def main() -> None:
if os.environ["GITHUB_EVENT_NAME"] not in ("workflow_run", "workflow_dispatch"):
raise RuntimeError("badge publisher must follow CI completion or manual dispatch")
if os.environ["GITHUB_REF"] != "refs/heads/main":
raise RuntimeError("badge publisher must use the main branch")
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
if event.get("action") != "completed":
raise RuntimeError("expected a completed workflow_run event")
run = event["workflow_run"]
workflow = run["path"].split("@", 1)[0].rsplit("/", 1)[-1]
expected_branch = WORKFLOWS.get(workflow)
if expected_branch is None or run.get("head_branch") != expected_branch:
raise RuntimeError("unexpected workflow or branch")
repo = os.environ["GITHUB_REPOSITORY"]
if event["repository"]["full_name"] != repo:
raise RuntimeError("repository mismatch")
api = os.environ["GITHUB_API_URL"].rstrip("/")
token = os.environ["GITEA_TOKEN"]
completed = {branch: latest_completed(api, repo, workflow, branch, token)
for workflow, branch in WORKFLOWS.items()}
for branch, (run_id, conclusion) in completed.items():
publish(api, repo, branch, badge(branch, conclusion, run_id), token)
print(f"{branch} badge records completed run {run_id}: {conclusion}")
run_id, conclusion = latest_completed(api, repo, workflow, expected_branch, token)
publish(api, repo, expected_branch, badge(expected_branch, conclusion, run_id), token)
print(f"{expected_branch} badge records completed run {run_id}: {conclusion}")
if __name__ == "__main__":
+21 -54
View File
@@ -4,26 +4,11 @@
import argparse
import html
import json
import math
import pathlib
import re
import tomllib
from bench_host import identity as benchmark_host
EXPECTED_BENCHES = frozenset({
"target_matrix", "power_policy", "share_verification",
"scrypt_share_verification", "bm1366_work_encoding", "bm1362_commands",
"bm1362_job_encoding", "bm1366_report_decode", "stratum_header",
"stratum_submission", "stratum_authorize_format", "stratum_notify_parse",
"stratum_control_parse", "stratum_configure_parse", "difficulty_target",
"stratum_job_issue", "bm1366_session_cycle", "bm1362_work_encoding",
"stratum_configure_format", "stratum_subscribe_format",
"stratum_subscription_parse", "stratum_accept_parse",
"hal_socket_exchange", "stratum_socket_round_trip",
"bm13xx_crc5", "bm13xx_crc16", "bm1366_captured_report_poll",
})
BENCH_LINE = re.compile(r"\bBENCH ([A-Za-z0-9_]+) ([0-9]+(?:\.[0-9]+)?) ns/op\Z")
def coverage(path):
data = json.loads(pathlib.Path(path).read_text())
@@ -31,40 +16,8 @@ def coverage(path):
def bench_results(path):
results = {}
for line in pathlib.Path(path).read_text().splitlines():
if "BENCH " not in line:
continue
match = BENCH_LINE.search(line)
if match is None:
raise ValueError("malformed microbenchmark result")
name, value = match.groups()
measurement = float(value)
if name in results or not math.isfinite(measurement) or measurement <= 0:
raise ValueError("duplicate or invalid microbenchmark result")
results[name] = measurement
return results
def benchmark_delta(current, baseline):
if set(current) != EXPECTED_BENCHES:
raise ValueError("microbenchmark set differs from the declared suite")
if not isinstance(baseline, dict) or not set(baseline).issubset(current):
raise ValueError("baseline contains retired or invalid benchmarks")
if any(not isinstance(value, (int, float)) or isinstance(value, bool)
or not math.isfinite(value) or value <= 0 for value in baseline.values()):
raise ValueError("baseline contains invalid measurements")
if not baseline:
return None
return sum((baseline[name] - current[name]) / baseline[name]
for name in baseline) / len(baseline) * 100
def quality_grade(path):
checks = json.loads(pathlib.Path(path).read_text())
if checks != {"format": True, "clippy_warnings_denied": True}:
raise ValueError("format and strict Clippy must pass before publishing quality")
return "A"
text = pathlib.Path(path).read_text()
return {name: float(ns) for name, ns in re.findall(r"BENCH (\w+) ([0-9.]+) ns/op", text)}
def compact(number):
@@ -81,6 +34,19 @@ def compact(number):
return number + units[index]
def quality_grade(line_coverage):
# Main CI reaches this publisher only after warnings-denied Clippy passes.
if line_coverage >= 90:
return "A"
if line_coverage >= 80:
return "B"
if line_coverage >= 70:
return "C"
if line_coverage >= 60:
return "D"
return "F"
def svg(label, value, color):
label, value = html.escape(label), html.escape(value)
lw, vw = 12 + 7 * len(label), 12 + 7 * len(value)
@@ -99,7 +65,6 @@ def main():
parser.add_argument("--tests-coverage", required=True)
parser.add_argument("--bench-output", required=True)
parser.add_argument("--bench-coverage", required=True)
parser.add_argument("--quality-gate", required=True)
parser.add_argument("--bench-baseline", default="badges/bench-baseline.json")
args = parser.parse_args()
test_output = pathlib.Path(args.tests_output).read_text()
@@ -107,9 +72,13 @@ def main():
if tests < 1:
raise SystemExit("no passing tests parsed")
current = bench_results(args.bench_output)
if not current or any(value <= 0 for value in current.values()):
raise SystemExit("microbenchmark result missing or zero")
base_path = pathlib.Path(args.bench_baseline)
baseline = json.loads(base_path.read_text()) if base_path.exists() else {}
delta = benchmark_delta(current, baseline)
common = [name for name in current if name in baseline and baseline[name] > 0]
delta = (sum((baseline[name] - current[name]) / baseline[name] for name in common)
/ len(common) * 100) if common else None
line_coverage = coverage(args.tests_coverage)
bench_coverage = coverage(args.bench_coverage)
loc = sum(len(path.read_text().splitlines()) for parent in (pathlib.Path("src"), pathlib.Path("ci"))
@@ -121,9 +90,7 @@ def main():
"bench_ns_per_op": current, "bench_improvement_pct": delta,
"bench_host": benchmark_host(),
"lines_of_code": loc, "dependencies": dependencies,
"code_quality": quality_grade(args.quality_gate),
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"}
"code_quality": quality_grade(line_coverage), "license": "MIT"}
pathlib.Path("badges").mkdir(exist_ok=True)
pathlib.Path("badges/metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")
badges = {
-125
View File
@@ -1,125 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish a measured benchmark page to the public, data-only Pages repo."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
import tempfile
from urllib.request import Request, urlopen
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
PAGES_HOST = "gitea.bluefla.re"
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
def run(*args: str, env: dict[str, str] | None = None,
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
result = subprocess.run(args, env=env, cwd=cwd, text=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:
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
request = Request(f"{api}/repos/{repo}/branches/main",
headers={"Authorization": f"token {token}"})
with urlopen(request, timeout=20) as response:
branch = json.load(response)
return branch["commit"]["id"]
def publish(site: str) -> None:
if os.environ.get("GITHUB_REF") != "refs/heads/main":
raise ValueError("benchmark Pages publication requires main")
sha = os.environ["GITHUB_SHA"]
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
page = Path("bench-site/index.html").read_bytes()
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
raise ValueError("invalid benchmark page")
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
temporary = Path(directory)
guard_checkout = temporary / "guard"
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
GUARD_REPO, str(guard_checkout))
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
cwd=guard_checkout).stdout
guard_script = temporary / "validate_site.py"
guard_script.write_text(guard_source)
run("python3", str(guard_script), "--page", site,
str(Path("bench-site/index.html").resolve()))
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
raise ValueError("missing benchmark Pages deploy key")
key_path = temporary / "deploy_key"
key_path.write_text(key.rstrip("\n") + "\n")
key_path.chmod(0o600)
known_hosts = temporary / "known_hosts"
known_hosts.write_text(PAGES_HOST_KEY + "\n")
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
if fingerprint != PAGES_HOST_FINGERPRINT:
raise ValueError("benchmark Pages SSH host key changed")
git_env = os.environ.copy()
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
git_env["GIT_SSH_COMMAND"] = ssh_command
git_env["GIT_TERMINAL_PROMPT"] = "0"
checkout = temporary / "site"
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
PAGES_REPO, str(checkout), env=git_env)
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
for attempt in range(3):
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
cwd=checkout)
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
cwd=checkout)
destination = checkout / site / "index.html"
destination.parent.mkdir(exist_ok=True)
destination.write_bytes(page)
run("git", "add", f"{site}/index.html", cwd=checkout)
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
cwd=checkout, check=False)
if changed.returncode == 0:
print(f"{site} benchmark page is already current")
return
if changed.returncode != 1:
raise RuntimeError("cannot compare benchmark page")
run("git", "commit", "-q", "-m",
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
pushed = subprocess.run(("git", "push", "--quiet", "origin",
"HEAD:gh-pages"), env=git_env, cwd=checkout,
text=True, capture_output=True, check=False)
if pushed.returncode == 0:
print(f"Published {site} benchmark page for {sha[:10]}")
return
if attempt == 2:
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
raise RuntimeError("benchmark Pages publication did not complete")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
publish(parser.parse_args().site)
if __name__ == "__main__":
main()
+3 -17
View File
@@ -64,23 +64,9 @@ class ConformanceGateTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "submitted nonce"):
gate.verify_accept(capture, "Sha256")
def test_scrypt_proof_matches_litecoin_and_independent_vectors(self):
header = bytes.fromhex(
"01000000f615f7ce3b4fc6b8f61e8f89aedb1d0852507650533a9e3b10b9bbcc30639f27"
"9fcaa86746e1ef52d3edb3c4ad8259920d509bd073605c9bf1d59983752a6b06b817bb4"
"ea78e011d012d59d4"
)
self.assertEqual(len(header), 80)
self.assertEqual(
gate.proof_digest(header, "Scrypt")[::-1].hex(),
"0000000110c8357966576df46f3b802ca897deb7ad18b12f1c24ecff6386ebd9",
)
self.assertEqual(
gate.proof_digest(bytes(range(80)), "Scrypt").hex(),
"bc540a1a801df96e493005c71e010e2d387607fbf0fec416fd3c2645aa1ba9d2",
)
def test_equihash_cells_still_need_an_algorithm_specific_verifier(self):
def test_non_sha256_cells_need_algorithm_specific_verifiers(self):
with self.assertRaisesRegex(ValueError, "Scrypt share verifier"):
gate.verify_accept({}, "Scrypt")
with self.assertRaisesRegex(ValueError, "Equihash share verifier"):
gate.verify_accept({}, "Equihash")
-28
View File
@@ -3,7 +3,6 @@
"""Check that queued CI runs do not displace the last completed result."""
import importlib.util
import os
from pathlib import Path
from unittest.mock import patch
import xml.etree.ElementTree as ET
@@ -35,33 +34,6 @@ assert root.attrib["aria-label"] == "CI main: last completed attempt fail (run 1
assert b">fail</text>" in svg
assert b"#d1242f" in svg
assert b">pass</text>" in module.badge("next", "success", 108)
environment = {
"GITHUB_EVENT_NAME": "workflow_run",
"GITHUB_REF": "refs/heads/main",
"GITHUB_REPOSITORY": "owner/repo",
"GITHUB_API_URL": "https://example.invalid/api/v1",
"GITEA_TOKEN": "test-token",
}
with patch.dict(os.environ, environment), \
patch.object(module, "latest_completed", side_effect=[(201, "success"),
(202, "failure")]) as latest, \
patch.object(module, "publish") as published:
module.main()
assert latest.call_count == 2
assert [call.args[2] for call in published.call_args_list] == ["main", "next"]
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:
module.main()
except RuntimeError as error:
assert "CI completion or manual dispatch" in str(error)
else:
raise AssertionError("scheduled event entered badge publisher")
for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"):
try:
publish_file("https://example.invalid/api/v1", "owner/repo", invalid,
+8 -28
View File
@@ -3,49 +3,29 @@
"""Regression checks for measured benchmark and quality badges."""
import sys
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
from metrics import EXPECTED_BENCHES, bench_results, benchmark_delta, compact, quality_grade
from metrics import bench_results, compact, quality_grade
class MetricTests(unittest.TestCase):
def test_quality_requires_both_static_checks(self):
with TemporaryDirectory() as directory:
path = Path(directory) / "quality.json"
path.write_text(json.dumps({"format": True, "clippy_warnings_denied": True}))
self.assertEqual(quality_grade(path), "A")
path.write_text(json.dumps({"format": True, "clippy_warnings_denied": False}))
with self.assertRaises(ValueError):
quality_grade(path)
def test_quality_grade_depends_on_measured_coverage(self):
self.assertEqual(quality_grade(92), "A")
self.assertEqual(quality_grade(88), "B")
self.assertEqual(quality_grade(72), "C")
self.assertEqual(quality_grade(65), "D")
self.assertEqual(quality_grade(40), "F")
def test_benchmark_parser_and_short_si_badge(self):
with TemporaryDirectory() as directory:
path = Path(directory) / "bench.txt"
path.write_text("test bench_sha ... BENCH sha 42.125 ns/op\n")
path.write_text("BENCH sha 42.125 ns/op\n")
self.assertEqual(bench_results(path), {"sha": 42.125})
path.write_text("BENCH sha 42.125 ns/op\nBENCH sha 40.000 ns/op\n")
with self.assertRaisesRegex(ValueError, "duplicate"):
bench_results(path)
path.write_text("BENCH sha 42.125 ns/op\nBENCH broken nan ns/op\n")
with self.assertRaisesRegex(ValueError, "malformed"):
bench_results(path)
self.assertEqual(compact(1234567), "1.23M")
def test_benchmark_suite_and_baseline_must_be_complete(self):
current = {name: 10.0 for name in EXPECTED_BENCHES}
self.assertIsNone(benchmark_delta(current, {}))
self.assertEqual(benchmark_delta(current, {"target_matrix": 20.0}), 50.0)
with self.assertRaisesRegex(ValueError, "declared suite"):
benchmark_delta({"target_matrix": 10.0}, {})
with self.assertRaisesRegex(ValueError, "retired"):
benchmark_delta(current, {"removed_bench": 20.0})
with self.assertRaisesRegex(ValueError, "invalid measurements"):
benchmark_delta(current, {"target_matrix": float("inf")})
if __name__ == "__main__":
unittest.main()
+8 -6
View File
@@ -2,7 +2,7 @@
//! Exercise the SDK's host-only BM13xx HAL simulator with a captured job.
use alkane_os::hal_wire::HalClient;
use alkane_os::miner::{Bm1366Miner, ChipModel};
use alkane_os::miner::Bm1366Miner;
use std::error::Error;
use std::io;
@@ -38,14 +38,16 @@ fn main() -> Result<(), Box<dyn Error>> {
if args.next().is_some() {
return Err("unexpected argument".into());
}
let (header, nonce, model) = match chip.as_str() {
"BM1366" => (HEADER, 0xedad_ff38, ChipModel::Bm1366),
"BM1362" => (bm1362_header()?, 0x630b_2533, ChipModel::Bm1362),
let (header, nonce) = match chip.as_str() {
"BM1366" => (HEADER, 0xedad_ff38),
"BM1362" => (bm1362_header()?, 0x630b_2533),
_ => return Err("unsupported captured chip".into()),
};
let mut backend = HalClient::connect(path)?;
// Chip initialization is outside this host-only check.
let mut miner = Bm1366Miner::new_for_chip(&mut backend, model, 0, 0, 0, 100, 80_000)
// BM1362 and BM1366 share the observed 88-byte job and 11-byte report
// framing exercised by this miner. Chip initialization is outside this
// host-only check.
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000)
.ok_or("invalid simulator probe configuration")?;
miner.start()?;
let mut target = [0_u8; 32];
-232
View File
@@ -1,232 +0,0 @@
// SPDX-License-Identifier: MIT
//! BM1362 frame encoding from captured command and job traffic.
//!
//! These pure encoders do not initialize a chain. PLL fields, voltage, and
//! model-specific operating points still require silicon-backed validation.
use crate::bm13xx::{crc16, crc5, reverse_words};
pub const JOB_BYTES: usize = 88;
pub const CHIP_ADDRESS_STEP: u8 = 2;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ModelGeometry {
chips_per_chain: u8,
ticket_mask: u8,
}
pub const S19J_PRO: ModelGeometry = ModelGeometry {
chips_per_chain: 126,
ticket_mask: 0x7f,
};
pub const S19J: ModelGeometry = ModelGeometry {
chips_per_chain: 108,
ticket_mask: 0x7f,
};
pub const S19_88: ModelGeometry = ModelGeometry {
chips_per_chain: 88,
ticket_mask: 0x3f,
};
impl ModelGeometry {
pub const fn new(chips_per_chain: u8, ticket_mask: u8) -> Option<Self> {
if chips_per_chain == 0 || chips_per_chain > 128 {
return None;
}
Some(Self {
chips_per_chain,
ticket_mask,
})
}
pub const fn chips_per_chain(self) -> u8 {
self.chips_per_chain
}
pub const fn ticket_mask(self) -> u8 {
self.ticket_mask
}
/// Addresses for an observed two-address-step enumeration walk.
pub fn chip_addresses(self) -> impl Iterator<Item = u8> {
(0..self.chips_per_chain).map(|index| index * CHIP_ADDRESS_STEP)
}
}
fn short_command(code: u8, address: u8, register: u8) -> [u8; 7] {
let mut frame = [0x55, 0xaa, code, 0x05, address, register, 0];
frame[6] = crc5(&frame[2..6]);
frame
}
fn long_command(code: u8, address: u8, register: u8, value: u32) -> [u8; 11] {
let mut frame = [0_u8; 11];
frame[..6].copy_from_slice(&[0x55, 0xaa, code, 0x09, address, register]);
frame[6..10].copy_from_slice(&value.to_be_bytes());
frame[10] = crc5(&frame[2..10]);
frame
}
pub fn chain_inactive() -> [u8; 7] {
short_command(0x53, 0, 0)
}
pub fn set_chip_address(address: u8) -> [u8; 7] {
short_command(0x40, address, 0)
}
pub fn read_register(address: u8, register: u8) -> [u8; 7] {
short_command(0x42, address, register)
}
pub fn read_register_all(register: u8) -> [u8; 7] {
short_command(0x52, 0, register)
}
pub fn write_register(address: u8, register: u8, value: u32) -> [u8; 11] {
long_command(0x41, address, register, value)
}
pub fn write_register_all(register: u8, value: u32) -> [u8; 11] {
long_command(0x51, 0, register, value)
}
/// Raw header fields in BM1362 wire order. The caller owns work-ID allocation
/// and must supply roots and hashes in the order established by its capture.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Job {
pub work_id: u8,
pub num_midstates: u8,
pub start_nonce: u32,
pub nbits: u32,
pub ntime: u32,
pub merkle_root: [u8; 32],
pub previous_hash: [u8; 32],
pub version: u32,
}
/// Encode the 88-byte SEND_JOB form with the true-length tag observed on wire.
pub fn encode_job(job: &Job) -> [u8; JOB_BYTES] {
let mut frame = [0_u8; JOB_BYTES];
frame[..6].copy_from_slice(&[0x55, 0xaa, 0x21, 0x56, job.work_id, job.num_midstates]);
frame[6..10].copy_from_slice(&job.start_nonce.to_le_bytes());
frame[10..14].copy_from_slice(&job.nbits.to_le_bytes());
frame[14..18].copy_from_slice(&job.ntime.to_le_bytes());
frame[18..50].copy_from_slice(&job.merkle_root);
frame[50..82].copy_from_slice(&job.previous_hash);
frame[82..86].copy_from_slice(&job.version.to_le_bytes());
let checksum = crc16(&frame[2..86]);
frame[86..88].copy_from_slice(&checksum.to_be_bytes());
frame
}
/// Encode one nonce-zero pool header in the observed raw-header job layout.
/// This covers work delivery; chain initialization still needs board evidence.
pub fn encode_work(header: &[u8; 80], work_id: u8) -> Option<[u8; JOB_BYTES]> {
if header[76..80] != [0; 4] || work_id & 7 != 0 {
return None;
}
Some(encode_job(&Job {
work_id,
num_midstates: 1,
start_nonce: 0,
nbits: u32::from_le_bytes(header[72..76].try_into().expect("nbits")),
ntime: u32::from_le_bytes(header[68..72].try_into().expect("ntime")),
merkle_root: reverse_words(&header[36..68]),
previous_hash: reverse_words(&header[4..36]),
version: u32::from_le_bytes(header[..4].try_into().expect("version")),
}))
}
/// BT8D for a 25 MHz input clock with BCLK_SEL=0. A model must still choose
/// the actual target baud and confirm switching on silicon.
pub fn bt8d_for_baud(baud: u32) -> Option<u8> {
if baud == 0 || baud > 3_125_000 {
return None;
}
let divider = 25_000_000_u64 / (8 * u64::from(baud));
u8::try_from(divider - 1).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captured_command_frames() {
assert_eq!(chain_inactive(), [0x55, 0xaa, 0x53, 5, 0, 0, 3]);
assert_eq!(set_chip_address(0), [0x55, 0xaa, 0x40, 5, 0, 0, 0x1c]);
assert_eq!(set_chip_address(8), [0x55, 0xaa, 0x40, 5, 8, 0, 7]);
assert_eq!(read_register_all(0), [0x55, 0xaa, 0x52, 5, 0, 0, 0x0a]);
assert_eq!(
read_register(0x40, 0x1c),
[0x55, 0xaa, 0x42, 5, 0x40, 0x1c, 0x0b]
);
assert_eq!(
write_register_all(0x80, 0),
[0x55, 0xaa, 0x51, 9, 0, 0x80, 0, 0, 0, 0, 0x1c]
);
assert_eq!(
write_register(0x40, 0x18, 0x7a31),
[0x55, 0xaa, 0x41, 9, 0x40, 0x18, 0, 0, 0x7a, 0x31, 0x11]
);
}
#[test]
fn model_address_limits() {
assert_eq!(ModelGeometry::new(0, 0), None);
assert_eq!(ModelGeometry::new(129, 0), None);
assert_eq!(
ModelGeometry::new(128, 0).unwrap().chip_addresses().last(),
Some(0xfe)
);
assert_eq!(S19J_PRO.chip_addresses().last(), Some(0xfa));
assert_eq!(S19J.chip_addresses().last(), Some(0xd6));
assert_eq!(S19_88.chip_addresses().last(), Some(0xae));
}
#[test]
fn job_frame_layout() {
let mut merkle_root = [0_u8; 32];
let mut previous_hash = [0_u8; 32];
for index in 0..32 {
merkle_root[index] = 0xa0 + index as u8;
previous_hash[index] = 0x10 + index as u8;
}
let frame = encode_job(&Job {
work_id: 8,
num_midstates: 1,
start_nonce: 0,
nbits: 0x1a1f_2c34,
ntime: 0x5e9b_3cd4,
merkle_root,
previous_hash,
version: 0x2000_0000,
});
assert_eq!(
&frame[..18],
&[
0x55, 0xaa, 0x21, 0x56, 8, 1, 0, 0, 0, 0, 0x34, 0x2c, 0x1f, 0x1a, 0xd4, 0x3c, 0x9b,
0x5e
]
);
assert_eq!(&frame[18..50], &merkle_root);
assert_eq!(&frame[50..82], &previous_hash);
assert_eq!(&frame[82..86], &[0, 0, 0, 0x20]);
assert_eq!(&frame[86..88], &[0xc2, 0xbd]);
assert_eq!(
u16::from_be_bytes([frame[86], frame[87]]),
crc16(&frame[2..86])
);
}
#[test]
fn baud_dividers() {
assert_eq!(bt8d_for_baud(0), None);
assert_eq!(bt8d_for_baud(3_000_000), Some(0));
assert_eq!(bt8d_for_baud(115_200), Some(26));
assert_eq!(bt8d_for_baud(1), None);
assert_eq!(bt8d_for_baud(3_125_001), None);
assert_eq!(bt8d_for_baud(u32::MAX), None);
}
}
+35 -6
View File
@@ -4,9 +4,6 @@
pub const WORK_BYTES: usize = 88;
pub const REPORT_BYTES: usize = 11;
pub use crate::bm13xx::crc16;
use crate::bm13xx::{crc5, reverse_words};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NonceReport {
pub nonce: u32,
@@ -23,6 +20,41 @@ pub enum ReportError {
Checksum,
}
pub fn crc16(bytes: &[u8]) -> u16 {
let mut value = 0xffff_u16;
for byte in bytes {
value ^= u16::from(*byte) << 8;
for _ in 0..8 {
value = if value & 0x8000 != 0 {
(value << 1) ^ 0x1021
} else {
value << 1
};
}
}
value
}
fn crc5(bytes: &[u8]) -> u8 {
let mut value = 0x1f_u8;
for byte in bytes {
for shift in (0..8).rev() {
let feedback = ((value >> 4) ^ (byte >> shift)) & 1;
value = ((value << 1) | feedback) & 0x1f;
value ^= feedback << 2;
}
}
value
}
fn reverse_words(input: &[u8]) -> [u8; 32] {
let mut output = [0_u8; 32];
for index in 0..8 {
output[index * 4..index * 4 + 4].copy_from_slice(&input[(7 - index) * 4..(8 - index) * 4]);
}
output
}
/// Encode a nonce-zero Bitcoin header for the observed 88-byte SEND_JOB form.
/// The low three work-ID bits are reserved by the BM1366 response format.
pub fn encode_work(header: &[u8; 80], work_id: u8) -> Option<[u8; WORK_BYTES]> {
@@ -32,8 +64,6 @@ pub fn encode_work(header: &[u8; 80], work_id: u8) -> Option<[u8; WORK_BYTES]> {
let mut frame = [0_u8; WORK_BYTES];
frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]);
frame[4] = work_id;
// The captured 88-byte on-die-midstate job uses one midstate.
frame[5] = 1;
frame[10..14].copy_from_slice(&header[72..76]);
frame[14..18].copy_from_slice(&header[68..72]);
frame[18..50].copy_from_slice(&reverse_words(&header[36..68]));
@@ -80,7 +110,6 @@ mod tests {
let header: [u8; 80] = hex_header();
let frame = encode_work(&header, 0x18).unwrap();
assert_eq!(&frame[..5], &[0x55, 0xaa, 0x21, 0x54, 0x18]);
assert_eq!(frame[5], 1);
assert_eq!(
crc16(&frame[2..86]),
u16::from_be_bytes([frame[86], frame[87]])
-66
View File
@@ -1,66 +0,0 @@
// SPDX-License-Identifier: MIT
//! Shared BM13xx wire checksums. This module never generates mining nonces.
/// Reverse the eight 32-bit header words for the observed SEND_JOB layout.
pub(crate) fn reverse_words(input: &[u8]) -> [u8; 32] {
let mut output = [0_u8; 32];
for index in 0..8 {
output[index * 4..index * 4 + 4].copy_from_slice(&input[(7 - index) * 4..(8 - index) * 4]);
}
output
}
/// CRC5 used by command and nonce-report frames, initial value 0x1f.
pub fn crc5(bytes: &[u8]) -> u8 {
let mut state = 0x1f_u8;
for &byte in bytes {
for bit in (0..8).rev() {
let feedback = ((state >> 4) ^ (byte >> bit)) & 1;
state = ((state << 1) | feedback) & 0x1f;
state ^= feedback << 2;
}
}
state
}
/// CRC16-CCITT-FALSE used by 88-byte SEND_JOB frames.
pub fn crc16(bytes: &[u8]) -> u16 {
let mut state = 0xffff_u16;
for &byte in bytes {
state ^= u16::from(byte) << 8;
for _ in 0..8 {
state = if state & 0x8000 == 0 {
state << 1
} else {
(state << 1) ^ 0x1021
};
}
}
state
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captured_command_checksums() {
let vectors: &[(&[u8], u8)] = &[
(&[0x53, 0x05, 0, 0], 0x03),
(&[0x40, 0x05, 0, 0], 0x1c),
(&[0x52, 0x05, 0, 0], 0x0a),
(&[0x40, 0x05, 8, 0], 0x07),
(&[0x42, 0x05, 0x40, 0x1c], 0x0b),
(&[0x51, 0x09, 0, 0x80, 0, 0, 0, 0], 0x1c),
(&[0x41, 0x09, 0x40, 0x18, 0, 0, 0x7a, 0x31], 0x11),
];
for &(body, expected) in vectors {
assert_eq!(crc5(body), expected);
}
}
#[test]
fn standard_crc16_check() {
assert_eq!(crc16(b"123456789"), 0x29b1);
}
}
-3
View File
@@ -3,12 +3,9 @@
//! 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.
pub mod bm1362;
pub mod bm1366;
pub mod bm13xx;
pub mod difficulty;
pub mod hal_wire;
pub mod management;
pub mod miner;
pub mod pow;
pub mod scrypt_pow;
+2 -89
View File
@@ -1,88 +1,7 @@
// SPDX-License-Identifier: MIT
use alkane_os::hal_wire::HalClient;
use alkane_os::management::{bind_local, serve, MiningStatus};
use alkane_os::miner::{Bm1366Miner, ChipModel};
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
use alkane_os::target_matrix;
use std::error::Error;
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let socket = args.next().ok_or("missing HAL socket")?;
let address: SocketAddr = args.next().ok_or("missing pool address")?.parse()?;
let worker = args.next().ok_or("missing pool worker")?;
let chip = match args.next().as_deref() {
Some("BM1362") => ChipModel::Bm1362,
Some("BM1366") => ChipModel::Bm1366,
_ => return Err("select BM1362 or BM1366".into()),
};
let max_accepts: Option<u64> = args.next().map(|value| value.parse()).transpose()?;
if args.next().is_some() || worker.is_empty() || max_accepts == Some(0) {
return Err("invalid simulator mining arguments".into());
}
let password = std::env::var("ALKANE_POOL_PASSWORD")
.map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?;
let status = Arc::new(MiningStatus::new());
if let Ok(bind) = std::env::var("ALKANE_API_LISTEN") {
let listener = bind_local(bind.parse()?)?;
let snapshot = Arc::clone(&status);
std::thread::spawn(move || {
if let Err(error) = serve(listener, snapshot) {
eprintln!("management API stopped: {error}");
}
});
}
// Connect to the pool before enabling power. The SDK HAL server owns the
// power lease and cuts power if this process stalls or disconnects.
let mut pool = PoolConnection::connect(
address,
concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
&worker,
&password,
Duration::from_secs(2),
Duration::from_secs(5),
)
.map_err(|error| io::Error::other(format!("pool handshake: {error:?}")))?;
let mut backend = HalClient::connect(socket)?;
let mut miner = Bm1366Miner::new_for_chip(&mut backend, chip, 0, 0, 0, 100, 80_000)
.ok_or("invalid simulator safety configuration")?;
miner.start()?;
status.set_running(true);
let mut accepted = 0_u64;
loop {
let (event, reports) = pool
.cycle(&mut miner)
.map_err(|error| io::Error::other(format!("mining cycle: {error:?}")))?;
match event {
PoolEvent::ShareAccepted(_) => {
accepted += 1;
status.share_accepted();
if max_accepts == Some(accepted) {
miner.stop()?;
status.set_running(false);
println!("simulator shares accepted: {accepted}");
return Ok(());
}
}
PoolEvent::ShareRejected(id) => {
status.share_rejected();
eprintln!("pool rejected share request {id}");
}
_ => {}
}
if matches!(event, PoolEvent::Idle) && reports.is_empty() {
std::thread::sleep(Duration::from_millis(10));
}
}
}
fn main() {
let mut args = std::env::args().skip(1);
match args.next().as_deref() {
match std::env::args().nth(1).as_deref() {
Some("--list-targets") => {
println!("control_board,hash_chip,algorithm");
for target in target_matrix() {
@@ -93,14 +12,8 @@ fn main() {
}
}
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
Some("--mine-simulator") => {
if let Err(error) = sim_mine(args) {
eprintln!("simulator mining failed: {error}");
std::process::exit(1);
}
}
_ => {
eprintln!("usage: alkane-os --list-targets | --version | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
eprintln!("usage: alkane-os --list-targets | --version");
std::process::exit(2);
}
}
-249
View File
@@ -1,249 +0,0 @@
// SPDX-License-Identifier: MIT
//! Bounded, read-only cgminer-style status for a local management client.
use serde_json::{json, Value};
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const MAX_REQUEST_BYTES: usize = 2048;
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
const REQUEST_DEADLINE: Duration = Duration::from_secs(2);
#[derive(Debug)]
pub struct MiningStatus {
started: Instant,
running: AtomicBool,
accepted: AtomicU64,
rejected: AtomicU64,
}
impl Default for MiningStatus {
fn default() -> Self {
Self::new()
}
}
impl MiningStatus {
pub fn new() -> Self {
Self {
started: Instant::now(),
running: AtomicBool::new(false),
accepted: AtomicU64::new(0),
rejected: AtomicU64::new(0),
}
}
pub fn set_running(&self, running: bool) {
self.running.store(running, Ordering::Relaxed);
}
pub fn share_accepted(&self) {
self.accepted.fetch_add(1, Ordering::Relaxed);
}
pub fn share_rejected(&self) {
self.rejected.fetch_add(1, Ordering::Relaxed);
}
fn response(&self, command: &str) -> Value {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let (code, description, payload) = match command {
"summary" => (
"S",
"Summary",
json!({"SUMMARY": [{
"Elapsed": self.started.elapsed().as_secs(),
"Accepted": self.accepted.load(Ordering::Relaxed),
"Rejected": self.rejected.load(Ordering::Relaxed),
"Status": if self.running.load(Ordering::Relaxed) { "Mining" } else { "Stopped" }
}]}),
),
"version" => (
"S",
"Version",
json!({"VERSION": [{
"Miner": concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
"API": "1.0"
}]}),
),
_ => ("E", "Unknown command", json!({})),
};
let mut response = json!({"STATUS": [{
"STATUS": code,
"When": now,
"Code": if code == "S" { 0 } else { 14 },
"Msg": description,
"Description": "alkane-os"
}]});
response
.as_object_mut()
.unwrap()
.extend(payload.as_object().unwrap().clone());
response
}
}
fn request_command(bytes: &[u8]) -> Option<&str> {
let request = std::str::from_utf8(bytes).ok()?.trim();
if request.starts_with('{') {
let value: Value = serde_json::from_str(request).ok()?;
let command = value.get("command")?.as_str()?;
match command {
"summary" => Some("summary"),
"version" => Some("version"),
_ => Some("unknown"),
}
} else {
match request {
"summary" => Some("summary"),
"version" => Some("version"),
_ => Some("unknown"),
}
}
}
fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> {
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
let mut request = Vec::new();
let mut chunk = [0_u8; 256];
let deadline = Instant::now() + REQUEST_DEADLINE;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"management request deadline",
));
}
stream.set_read_timeout(Some(CLIENT_TIMEOUT.min(remaining)))?;
let count = match stream.read(&mut chunk) {
Ok(count) => count,
Err(error) if error.kind() == io::ErrorKind::TimedOut && !request.is_empty() => break,
Err(error) if error.kind() == io::ErrorKind::WouldBlock && !request.is_empty() => break,
Err(error) => return Err(error),
};
if count == 0 {
break;
}
if request.len() + count > MAX_REQUEST_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"management request too large",
));
}
request.extend_from_slice(&chunk[..count]);
if request.contains(&b'\n') || request.contains(&0) {
break;
}
if matches!(request_command(&request), Some("summary" | "version"))
|| serde_json::from_slice::<Value>(&request).is_ok()
{
break;
}
}
let end = request
.iter()
.position(|byte| *byte == 0 || *byte == b'\n')
.unwrap_or(request.len());
let command = request_command(&request[..end]).unwrap_or("unknown");
let mut reply = serde_json::to_vec(&status.response(command)).map_err(io::Error::other)?;
reply.push(0);
stream.write_all(&reply)
}
/// Bind only to loopback. The board management plane can be reached through SSH.
pub fn bind_local(address: SocketAddr) -> io::Result<TcpListener> {
if !address.ip().is_loopback() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"management API requires loopback address",
));
}
TcpListener::bind(address)
}
pub fn serve(listener: TcpListener, status: Arc<MiningStatus>) -> io::Result<()> {
for stream in listener.incoming() {
let stream = stream?;
if let Err(error) = handle(stream, &status) {
eprintln!("management request failed: {error}");
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpStream;
#[test]
fn refuses_nonlocal_bind() {
let address = "0.0.0.0:0".parse().unwrap();
assert_eq!(
bind_local(address).unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
}
#[test]
fn reports_only_observed_share_counts() {
let status = MiningStatus::new();
status.set_running(true);
status.share_accepted();
status.share_rejected();
let reply = status.response("summary");
assert_eq!(reply["SUMMARY"][0]["Accepted"], 1);
assert_eq!(reply["SUMMARY"][0]["Rejected"], 1);
assert_eq!(reply["SUMMARY"][0]["Status"], "Mining");
assert!(reply["SUMMARY"][0].get("MHS av").is_none());
}
#[test]
fn local_socket_uses_nul_terminated_cgminer_envelope() {
let listener = bind_local("127.0.0.1:0".parse().unwrap()).unwrap();
let address = listener.local_addr().unwrap();
let status = Arc::new(MiningStatus::new());
let worker = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
handle(stream, &status).unwrap();
});
let mut client = TcpStream::connect(address).unwrap();
client.write_all(b"{\"command\":\"summary\"}\n").unwrap();
let mut reply = Vec::new();
client.read_to_end(&mut reply).unwrap();
assert_eq!(reply.pop(), Some(0));
let parsed: Value = serde_json::from_slice(&reply).unwrap();
assert_eq!(parsed["STATUS"][0]["STATUS"], "S");
assert_eq!(parsed["SUMMARY"][0]["Status"], "Stopped");
worker.join().unwrap();
}
#[test]
fn fragmented_plain_command_is_not_answered_early() {
let listener = bind_local("127.0.0.1:0".parse().unwrap()).unwrap();
let address = listener.local_addr().unwrap();
let status = Arc::new(MiningStatus::new());
let worker = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
handle(stream, &status).unwrap();
});
let mut client = TcpStream::connect(address).unwrap();
client.write_all(b"sum").unwrap();
std::thread::sleep(Duration::from_millis(10));
client.write_all(b"mary").unwrap();
let mut reply = Vec::new();
client.read_to_end(&mut reply).unwrap();
assert_eq!(reply.pop(), Some(0));
let parsed: Value = serde_json::from_slice(&reply).unwrap();
assert_eq!(parsed["STATUS"][0]["STATUS"], "S");
assert!(parsed.get("SUMMARY").is_some());
worker.join().unwrap();
}
}
+6 -40
View File
@@ -1,19 +1,12 @@
// SPDX-License-Identifier: MIT
//! One-chain BM13xx mining control built on the SDK hardware backend.
//! One-chain BM1366 mining control built on the SDK hardware backend.
//! This module never searches for nonces or chooses board safety thresholds.
use crate::bm1362;
use crate::bm1366::{decode_nonce_report, encode_work, ReportError, REPORT_BYTES};
use crate::pow::verify_sha256_report;
use crate::{power_decision, HardwareBackend, PowerDecision};
use std::fmt;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChipModel {
Bm1362,
Bm1366,
}
#[derive(Debug, Eq, PartialEq)]
pub enum MinerError<E> {
Backend(E),
@@ -35,11 +28,11 @@ impl<E: fmt::Display> fmt::Display for MinerError<E> {
Self::AlreadyRunning => f.write_str("miner is already running"),
Self::NotRunning => f.write_str("miner is not running"),
Self::Faulted => f.write_str("miner shutdown is unconfirmed"),
Self::WorkIdInUse(id) => write!(f, "BM13xx work ID {id} is still in use"),
Self::WorkIdInUse(id) => write!(f, "BM1366 work ID {id} is still in use"),
Self::UnsafeTemperature(value) => write!(f, "unsafe temperature: {value} mC"),
Self::InvalidWork => f.write_str("invalid BM13xx work"),
Self::InvalidReport(error) => write!(f, "invalid BM13xx report: {error:?}"),
Self::StaleReport => f.write_str("stale BM13xx work ID"),
Self::InvalidWork => f.write_str("invalid BM1366 work"),
Self::InvalidReport(error) => write!(f, "invalid BM1366 report: {error:?}"),
Self::StaleReport => f.write_str("stale BM1366 work ID"),
Self::BelowTarget => f.write_str("nonce is below the pool target"),
}
}
@@ -64,7 +57,6 @@ struct Work {
pub struct Bm1366Miner<'a, B: HardwareBackend> {
backend: &'a mut B,
chip: ChipModel,
chain: u8,
sensor: u8,
fan: u8,
@@ -85,34 +77,12 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
fan: u8,
fan_percent: u8,
max_temperature_mc: i32,
) -> Option<Self> {
Self::new_for_chip(
backend,
ChipModel::Bm1366,
chain,
sensor,
fan,
fan_percent,
max_temperature_mc,
)
}
/// Select the captured BM1362 or BM1366 work format explicitly.
pub fn new_for_chip(
backend: &'a mut B,
chip: ChipModel,
chain: u8,
sensor: u8,
fan: u8,
fan_percent: u8,
max_temperature_mc: i32,
) -> Option<Self> {
if fan_percent == 0 || fan_percent > 100 || max_temperature_mc <= 0 {
return None;
}
Some(Self {
backend,
chip,
chain,
sensor,
fan,
@@ -223,11 +193,7 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
return Err(MinerError::Faulted);
}
self.check_temperature()?;
let frame = match self.chip {
ChipModel::Bm1362 => bm1362::encode_work(&header, work_id),
ChipModel::Bm1366 => encode_work(&header, work_id),
}
.ok_or(MinerError::InvalidWork)?;
let frame = encode_work(&header, work_id).ok_or(MinerError::InvalidWork)?;
let slot = usize::from(work_id >> 3);
if self.used_work_ids[slot] {
return Err(MinerError::WorkIdInUse(work_id));
+4 -13
View File
@@ -105,12 +105,8 @@ impl PoolSession {
Ok(false)
}
PoolNotification::SetVersionMask(mask) => {
if self.version_mask == Some(mask) {
return Ok(false);
}
self.version_mask = Some(mask);
self.tracked = std::array::from_fn(|_| None);
Ok(true)
Ok(false)
}
PoolNotification::SetExtranonce(subscription) => {
self.subscription = subscription;
@@ -123,7 +119,7 @@ impl PoolSession {
}
/// Apply a pool control message and invalidate the hardware miner's work
/// when an extranonce or version-mask change makes earlier jobs stale.
/// when an extranonce change makes earlier jobs stale.
pub fn control_with_miner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
@@ -364,15 +360,10 @@ mod tests {
),
Err(SessionError::UnverifiedShare)
);
assert_eq!(
session.control(
b"{\"id\":null,\"method\":\"mining.set_version_mask\",\"params\":[\"00002000\"]}"
),
Ok(true)
);
session.version_mask = VersionMask::new(0x0000_2000);
assert_eq!(
session.submission(share, "miner.worker", 8),
Err(SessionError::StaleShare)
Err(SessionError::Submit(SubmitError::UnrepresentableVersion))
);
}
}
+2 -10
View File
@@ -120,11 +120,7 @@ impl StratumWire {
return Err(WireError::LineTooLong);
}
let line = self.buffered.drain(..=end).collect();
self.partial_started = if self.buffered.is_empty() {
None
} else {
self.partial_started.or_else(|| Some(Instant::now()))
};
self.partial_started = (!self.buffered.is_empty()).then(Instant::now);
return Ok(line);
}
if self.buffered.len() >= MAX_POOL_LINE_BYTES {
@@ -225,11 +221,7 @@ impl StratumWire {
return Err(WireError::LineTooLong);
}
let line = self.buffered.drain(..=end).collect();
self.partial_started = if self.buffered.is_empty() {
None
} else {
self.partial_started.or_else(|| Some(Instant::now()))
};
self.partial_started = (!self.buffered.is_empty()).then(Instant::now);
return Ok(Some(line));
}
if self.buffered.len() >= MAX_POOL_LINE_BYTES {
+6 -197
View File
@@ -1,11 +1,5 @@
use alkane_os::bm1362::{
bt8d_for_baud, chain_inactive, encode_job, encode_work as encode_bm1362_work, read_register,
read_register_all, set_chip_address, write_register, write_register_all, Job, S19J_PRO,
};
use alkane_os::bm1366::{decode_nonce_report, encode_work};
use alkane_os::bm13xx::{crc16, crc5};
use alkane_os::difficulty::PoolDifficulty;
use alkane_os::hal_wire::HalClient;
use alkane_os::miner::Bm1366Miner;
use alkane_os::pow::verify_sha256_report;
use alkane_os::pow::VersionMask;
@@ -13,19 +7,12 @@ use alkane_os::scrypt_pow::verify_scrypt_header;
use alkane_os::stratum_session::PoolSession;
use alkane_os::stratum_submit::{format_submission, Submission};
use alkane_os::stratum_v1::{
parse_boolean_response, parse_configure_result, parse_control_notification, parse_notify,
parse_subscription, Subscription,
};
use alkane_os::stratum_wire::{
authorize_request, configure_request, subscribe_request, StratumWire,
parse_configure_result, parse_control_notification, parse_notify, Subscription,
};
use alkane_os::stratum_wire::authorize_request;
use alkane_os::stratum_work::Sha256Job;
use alkane_os::{power_decision, target_matrix, HardwareBackend};
use std::hint::black_box;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::os::unix::net::UnixStream;
use std::thread;
use std::time::{Duration, Instant};
fn sample(iterations: u64, f: &mut impl FnMut()) -> Duration {
@@ -73,24 +60,6 @@ fn bench_power_policy() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm13xx_crc5() {
let command = [0x53, 0x05, 0, 0];
measure("bm13xx_crc5", 100_000, || {
black_box(crc5(black_box(&command)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm13xx_crc16() {
let job = [0x21_u8; 84];
measure("bm13xx_crc16", 20_000, || {
black_box(crc16(black_box(&job)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_share_verification() {
@@ -125,48 +94,6 @@ fn bench_bm1366_work_encoding() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1362_commands() {
measure("bm1362_commands", 20_000, || {
black_box(chain_inactive());
black_box(set_chip_address(black_box(8)));
black_box(read_register(black_box(0x40), 0x1c));
black_box(read_register_all(0));
black_box(write_register(black_box(0x40), 0x18, 0x7a31));
black_box(write_register_all(0x80, 0));
black_box(bt8d_for_baud(black_box(115_200)));
black_box(S19J_PRO.chip_addresses().last());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1362_job_encoding() {
let job = Job {
work_id: 8,
num_midstates: 1,
start_nonce: 0,
nbits: 0x1a1f_2c34,
ntime: 0x5e9b_3cd4,
merkle_root: [0xa5; 32],
previous_hash: [0x5a; 32],
version: 0x2000_0000,
};
measure("bm1362_job_encoding", 20_000, || {
black_box(encode_job(black_box(&job)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1362_work_encoding() {
let header = [0_u8; 80];
measure("bm1362_work_encoding", 20_000, || {
black_box(encode_bm1362_work(black_box(&header), black_box(8)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1366_report_decode() {
@@ -227,40 +154,6 @@ fn bench_stratum_authorize_format() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_configure_format() {
measure("stratum_configure_format", 20_000, || {
black_box(configure_request(black_box(1)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_subscribe_format() {
measure("stratum_subscribe_format", 20_000, || {
black_box(subscribe_request(black_box(2), "alkane-os/0.1").unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_subscription_parse() {
let line = br#"{"id":1,"result":[[["mining.notify","session"]],"01020304",4],"error":null}"#;
measure("stratum_subscription_parse", 20_000, || {
black_box(parse_subscription(black_box(line), black_box(1)).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_accept_parse() {
let line = br#"{"id":5,"result":true,"error":null}"#;
measure("stratum_accept_parse", 20_000, || {
black_box(parse_boolean_response(black_box(line), black_box(5)).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_notify_parse() {
@@ -341,9 +234,7 @@ fn bench_stratum_job_issue() {
});
}
struct BenchBackend {
report: Option<[u8; 11]>,
}
struct BenchBackend;
impl HardwareBackend for BenchBackend {
type Error = ();
@@ -352,13 +243,8 @@ impl HardwareBackend for BenchBackend {
black_box(frame);
Ok(())
}
fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
if let Some(report) = self.report {
frame[..report.len()].copy_from_slice(&report);
Ok(report.len())
} else {
Ok(0)
}
fn receive_frame(&mut self, _chain: u8, _frame: &mut [u8]) -> Result<usize, Self::Error> {
Ok(0)
}
fn set_chain_reset(&mut self, _chain: u8, _asserted: bool) -> Result<(), Self::Error> {
Ok(())
@@ -380,7 +266,7 @@ fn bench_bm1366_session_cycle() {
let header = [0_u8; 80];
let target = [0xff_u8; 32];
measure("bm1366_session_cycle", 20_000, || {
let mut backend = BenchBackend { report: None };
let mut backend = BenchBackend;
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner
@@ -390,80 +276,3 @@ fn bench_bm1366_session_cycle() {
miner.stop().unwrap();
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1366_captured_report_poll() {
let header = [
0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38,
0x9d, 0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, 0x57, 0xb6,
0xc2, 0x25, 0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, 0x44, 0x43, 0x06,
0x8f, 0xe1, 0x78, 0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, 0x13, 0x3a, 0xdd, 0xb0,
0x4a, 0xab, 0x2b, 0x38, 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02,
0x17, 0x00, 0x00, 0x00, 0x00,
];
let report = [
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
];
let mut target = [0_u8; 32];
target[26..28].fill(0xff);
let mut backend = BenchBackend {
report: Some(report),
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner.submit(header, target, 0x18).unwrap();
measure("bm1366_captured_report_poll", 20_000, || {
let share = miner.poll().unwrap().unwrap();
assert_eq!(black_box(share).nonce, 0xedad_ff38);
});
miner.stop().unwrap();
}
#[test]
#[ignore = "microbenchmark"]
fn bench_hal_socket_exchange() {
let (client, mut server) = UnixStream::pair().unwrap();
let worker = thread::spawn(move || {
let mut header = [0_u8; 16];
let mut payload = [0_u8; 2];
while server.read_exact(&mut header).is_ok() {
assert_eq!(&header[..6], b"ALKH\x01\x04");
assert_eq!(u32::from_le_bytes(header[12..16].try_into().unwrap()), 2);
server.read_exact(&mut payload).unwrap();
assert_eq!(payload, [0, 80]);
header[6..8].copy_from_slice(&1_u16.to_le_bytes());
header[12..16].copy_from_slice(&1_u32.to_le_bytes());
server.write_all(&header).unwrap();
server.write_all(&[0]).unwrap();
}
});
let mut backend = HalClient::from_stream(client).unwrap();
measure("hal_socket_exchange", 100, || {
backend.set_fan_target(black_box(0), black_box(80)).unwrap();
});
drop(backend);
worker.join().unwrap();
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_socket_round_trip() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let worker = thread::spawn(move || {
let (mut server, _) = listener.accept().unwrap();
let mut request = [0_u8; 3];
while server.read_exact(&mut request).is_ok() {
assert_eq!(&request, b"{}\n");
server.write_all(b"{}\n").unwrap();
}
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
measure("stratum_socket_round_trip", 100, || {
wire.send_line(black_box(b"{}\n")).unwrap();
black_box(wire.read_line().unwrap());
});
drop(wire);
worker.join().unwrap();
}
+1 -3
View File
@@ -76,9 +76,7 @@ fn rejects_wrong_response_sequence() {
let mut body = [0_u8; 1];
server.read_exact(&mut body).unwrap();
header[8..12].copy_from_slice(&2_u32.to_le_bytes());
header[6..8].copy_from_slice(&1_u16.to_le_bytes());
header[12..16].copy_from_slice(&1_u32.to_le_bytes());
server.write_all(&header).unwrap();
reply(&mut server, &header, &[0]);
let mut one = [0_u8; 1];
assert_eq!(server.read(&mut one).unwrap(), 0);
});
+3 -6
View File
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MIT
use alkane_os::bm1366::REPORT_BYTES;
use alkane_os::miner::{Bm1366Miner, ChipModel, MinerError};
use alkane_os::miner::{Bm1366Miner, MinerError};
use alkane_os::HardwareBackend;
const HEADER: [u8; 80] = [
@@ -125,7 +125,7 @@ fn captured_nonce_passes_a_started_miner() {
}
#[test]
fn real_bm1362_capture_uses_its_job_format_and_shared_report() {
fn real_bm1362_capture_uses_shared_bm13xx_work_and_report_frames() {
// SDK capture bm1362-real-nonces.txt: one real-silicon pool-accepted share.
// This checks host framing and proof only; board initialization is separate.
let header_hex = concat!(
@@ -146,9 +146,7 @@ fn real_bm1362_capture_uses_its_job_format_and_shared_report() {
..Default::default()
};
{
let mut miner =
Bm1366Miner::new_for_chip(&mut backend, ChipModel::Bm1362, 0, 0, 0, 100, 80_000)
.unwrap();
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner.submit(header, diff_one(), 0x18).unwrap();
let share = miner.poll().unwrap().unwrap();
@@ -158,7 +156,6 @@ fn real_bm1362_capture_uses_its_job_format_and_shared_report() {
miner.stop().unwrap();
}
assert!(!backend.powered);
assert_eq!(&backend.sent[..6], &[0x55, 0xaa, 0x21, 0x56, 0x18, 1]);
assert_eq!(&backend.sent[10..14], &header[72..76]);
}
+5 -23
View File
@@ -52,27 +52,9 @@ fn difficulty_changes_on_next_job_and_old_work_keeps_its_target() {
assert_eq!(second.work_id, 8);
assert_eq!(&second.target_le[26..28], &[0xff, 0x7f]);
assert_ne!(first.header, second.header);
assert_eq!(
pool.control(br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#),
Ok(true)
);
assert_eq!(
pool.submission(
ValidShare {
nonce: 0xedad_ff38,
work_id: first.work_id,
rolled_version: 0x2000_0000,
hash_le: [0; 32],
},
"worker",
10,
),
Err(SessionError::StaleShare)
);
assert_eq!(
pool.control(br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#),
Ok(false)
);
assert!(pool
.control(br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#)
.is_ok());
let clean = pool.issue_notify(notify("third", true).as_bytes()).unwrap();
assert!(clean.clean_jobs);
assert_eq!(clean.work_id, 16);
@@ -219,7 +201,7 @@ impl HardwareBackend for FakeBackend {
}
#[test]
fn pool_job_dispatch_and_version_mask_invalidation_reach_the_miner() {
fn pool_job_dispatch_and_extranonce_invalidation_reach_the_miner() {
let mut backend = FakeBackend {
powered: false,
sent: 0,
@@ -244,7 +226,7 @@ fn pool_job_dispatch_and_version_mask_invalidation_reach_the_miner() {
}
pool.control_with_miner(
&mut miner,
br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#,
br#"{"id":null,"method":"mining.set_extranonce","params":["aabbccdd",4]}"#,
)
.unwrap();
assert_eq!(miner.poll(), Err(MinerError::StaleReport));
-24
View File
@@ -90,30 +90,6 @@ fn trickled_pool_line_hits_the_absolute_deadline() {
server.join().unwrap();
}
#[test]
fn buffered_complete_lines_do_not_extend_a_partial_line_deadline() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.write_all(b"first\nsecond\nunfinished").unwrap();
thread::sleep(Duration::from_secs(3));
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
let first = loop {
if let Some(line) = wire.try_read_line().unwrap() {
break line;
}
};
assert_eq!(first, b"first\n");
thread::sleep(Duration::from_millis(1300));
assert_eq!(wire.try_read_line().unwrap(), Some(b"second\n".to_vec()));
thread::sleep(Duration::from_millis(800));
assert!(matches!(wire.try_read_line(), Err(WireError::Timeout)));
assert!(wire.is_closed());
server.join().unwrap();
}
#[test]
fn idle_timeout_keeps_connection_available_for_later_messages() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();