Compare commits

..
Author SHA1 Message Date
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
43 changed files with 232 additions and 4915 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
+5 -37
View File
@@ -4,15 +4,9 @@ on:
push:
branches: [main]
concurrency:
group: alkane-os-main
cancel-in-progress: false
jobs:
verify-and-release:
runs-on: alkane-ci
env:
CARGO_TARGET_DIR: target
permissions:
contents: write
actions: write
@@ -20,12 +14,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
@@ -34,18 +22,8 @@ jobs:
run: python3 ci/test-last-attempt-badge.py
- name: Benchmark history checks
run: python3 ci/test-bench-history.py
- name: Metric badge checks
run: python3 ci/test-metrics.py
- name: Release evidence gate checks
run: python3 ci/test-conformance.py
- name: Release publication checks
run: python3 ci/test-release.py
- 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
@@ -55,19 +33,13 @@ jobs:
- name: Microbenchmarks
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 }}
cargo test --release --locked -- --ignored --nocapture | tee bench-current.txt
- 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 +57,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
@@ -124,6 +95,3 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 ci/release.py "${{ steps.version.outputs.tag }}" false "dist/alkane-os-${{ steps.version.outputs.version }}-source.tar.gz" dist/alkane-os dist/bench-current.txt
- name: Clean generated build and benchmark work
if: always()
run: python3 ci/cleanup-generated.py
+1 -11
View File
@@ -4,16 +4,9 @@ on:
push:
branches: [next]
concurrency:
group: alkane-os-next
cancel-in-progress: false
jobs:
build:
runs-on: alkane-fast
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
runs-on: alkane-ci
steps:
- uses: actions/checkout@v4
with:
@@ -34,6 +27,3 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 ci/release.py "${{ steps.version.outputs.tag }}" true "dist/alkane-os-${{ steps.version.outputs.version }}-source.tar.gz" dist/alkane-os
- name: Clean generated candidate build
if: always()
run: python3 ci/cleanup-generated.py
-7
View File
@@ -1,7 +0,0 @@
# Alkane OS working rules
- 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.
+61 -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,75 @@
![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 the initial interface and release tooling. It does not mine yet. 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. A test checks a BM1366 nonce
captured from real silicon at difficulty 1588. This verifies reports only;
pool communication and continuous job scheduling are still pending.
The `simulator_replay_probe` example sends that captured job through the Rust
HAL client to the SDK's host-only C/Python replay server, then verifies the
returned nonce. From this repository, run it with
`cargo run --example simulator_replay_probe -- SOCKET_PATH` after starting
the SDK server. It is a simulator check and sends work to the named socket.
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 below the caller's pool target. Sensor or HAL
failure stops the PSU. 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. Pool connections, response tracking, and continuous scheduling
remain to be implemented.
The Stratum V1 decoder now bounds and validates `mining.subscribe` responses
and nine-field Bitcoin `mining.notify` jobs before handing them to the header
builder. It uses the MIT-compatible `serde_json` parser. A live pool client,
target conversion, and job-to-share scheduling are still pending.
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
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
python3 ci/check-conformance.py
```
Use an executable target directory if the source mount is `noexec`.
The last command currently fails because simulator and device evidence are
still pending. It is a release gate, not a unit test.
## 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.
-52
View File
@@ -1,52 +0,0 @@
# Release conformance evidence
`check-conformance.py` is a release gate for all 64 same-vendor cells. It
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
not fill any cell.
Each CI run must put a JSON report at
`ci/evidence/<GITHUB_RUN_ID>/<board>/<chip>.json`. The report binds its
`run_id`, `source_commit`, `os_binary_sha256`, `board`, and `chip` to the
current workflow. It records `stock_firmware_modified: false`,
`simulator_booted_stock: true`, and a `stock_result` of `mines` or `rejects`.
For a rejection, `stock_first_rejection` names the first genuine firmware
gate. Reports for stock mining also reference `stock_pool_accept_capture`.
The report references files under `ci/evidence/` with objects containing
`path` and `sha256`: `sdk_image`, `stock_image`, `simulator_trace`,
`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
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
`notify` message, exact decimal `difficulty`, and a `configure_response`
with an accepted BIP310 mask when version bits were submitted. A later
`version_mask_event` may supply the effective `mining.set_version_mask`.
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.
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.
The fixed digests and artifact paths also appear in `conformance.json` so
source review can track what each cell claims.
The simulator runner must generate these reports by booting pristine stock
firmware and Alkane OS in a machine model, with nonce data replayed from
real-silicon captures. A rejected stock pairing must show its first rejection
in the simulator trace while Alkane OS reaches pool ACCEPT. Bench devices
provide independent observations for model validation, not CI dependencies.
The checker verifies its input artifacts and reported nonce. It cannot prove
that a self-asserted pool response came from a real pool or turn a report into
physical evidence. The capture producer must preserve raw request/response
bytes and independent provenance. Capture provenance and faithful machine
models remain release blockers until the runner and bench validation are built.
+4 -17
View File
@@ -16,7 +16,6 @@ from urllib.error import HTTPError
from urllib.parse import quote
from badge_store import BADGE_BRANCH, publish_file, request_json
from bench_host import identity as benchmark_host
INDEX = "history/index.json"
MAX_INDEX_ENTRIES = 50
@@ -54,15 +53,13 @@ def git_distance(ancestor: str, sha: str) -> int | None:
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
def previous_measurement(index: dict, sha: str, distance=None) -> dict:
distance = distance or git_distance
choices = []
for entry in index.get("entries", []):
ancestor = entry.get("sha")
if ancestor == sha or not isinstance(ancestor, str):
continue
if host is not None and entry.get("metrics", {}).get("bench_host") != host:
continue
gap = distance(ancestor, sha)
if gap is not None and gap > 0:
choices.append((gap, entry))
@@ -92,9 +89,6 @@ def render_html(index: dict) -> str:
cells = [f'<td><a href="https://gitea.bluefla.re/blueflare/alkane-os/commit/{sha}">{sha[:10]}</a></td>',
f'<td>{html.escape(entry["timestamp"])}</td>']
values = valid_benches(entry["metrics"])
host = entry["metrics"].get("bench_host", {})
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
cells.append(f'<td>{html.escape(str(host_label))}</td>')
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
for name in names]
rows.append("<tr>" + "".join(cells) + "</tr>")
@@ -114,13 +108,13 @@ def render_html(index: dict) -> str:
f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained "
"in the private ci-badges branch.</small></p>"
f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>"
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>{headings}</tr></thead><tbody>{''.join(rows)}"
f"<th scope=\"col\">UTC</th>{headings}</tr></thead><tbody>{''.join(rows)}"
"</tbody></table></div></body></html>\n")
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"]
@@ -130,18 +124,11 @@ def main() -> None:
if index.get("schema") != 1 or not isinstance(index.get("entries"), list):
raise ValueError("unsupported benchmark history index")
if args.action == "prepare":
baseline = previous_measurement(index, sha, host=benchmark_host())
baseline = previous_measurement(index, sha)
Path("badges").mkdir(exist_ok=True)
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)
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Identify the CPU class used for comparable CI microbenchmark baselines."""
import os
import platform
from pathlib import Path
def identity() -> dict[str, object]:
model = "unknown"
cpuinfo = Path("/proc/cpuinfo")
if cpuinfo.is_file():
for line in cpuinfo.read_text(errors="replace").splitlines():
if line.startswith(("model name\t", "Hardware\t", "Processor\t")):
model = line.partition(":")[2].strip()[:160]
break
return {"architecture": platform.machine(), "cpu_model": model,
"logical_cpus": os.cpu_count() or 1}
+26 -394
View File
@@ -1,401 +1,33 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Require the binary target matrix and traceable per-cell release evidence."""
"""Fail the final release gate until every target has traceable evidence."""
import argparse
from decimal import Decimal, InvalidOperation
import hashlib
import json
import os
import pathlib
import re
import subprocess
import sys
manifest = json.loads(pathlib.Path("ci/conformance.json").read_text())
rows = manifest["targets"]
expected = {(board, chip) for board in manifest["boards"] for chip in manifest["chips"]
if manifest["vendors"][board] == manifest["vendors"][chip]}
actual = {(row["board"], row["chip"]) for row in rows}
if actual != expected or len(rows) != len(expected):
sys.exit(f"matrix mismatch: {len(actual)} present, {len(expected)} expected")
REQUIRED_BOARDS = {
"am335x-bb": "bitmain",
"zynq-7010": "bitmain",
"cv1835": "bitmain",
"a113d": "bitmain",
"allwinner-h3": "whatsminer",
"allwinner-h6": "whatsminer",
"allwinner-h616": "whatsminer",
}
REQUIRED_CHIPS = {
**{chip: "bitmain" for chip in (
"BM1384", "BM1387", "BM1360", "BM1362", "BM1366", "BM1368",
"BM1370", "BM1396", "BM1397", "BM1398", "BM1489", "BM1491", "BM1746",
)},
**{chip: "whatsminer" for chip in (
"KF1950", "ID-1968", "ID-1980", "ID-1990",
)},
}
REQUIRED_ALGORITHMS = {
**{chip: "Sha256" for chip in REQUIRED_CHIPS if chip not in
("BM1489", "BM1491", "BM1746")},
"BM1489": "Scrypt", "BM1491": "Scrypt", "BM1746": "Equihash",
}
DIGEST = re.compile(r"[0-9a-f]{64}\Z")
COMMIT = re.compile(r"[0-9a-f]{40}\Z")
DIFF_ONE_TARGET = 0xffff << (8 * (0x1d - 3))
MAX_REPORT_BYTES = 1_048_576
def sha256_file(path: pathlib.Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1_048_576), b""):
digest.update(chunk)
return digest.hexdigest()
def load_report(path: pathlib.Path) -> dict:
if path.stat().st_size > MAX_REPORT_BYTES:
raise ValueError("evidence report exceeds 1 MiB")
value = json.loads(path.read_text())
if not isinstance(value, dict):
raise ValueError("evidence report is not an object")
return value
def artifact(root: pathlib.Path, value: object) -> pathlib.Path:
if not isinstance(value, dict) or not isinstance(value.get("path"), str):
raise ValueError("artifact reference is missing")
digest = value.get("sha256")
if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
raise ValueError("artifact digest is invalid")
path = (root / value["path"]).resolve()
if not path.is_relative_to(root.resolve()) or not path.is_file():
raise ValueError("artifact is missing or outside evidence directory")
if sha256_file(path) != digest:
raise ValueError("artifact digest mismatch")
return path
def hex_field(value: object, size: int | None = None) -> bytes:
if (not isinstance(value, str) or len(value) & 1
or len(value) > 131_072 or not re.fullmatch(r"[0-9a-fA-F]*", value)
or (size is not None and len(value) != size * 2)):
raise ValueError("invalid Stratum hex field")
return bytes.fromhex(value)
def u32_hex(value: object) -> int:
return int.from_bytes(hex_field(value, 4), "big")
def reconstructed_header(capture: dict, params: list[str]) -> tuple[bytes, int]:
subscription = capture.get("subscription")
notify = capture.get("notify")
if not isinstance(subscription, dict) or not isinstance(notify, dict):
raise ValueError("subscription and notify are required to bind the share")
extra1 = hex_field(subscription.get("extranonce1"))
extra_size = subscription.get("extranonce2_size")
if (len(extra1) > 32 or type(extra_size) is not int
or not 0 <= extra_size <= 32):
raise ValueError("invalid subscription extranonce")
extra2 = hex_field(params[2], extra_size)
job = notify.get("params")
if (notify.get("method") != "mining.notify" or not isinstance(job, list)
or len(job) != 9 or job[0] != params[1]
or not isinstance(job[4], list) or len(job[4]) > 64
or type(job[8]) is not bool):
raise ValueError("submission is not bound to a matching notify")
prevhash = hex_field(job[1], 32)
coinbase = hex_field(job[2]) + extra1 + extra2 + hex_field(job[3])
if len(coinbase) > 65_536:
raise ValueError("coinbase exceeds supported size")
root = hashlib.sha256(hashlib.sha256(coinbase).digest()).digest()
for branch in job[4]:
pair = root + hex_field(branch, 32)
root = hashlib.sha256(hashlib.sha256(pair).digest()).digest()
base_version = u32_hex(job[5])
nbits = u32_hex(job[6])
u32_hex(job[7])
submitted_ntime = u32_hex(params[3])
submitted_nonce = u32_hex(params[4])
if len(params) == 6:
configure = capture.get("configure_response")
result = configure.get("result") if isinstance(configure, dict) else None
if not isinstance(result, dict) or result.get("version-rolling") is not True:
raise ValueError("version rolling was not negotiated")
mask_text = result.get("version-rolling.mask")
mask_event = capture.get("version_mask_event")
if mask_event is not None:
fields = mask_event.get("params") if isinstance(mask_event, dict) else None
if (not isinstance(mask_event, dict)
or mask_event.get("method") != "mining.set_version_mask"
or not isinstance(fields, list) or len(fields) != 1):
raise ValueError("invalid effective version mask event")
mask_text = fields[0]
mask = u32_hex(mask_text)
bits = u32_hex(params[5])
if bits & ~mask:
raise ValueError("submitted version bits exceed negotiated mask")
version = (base_version & ~mask) | bits
else:
if capture.get("configure_response") is not None or capture.get("version_mask_event") is not None:
raise ValueError("negotiated version mask requires submission bits")
version = base_version
header = bytearray()
header.extend(version.to_bytes(4, "little"))
for offset in range(0, 32, 4):
header.extend(prevhash[offset:offset + 4][::-1])
header.extend(root)
header.extend(submitted_ntime.to_bytes(4, "little"))
header.extend(nbits.to_bytes(4, "little"))
header.extend(submitted_nonce.to_bytes(4, "little"))
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"):
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")
header_hex = capture.get("header80")
target_hex = capture.get("pool_target_le")
nonce = capture.get("nonce")
if (not isinstance(header_hex, str) or len(header_hex) != 160
or not isinstance(target_hex, str) or not DIGEST.fullmatch(target_hex)
or type(nonce) is not int or not 0 <= nonce <= 0xffffffff):
raise ValueError("invalid accepted share work")
try:
header = bytearray.fromhex(header_hex)
except ValueError as error:
raise ValueError("invalid accepted share header") from error
if int.from_bytes(header[76:80], "little") != nonce:
raise ValueError("nonce differs from submitted header")
submission = capture.get("submission")
response = capture.get("pool_response")
params = submission.get("params") if isinstance(submission, dict) else None
if (not isinstance(params, list) or len(params) not in (5, 6)
or not all(isinstance(value, str) for value in params)
or not params[0] or not params[1]
or params[3].lower() != f"{int.from_bytes(header[68:72], 'little'):08x}"
or params[4].lower() != f"{nonce:08x}"
or (len(params) == 6 and not re.fullmatch(r"[0-9a-f]{8}", params[5].lower()))
or not isinstance(response, dict)
or submission.get("method") != "mining.submit"
or type(submission.get("id")) is not int
or response.get("id") != submission["id"]
or response.get("result") is not True
or response.get("error") is not None):
raise ValueError("no matching pool ACCEPT for submitted nonce")
target = int.from_bytes(bytes.fromhex(target_hex), "little")
if not 0 < target <= DIFF_ONE_TARGET:
raise ValueError("pool target is below difficulty one")
difficulty_text = capture.get("difficulty")
if not isinstance(difficulty_text, str) or len(difficulty_text) > 128:
raise ValueError("effective pool difficulty is missing")
try:
difficulty = Decimal(difficulty_text)
except InvalidOperation as error:
raise ValueError("invalid pool difficulty") from error
if not difficulty.is_finite() or difficulty < 1:
raise ValueError("pool difficulty is below one")
if abs(difficulty.as_tuple().exponent) > 64:
raise ValueError("pool difficulty exceeds supported range")
numerator, denominator = difficulty.as_integer_ratio()
expected_target = DIFF_ONE_TARGET * denominator // numerator
if target != expected_target:
raise ValueError("pool target differs from effective difficulty")
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)
if int.from_bytes(hash_bytes, "little") > target:
raise ValueError("captured nonce misses the pool target")
def verify_cell(row: dict, root: pathlib.Path, run_id: str,
source_commit: str, binary_digest: str,
algorithm: str) -> None:
board, chip = row["board"], row["chip"]
report_path = (root / run_id / board / f"{chip}.json").resolve()
if not report_path.is_relative_to(root.resolve()):
raise ValueError("evidence report is outside evidence directory")
report = load_report(report_path)
identity = {"schema": 1, "run_id": run_id, "source_commit": source_commit,
"os_binary_sha256": binary_digest, "board": board, "chip": chip,
"stock_firmware_modified": False, "algorithm": algorithm}
if any(report.get(key) != value for key, value in identity.items()):
raise ValueError("evidence belongs to a different run, source, binary, or cell")
if report.get("stock_result") != row.get("stock_result"):
raise ValueError("stock result differs from manifest")
if report.get("stock_first_rejection") != row.get("stock_first_rejection"):
raise ValueError("stock rejection differs from manifest")
if report["stock_result"] == "rejects" and not report.get("stock_first_rejection"):
raise ValueError("stock rejection gate is missing")
if report.get("simulator_booted_stock") is not True:
raise ValueError("unmodified stock boot is unverified")
paths = {}
for field, digest_field in (("sdk_image", "sdk_image_sha256"),
("stock_image", "stock_image_sha256"),
("simulator_trace", "simulator_trace_sha256")):
paths[field] = artifact(root, report.get(field))
if report[field]["sha256"] != row.get(digest_field):
raise ValueError(f"{field} digest differs from manifest")
artifact(root, report.get("simulator_model"))
model_digest = report["simulator_model"]["sha256"]
for field in ("control_capture", "chip_capture"):
artifact(root, report.get(field))
trace = load_report(paths["simulator_trace"])
trace_identity = {"run_id": run_id, "source_commit": source_commit,
"board": board, "chip": chip,
"sdk_image_sha256": row["sdk_image_sha256"],
"stock_image_sha256": row["stock_image_sha256"],
"stock_firmware_modified": False,
"stock_result": row["stock_result"],
"algorithm": algorithm,
"simulator_model_sha256": model_digest}
if any(trace.get(key) != value for key, value in trace_identity.items()):
raise ValueError("simulator trace does not bind stock image and current run")
if report["stock_result"] == "rejects":
if trace.get("first_rejection") != row["stock_first_rejection"]:
raise ValueError("stock rejection gate is absent from simulator trace")
else:
stock_capture = load_report(artifact(root, report.get("stock_pool_accept_capture")))
if trace.get("stock_pool_accept_capture_sha256") != report["stock_pool_accept_capture"]["sha256"]:
raise ValueError("stock pool acceptance is not linked to simulator trace")
if (stock_capture.get("board") != board or stock_capture.get("chip") != chip
or stock_capture.get("firmware") != "stock"):
raise ValueError("stock pool acceptance belongs to another firmware or cell")
verify_accept(stock_capture, algorithm)
capture = load_report(artifact(root, report.get("alkane_share_accept_capture")))
if report["alkane_share_accept_capture"]["path"] != row.get("alkane_share_accept_capture"):
raise ValueError("accepted share artifact differs from manifest")
if trace.get("alkane_share_accept_capture_sha256") != report["alkane_share_accept_capture"]["sha256"]:
raise ValueError("Alkane pool acceptance is not linked to simulator trace")
if (capture.get("board") != board or capture.get("chip") != chip
or capture.get("firmware") != "alkane"):
raise ValueError("accepted share belongs to another cell")
verify_accept(capture, algorithm)
bench = load_report(artifact(root, report.get("bench_validation")))
if report["bench_validation"]["path"] != row.get("bench_validation"):
raise ValueError("bench artifact differs from manifest")
if (bench.get("board") != board or bench.get("chip") != chip
or bench.get("validated") is not True
or bench.get("simulator_model_sha256") != model_digest
or any(bench.get(f"{field}_sha256") != report[field]["sha256"]
for field in ("control_capture", "chip_capture"))
or any(not isinstance(bench.get(f"{name}_device_id"), str)
or not bench[f"{name}_device_id"]
for name in ("control", "chip"))):
raise ValueError("bench validation is missing or belongs to another cell")
def binary_targets(path: pathlib.Path) -> dict[tuple[str, str], str]:
output = subprocess.run(
[str(path), "--list-targets"],
check=True, capture_output=True, text=True, timeout=15,
).stdout.splitlines()
if not output or output[0] != "control_board,hash_chip,algorithm":
raise ValueError("Alkane OS binary has no target matrix header")
targets = {}
for line in output[1:]:
parts = line.split(",")
if len(parts) != 3 or not all(parts):
raise ValueError(f"invalid binary target row: {line!r}")
cell = (parts[0], parts[1])
if cell in targets:
raise ValueError("duplicate binary target")
targets[cell] = parts[2]
return targets
def validate(manifest: dict, built_targets: dict[tuple[str, str], str],
evidence_root: pathlib.Path = pathlib.Path("ci/evidence"),
run_id: str = "", source_commit: str = "",
binary_digest: str = "") -> list[str]:
errors = []
if manifest.get("schema") != 1:
errors.append("unsupported conformance manifest schema")
boards = set(manifest["boards"])
chips = set(manifest["chips"])
vendors = manifest["vendors"]
if len(boards) != len(manifest["boards"]) or len(chips) != len(manifest["chips"]):
errors.append("duplicate board or chip in manifest")
for name, vendor in {**REQUIRED_BOARDS, **REQUIRED_CHIPS}.items():
if name not in boards | chips or vendors.get(name) != vendor:
errors.append(f"required target identity changed: {name}")
if set(vendors) != boards | chips:
errors.append("vendor map differs from board and chip lists")
expected = {(board, chip) for board in boards for chip in chips
if vendors.get(board) == vendors.get(chip)}
rows = manifest["targets"]
actual = {(row["board"], row["chip"]) for row in rows}
if len(expected) < 64 or actual != expected or len(rows) != len(expected):
errors.append(f"manifest matrix mismatch: {len(actual)} present, {len(expected)} expected")
if set(built_targets) != expected:
errors.append(f"binary matrix mismatch: {len(built_targets)} built, {len(expected)} expected")
for (board, chip), algorithm in built_targets.items():
if chip in REQUIRED_ALGORITHMS and algorithm != REQUIRED_ALGORITHMS[chip]:
errors.append(f"binary algorithm mismatch: {board} x {chip}")
if (not run_id.isdecimal() or not COMMIT.fullmatch(source_commit)
or not DIGEST.fullmatch(binary_digest)):
errors.append("current run, source commit, or binary digest is unbound")
required = ("sdk_image_sha256", "stock_image_sha256", "stock_result",
"alkane_share_accept_capture", "simulator_trace_sha256",
"bench_validation")
for row in rows:
cell = f"{row['board']} x {row['chip']}"
missing = [field for field in required if not row.get(field)]
if row.get("stock_result") not in (None, "mines", "rejects"):
missing.append("stock_result invalid")
if row.get("stock_result") == "rejects" and not row.get("stock_first_rejection"):
missing.append("stock_first_rejection")
for field in ("sdk_image_sha256", "stock_image_sha256", "simulator_trace_sha256"):
value = row.get(field)
if value and (not isinstance(value, str) or not DIGEST.fullmatch(value)):
missing.append(f"{field} invalid")
if missing:
errors.append(f"{cell}: {', '.join(missing)}")
elif run_id.isdecimal() and COMMIT.fullmatch(source_commit) and DIGEST.fullmatch(binary_digest):
try:
verify_cell(row, evidence_root, run_id, source_commit, binary_digest,
built_targets.get((row["board"], row["chip"]), "unknown"))
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as error:
errors.append(f"{cell}: evidence invalid: {error}")
return errors
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=pathlib.Path,
default=pathlib.Path("ci/conformance.json"))
parser.add_argument("--binary", type=pathlib.Path,
default=pathlib.Path(os.environ.get("CARGO_TARGET_DIR", "target"))
/ "release/alkane-os")
parser.add_argument("--evidence-dir", type=pathlib.Path,
default=pathlib.Path("ci/evidence"))
parser.add_argument("--run-id", default=os.environ.get("GITHUB_RUN_ID", ""))
args = parser.parse_args()
manifest = json.loads(args.manifest.read_text())
try:
built_targets = binary_targets(args.binary.resolve())
except (OSError, subprocess.SubprocessError, ValueError) as error:
sys.exit(f"cannot verify Alkane OS binary target matrix: {error}")
source_commit = subprocess.run(["git", "rev-parse", "HEAD"], check=True,
capture_output=True, text=True).stdout.strip()
errors = validate(manifest, built_targets, args.evidence_dir, args.run_id,
source_commit, sha256_file(args.binary.resolve()))
if errors:
print(f"Conformance pending: {len(errors)} issues across {len(manifest['targets'])} targets")
for error in errors[:8]:
print(f" {error}")
sys.exit(1)
print(f"Conformance complete: {len(manifest['targets'])} targets")
if __name__ == "__main__":
main()
required = ("sdk_image_sha256", "stock_image_sha256", "stock_result",
"alkane_share_accept_capture", "simulator_trace_sha256",
"bench_validation")
incomplete = []
for row in rows:
missing = [field for field in required if not row.get(field)]
if row.get("stock_result") not in (None, "mines", "rejects"):
missing.append("stock_result invalid")
if row.get("stock_result") == "rejects" and not row.get("stock_first_rejection"):
missing.append("stock_first_rejection")
if missing:
incomplete.append((row["board"], row["chip"], missing))
if incomplete:
print(f"Conformance pending: {len(incomplete)}/{len(rows)} targets")
for board, chip, missing in incomplete[:8]:
print(f" {board} x {chip}: {', '.join(missing)}")
sys.exit(1)
print(f"Conformance complete: {len(rows)} targets")
-42
View File
@@ -1,42 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Remove generated Alkane OS CI files after tests and release upload."""
import os
from pathlib import Path
import shutil
import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "coverage", "dist", "bench-site")
FILES = ("tests-current.txt", "bench-current.txt", "quality-current.json")
def cleanup() -> None:
if not os.environ.get("GITHUB_RUN_ID"):
raise ValueError("cleanup is restricted to CI runs")
for name in DIRECTORIES:
path = ROOT / name
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
raise ValueError(f"unsafe generated directory: {path}")
if path.is_dir():
shutil.rmtree(path)
print(f"Removed generated directory: {name}")
elif path.exists():
raise ValueError(f"expected a generated directory: {path}")
for name in FILES:
path = ROOT / name
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
raise ValueError(f"unsafe generated file: {path}")
if path.is_file():
path.unlink()
print(f"Removed generated file: {name}")
if __name__ == "__main__":
try:
cleanup()
except (OSError, ValueError) as error:
print(f"ERROR: Alkane OS cleanup: {error}", file=sys.stderr)
raise SystemExit(1)
+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__":
+9 -59
View File
@@ -4,25 +4,9 @@
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):
@@ -31,40 +15,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):
@@ -99,7 +51,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 +58,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"))
@@ -119,11 +74,8 @@ def main():
metrics = {"tests": tests, "line_coverage_pct": round(line_coverage, 1),
"bench_coverage_pct": round(bench_coverage, 1),
"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": "A", "license": "MIT"}
pathlib.Path("badges").mkdir(exist_ok=True)
pathlib.Path("badges/metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")
badges = {
@@ -133,9 +85,7 @@ def main():
"bench": ("bench", "baseline set" if delta is None else f"{delta:+.1f}% vs prev", "#007ec6"),
"loc": ("lines of code", compact(loc), "#007ec6"),
"dependencies": ("dependencies", str(dependencies), "#007ec6"),
"quality": ("code quality", metrics["code_quality"],
{"A": "#4c1", "B": "#97ca00", "C": "#dfb317",
"D": "#fe7d37", "F": "#e05d44"}[metrics["code_quality"]]),
"quality": ("code quality", "A", "#4c1"),
"license": ("license", "MIT", "#007ec6"),
}
for name, (label, value, color) in badges.items():
-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()
+33 -138
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish a complete Gitea release after all assets are attached to a draft."""
"""Create one Gitea release and attach files using the runner's scoped token."""
import json
import hashlib
import os
import pathlib
import sys
@@ -12,148 +10,45 @@ import urllib.parse
import urllib.request
def request(url, method="GET", payload=None, content_type=None):
headers = {"Authorization": "token " + os.environ["GITEA_TOKEN"]}
if content_type:
headers["Content-Type"] = content_type
operation = urllib.request.Request(url, data=payload, headers=headers, method=method)
with urllib.request.urlopen(operation, timeout=60) as response:
body = response.read()
return json.loads(body) if body else None
def json_request(url, method, value):
return request(url, method, json.dumps(value).encode(), "application/json")
def files_to_publish(names):
paths = [pathlib.Path(name) for name in names]
if not paths or len({path.name for path in paths}) != len(paths):
raise ValueError("release assets must have distinct basenames")
for path in paths:
if not path.is_file() or path.stat().st_size == 0:
raise ValueError(f"release asset missing or empty: {path}")
return paths
def sha256_file(path):
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1_048_576), b""):
digest.update(chunk)
return digest.hexdigest()
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, fp, code, message, headers, new_url):
return None
def asset_digest(asset, api):
url = asset["browser_download_url"]
remote = urllib.parse.urlsplit(url)
expected = urllib.parse.urlsplit(api)
if remote.scheme != "https" or remote.netloc != expected.netloc:
raise ValueError("asset download is outside the trusted Gitea host")
operation = urllib.request.Request(
url, headers={"Authorization": "token " + os.environ["GITEA_TOKEN"]})
digest = hashlib.sha256()
with urllib.request.build_opener(NoRedirect).open(operation, timeout=60) as response:
for chunk in iter(lambda: response.read(1_048_576), b""):
digest.update(chunk)
return digest.hexdigest()
def get_release(url):
try:
return request(url)
except urllib.error.HTTPError as error:
if error.code == 404:
return None
raise
def check_tag_commit(api, repo, tag, sha):
url = f"{api}/repos/{repo}/tags/{urllib.parse.quote(tag, safe='')}"
try:
remote_tag = request(url)
except urllib.error.HTTPError as error:
if error.code == 404:
return False
raise
if not isinstance(remote_tag, dict) or remote_tag.get("commit", {}).get("sha") != sha:
raise ValueError("Git tag points to a different or unknown commit")
return True
def publish(tag, prerelease, paths, api, repo, sha):
base = f"{api}/repos/{repo}/releases"
tag_url = f"{base}/tags/{urllib.parse.quote(tag, safe='')}"
metadata = {
"tag_name": tag,
"target_commitish": sha,
"name": tag,
"body": f"Automated Alkane OS build from {sha}. Conformance results are in the repository.",
"prerelease": prerelease,
def request(url, payload, content_type):
headers = {
"Authorization": "token " + os.environ["GITEA_TOKEN"],
"Content-Type": content_type,
}
check_tag_commit(api, repo, tag, sha)
release = get_release(tag_url)
if release is None:
release = json_request(base, "POST", {**metadata, "draft": True})
elif release.get("target_commitish") != sha:
raise ValueError("release tag already belongs to another source revision")
release_url = f"{base}/{release['id']}"
assets_url = f"{release_url}/assets"
existing = request(assets_url)
wanted = {path.name: path.stat().st_size for path in paths}
digests = {path.name: sha256_file(path) for path in paths}
present = {asset["name"]: asset for asset in existing}
if not release.get("draft") and all(
(asset := present.get(name)) is not None and asset["size"] == size
and asset_digest(asset, api) == digests[name]
for name, size in wanted.items()
):
if not check_tag_commit(api, repo, tag, sha):
raise ValueError("published release has no Git tag")
print(f"Release {tag} is already complete")
return
if not release.get("draft"):
release = json_request(release_url, "PATCH", {**metadata, "draft": True})
if not release.get("draft"):
raise ValueError("incomplete release could not be returned to draft")
for asset in existing:
if asset["name"] in wanted:
request(f"{assets_url}/{asset['id']}", "DELETE")
for path in paths:
query = urllib.parse.urlencode({"name": path.name})
request(f"{assets_url}?{query}", "POST", path.read_bytes(),
"application/octet-stream")
uploaded = request(assets_url)
actual = {asset["name"]: asset for asset in uploaded}
if any((asset := actual.get(name)) is None or asset["size"] != size
or asset_digest(asset, api) != digests[name]
for name, size in wanted.items()):
raise ValueError("draft release asset verification failed")
check_tag_commit(api, repo, tag, sha)
release = json_request(release_url, "PATCH", {**metadata, "draft": False})
if release.get("draft"):
raise ValueError("release remained a draft after publishing")
if not check_tag_commit(api, repo, tag, sha):
raise ValueError("published release did not create the expected Git tag")
print(f"Published {tag} with {len(paths)} assets")
req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=60) as response:
return json.load(response)
def main():
if len(sys.argv) < 4:
sys.exit("usage: release.py TAG PRERELEASE FILE [FILE ...]")
tag, prerelease, *names = sys.argv[1:]
tag, prerelease, *files = sys.argv[1:]
api = os.environ.get("GITHUB_API_URL", "https://gitea.bluefla.re/api/v1").rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
sha = os.environ["GITHUB_SHA"]
body = f"Automated Alkane OS build from {sha}. Conformance results are in the repository."
metadata = {
"tag_name": tag,
"target_commitish": sha,
"name": tag,
"body": body,
"prerelease": prerelease.lower() == "true",
}
try:
paths = files_to_publish(names)
api = os.environ.get("GITHUB_API_URL", "https://gitea.bluefla.re/api/v1").rstrip("/")
publish(tag, prerelease.lower() == "true", paths, api,
os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_SHA"])
except (ValueError, OSError, urllib.error.HTTPError) as error:
sys.exit(f"release publication failed: {error}")
release = request(f"{api}/repos/{repo}/releases", json.dumps(metadata).encode(), "application/json")
except urllib.error.HTTPError as exc:
sys.exit(f"release creation failed: HTTP {exc.code}")
release_id = release["id"]
for name in files:
path = pathlib.Path(name)
query = urllib.parse.urlencode({"name": path.name})
try:
request(f"{api}/repos/{repo}/releases/{release_id}/assets?{query}",
path.read_bytes(), "application/octet-stream")
except urllib.error.HTTPError as exc:
sys.exit(f"asset upload failed for {path.name}: HTTP {exc.code}")
print(f"Created {tag} with {len(files)} assets")
if __name__ == "__main__":
+1 -13
View File
@@ -33,21 +33,9 @@ class HistoryTests(unittest.TestCase):
with self.assertRaises(ValueError):
updated_index({}, "a" * 40, {"bench_ns_per_op": {"hash": -1}}, "now")
def test_baseline_must_match_cpu_class(self):
first = "a" * 40
host = {"architecture": "x86_64", "cpu_model": "A", "logical_cpus": 8}
other = {"architecture": "x86_64", "cpu_model": "B", "logical_cpus": 8}
index = {"entries": [{"sha": first, "metrics": {
"bench_ns_per_op": {"hash": 10.0}, "bench_host": host}}]}
distance = lambda _ancestor, _sha: 1
self.assertEqual(previous_measurement(index, "b" * 40, distance, host),
{"hash": 10.0})
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
def test_site_escapes_history_content(self):
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
"metrics": {"bench_ns_per_op": {"hash": 10.0},
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
"metrics": {"bench_ns_per_op": {"hash": 10.0}}}
page = render_html({"entries": [entry]})
self.assertIn("&lt;script&gt;", page)
self.assertNotIn("<script>", page)
-50
View File
@@ -1,50 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Verify cleanup removes only generated files inside the CI checkout."""
import importlib.util
import os
from pathlib import Path
import tempfile
from unittest.mock import patch
SPEC = importlib.util.spec_from_file_location(
"cleanup_generated", Path(__file__).resolve().with_name("cleanup-generated.py"))
CLEANUP = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(CLEANUP)
def main() -> None:
with tempfile.TemporaryDirectory(prefix="alkane-os-cleanup-") as temporary:
root = Path(temporary)
outside = root.parent / (root.name + "-outside")
outside.mkdir()
(outside / "keep").write_bytes(b"safe")
previous = CLEANUP.ROOT
CLEANUP.ROOT = root
try:
with patch.dict(os.environ, {"GITHUB_RUN_ID": "123"}):
(root / "target").mkdir()
(root / "target/build").write_bytes(b"generated")
(root / "bench-current.txt").write_bytes(b"generated")
CLEANUP.cleanup()
assert not (root / "target").exists()
assert not (root / "bench-current.txt").exists()
(root / "target").symlink_to(outside, target_is_directory=True)
try:
CLEANUP.cleanup()
except ValueError:
pass
else:
raise AssertionError("cleanup followed a symlink")
assert (outside / "keep").read_bytes() == b"safe"
finally:
CLEANUP.ROOT = previous
(outside / "keep").unlink()
outside.rmdir()
print("Alkane OS CI cleanup containment: PASS")
if __name__ == "__main__":
main()
-115
View File
@@ -1,115 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Regression checks for the fail-closed release evidence gate."""
import copy
import importlib.util
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
SCRIPT = Path(__file__).with_name("check-conformance.py")
spec = importlib.util.spec_from_file_location("check_conformance", SCRIPT)
gate = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gate)
MANIFEST = json.loads(Path(__file__).with_name("conformance.json").read_text())
TARGETS = {(row["board"], row["chip"]): gate.REQUIRED_ALGORITHMS[row["chip"]]
for row in MANIFEST["targets"]}
class ConformanceGateTest(unittest.TestCase):
def test_placeholder_matrix_cannot_pass_without_current_run_artifacts(self):
manifest = copy.deepcopy(MANIFEST)
for row in manifest["targets"]:
row.update(sdk_image_sha256="0" * 64,
stock_image_sha256="0" * 64,
simulator_trace_sha256="0" * 64,
stock_result="mines",
alkane_share_accept_capture="does-not-exist.json",
bench_validation="not-run")
with TemporaryDirectory() as directory:
errors = gate.validate(manifest, TARGETS, Path(directory), "123",
"a" * 40, "b" * 64)
self.assertEqual(len(errors), 64)
self.assertTrue(all("evidence invalid" in error for error in errors))
def test_stale_source_identity_is_rejected(self):
row = copy.deepcopy(MANIFEST["targets"][0])
row["stock_result"] = "mines"
with TemporaryDirectory() as directory:
root = Path(directory)
report = root / "123" / row["board"] / f"{row['chip']}.json"
report.parent.mkdir(parents=True)
report.write_text(json.dumps({"schema": 1, "run_id": "123",
"source_commit": "f" * 40,
"os_binary_sha256": "b" * 64,
"board": row["board"], "chip": row["chip"],
"stock_firmware_modified": False}))
with self.assertRaisesRegex(ValueError, "different run, source"):
gate.verify_cell(row, root, "123", "a" * 40, "b" * 64,
TARGETS[(row["board"], row["chip"])])
def test_share_accept_requires_real_difficulty_one_work(self):
capture = {"nonce_source": "real_silicon_capture",
"header80": "00" * 80,
"pool_target_le": "ff" * 32, "nonce": 0,
"submission": {"id": 4, "method": "mining.submit",
"params": ["worker", "job", "", "00000000", "00000000"]},
"pool_response": {"id": 4, "result": True, "error": None}}
with self.assertRaisesRegex(ValueError, "below difficulty one"):
gate.verify_accept(capture, "Sha256")
capture["submission"]["params"][4] = "00000001"
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):
with self.assertRaisesRegex(ValueError, "Equihash share verifier"):
gate.verify_accept({}, "Equihash")
def test_submitted_header_reconstruction_rejects_version_and_extranonce_changes(self):
capture = {
"subscription": {"extranonce1": "aa", "extranonce2_size": 1},
"notify": {"method": "mining.notify", "params": [
"job", "11" * 32, "01", "02", [],
"20000000", "1d00ffff", "12345678", True]},
"configure_response": {"result": {
"version-rolling": True, "version-rolling.mask": "1fffe000"}},
}
params = ["worker", "job", "bb", "12345678", "00000001", "00002000"]
header, _ = gate.reconstructed_header(capture, params)
self.assertEqual(len(header), 80)
self.assertEqual(header[:4], (0x20002000).to_bytes(4, "little"))
self.assertEqual(header[4:8], b"\x11" * 4)
changed = params.copy()
changed[5] = "ffffffff"
with self.assertRaisesRegex(ValueError, "version bits"):
gate.reconstructed_header(capture, changed)
changed[5] = params[5]
changed[2] = "f"
with self.assertRaisesRegex(ValueError, "Stratum hex"):
gate.reconstructed_header(capture, changed)
changed[2] = "cc"
rebuilt, _ = gate.reconstructed_header(capture, changed)
self.assertNotEqual(rebuilt, header)
if __name__ == "__main__":
unittest.main()
-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,
-51
View File
@@ -1,51 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""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
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_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")
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()
-133
View File
@@ -1,133 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check draft release recovery without making network requests."""
import importlib.util
import hashlib
import urllib.error
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
SCRIPT = Path(__file__).with_name("release.py")
spec = importlib.util.spec_from_file_location("release", SCRIPT)
release = importlib.util.module_from_spec(spec)
spec.loader.exec_module(release)
class FakeGitea:
def __init__(self):
self.release = None
self.assets = []
self.blobs = {}
self.fail_second_upload = True
self.uploads = 0
self.tag_sha = None
def request(self, url, method="GET", payload=None, content_type=None):
if "/tags/" in url and "/releases/" not in url:
if self.tag_sha is None:
raise urllib.error.HTTPError(url, 404, "missing", {}, None)
return {"commit": {"sha": self.tag_sha}}
if "/assets" in url:
if method == "GET":
return list(self.assets)
if method == "DELETE":
asset_id = int(url.rsplit("/", 1)[1])
self.assets = [item for item in self.assets if item["id"] != asset_id]
self.blobs.pop(asset_id, None)
return None
self.uploads += 1
if self.fail_second_upload and self.uploads == 2:
raise OSError("injected upload failure")
name = release.urllib.parse.parse_qs(url.split("?", 1)[1])["name"][0]
item = {"id": self.uploads, "name": name, "size": len(payload),
"browser_download_url": f"https://api/download/{self.uploads}"}
self.assets.append(item)
self.blobs[self.uploads] = payload
return item
if method == "GET":
return self.release
if method == "POST":
assert self.release is None
self.release = {**release.json.loads(payload), "id": 7}
return dict(self.release)
if method == "PATCH":
self.release.update(release.json.loads(payload))
if not self.release["draft"] and self.tag_sha is None:
self.tag_sha = self.release["target_commitish"]
return dict(self.release)
raise AssertionError((method, url))
class ReleaseTest(unittest.TestCase):
def test_retry_after_partial_upload_keeps_release_draft_until_complete(self):
with TemporaryDirectory() as directory:
paths = [Path(directory) / "source.tar.gz", Path(directory) / "bench.txt"]
for path in paths:
path.write_bytes(path.name.encode())
fake = FakeGitea()
def digest(asset, _api):
return hashlib.sha256(fake.blobs[asset["id"]]).hexdigest()
with patch.object(release, "request", fake.request), \
patch.object(release, "asset_digest", digest):
with self.assertRaisesRegex(OSError, "injected upload failure"):
release.publish("v1.2.3", False, paths, "https://api", "org/repo", "a" * 40)
self.assertTrue(fake.release["draft"])
self.assertEqual(len(fake.assets), 1)
fake.fail_second_upload = False
release.publish("v1.2.3", False, paths, "https://api", "org/repo", "a" * 40)
self.assertFalse(fake.release["draft"])
self.assertEqual({item["name"] for item in fake.assets},
{path.name for path in paths})
fake.assets[0]["size"] = len(fake.blobs[fake.assets[0]["id"]])
fake.blobs[fake.assets[0]["id"]] = b"x" * fake.assets[0]["size"]
release.publish("v1.2.3", False, paths, "https://api", "org/repo", "a" * 40)
self.assertFalse(fake.release["draft"])
self.assertEqual(digest(fake.assets[0], "https://api"),
release.sha256_file(paths[0]))
def test_preflight_rejects_missing_and_duplicate_assets(self):
with TemporaryDirectory() as directory:
path = Path(directory) / "one"
with self.assertRaisesRegex(ValueError, "missing or empty"):
release.files_to_publish([str(path)])
path.write_bytes(b"x")
with self.assertRaisesRegex(ValueError, "distinct"):
release.files_to_publish([str(path), str(path)])
def test_existing_git_tag_mismatch_blocks_release_without_changes(self):
with TemporaryDirectory() as directory:
path = Path(directory) / "image.tar.gz"
path.write_bytes(b"image")
fake = FakeGitea()
fake.tag_sha = "b" * 40
fake.release = {"id": 7, "tag_name": "v1.2.3",
"target_commitish": "a" * 40, "draft": False}
with patch.object(release, "request", fake.request):
with self.assertRaisesRegex(ValueError, "Git tag points"):
release.publish("v1.2.3", False, [path], "https://api",
"org/repo", "a" * 40)
self.assertEqual(fake.uploads, 0)
self.assertFalse(fake.release["draft"])
def test_complete_release_without_git_tag_is_not_accepted(self):
with TemporaryDirectory() as directory:
path = Path(directory) / "image.tar.gz"
path.write_bytes(b"image")
fake = FakeGitea()
fake.release = {"id": 7, "tag_name": "v1.2.3",
"target_commitish": "a" * 40, "draft": False}
fake.assets = [{"id": 1, "name": path.name, "size": path.stat().st_size}]
with patch.object(release, "request", fake.request), \
patch.object(release, "asset_digest", lambda *_: release.sha256_file(path)):
with self.assertRaisesRegex(ValueError, "no Git tag"):
release.publish("v1.2.3", False, [path], "https://api",
"org/repo", "a" * 40)
if __name__ == "__main__":
unittest.main()
-116
View File
@@ -1,116 +0,0 @@
// SPDX-License-Identifier: MIT
//! Bounded host-only check: captured BM13xx report through HAL to a strict pool.
use alkane_os::hal_wire::HalClient;
use alkane_os::miner::Bm1366Miner;
use alkane_os::stratum_client::{PoolConnection, PoolEvent, ReportEvent};
use std::error::Error;
use std::io;
use std::net::SocketAddr;
use std::time::{Duration, Instant};
const CAPTURED_HEADER: [u8; 80] = [
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,
];
const BM1362_HEADER_HEX: &str = concat!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
"b4213a0503969b7384e1215aace8cfc65dae22d8493ad48fec0b7ac3b0ad7b4e7",
"fb0c5c0012e6a8f06021700000000"
);
fn bm1362_header() -> Result<[u8; 80], io::Error> {
let mut header = [0_u8; 80];
for (index, pair) in BM1362_HEADER_HEX.as_bytes().chunks_exact(2).enumerate() {
let digits = std::str::from_utf8(pair).map_err(io::Error::other)?;
header[index] = u8::from_str_radix(digits, 16).map_err(io::Error::other)?;
}
Ok(header)
}
fn failure(message: impl Into<String>) -> io::Error {
io::Error::other(message.into())
}
fn main() -> Result<(), Box<dyn Error>> {
let mut args = std::env::args().skip(1);
let socket = args.next().ok_or_else(|| {
failure("usage: simulator_pool_replay_probe HAL_SOCKET POOL_ADDRESS [SHARES] [CHIP]")
})?;
let address: SocketAddr = args
.next()
.ok_or_else(|| failure("missing pool address"))?
.parse()?;
let expected_accepts: usize = args.next().map_or(Ok(1), |value| value.parse())?;
if !(1..=64).contains(&expected_accepts) {
return Err(failure("SHARES must be between 1 and 64").into());
}
let chip = args.next().unwrap_or_else(|| "BM1366".to_owned());
let first_header = match chip.as_str() {
"BM1366" => CAPTURED_HEADER,
"BM1362" if expected_accepts == 1 => bm1362_header()?,
"BM1362" => return Err(failure("BM1362 has one captured header").into()),
_ => return Err(failure("unsupported captured chip").into()),
};
if args.next().is_some() {
return Err(failure("unexpected argument").into());
}
if !address.ip().is_loopback() {
return Err(failure("probe pool must be on loopback").into());
}
let mut backend = HalClient::connect(socket)?;
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000)
.ok_or_else(|| failure("invalid simulator configuration"))?;
let mut pool = PoolConnection::connect(
address,
"alkane-simulator-probe",
"alkane.test",
"x",
Duration::from_secs(2),
Duration::from_secs(5),
)
.map_err(|error| failure(format!("pool handshake: {error:?}")))?;
miner.start()?;
let deadline = Instant::now() + Duration::from_secs(10 + 2 * expected_accepts as u64);
let mut issued = 0;
let mut submitted = 0;
let mut accepted = 0;
while Instant::now() < deadline {
let (event, reports) = pool
.cycle(&mut miner)
.map_err(|error| failure(format!("mining cycle: {error:?}")))?;
submitted += reports
.iter()
.filter(|report| matches!(report, ReportEvent::Submitted(_)))
.count();
match event {
PoolEvent::Work(work) => {
if issued == 0 && work.header != first_header {
return Err(failure("pool job differs from real-silicon capture").into());
}
issued += 1;
}
PoolEvent::ShareAccepted(_) => {
if accepted >= submitted || accepted >= issued {
return Err(failure("unattributed pool acceptance").into());
}
accepted += 1;
if accepted == expected_accepts {
miner.stop()?;
println!(
"{chip} real captured nonce accepted by strict loopback pool ({accepted} shares)"
);
return Ok(());
}
}
PoolEvent::ShareRejected(_) => return Err(failure("pool rejected share").into()),
_ => {}
}
}
Err(failure("captured share was not accepted before deadline").into())
}
+10 -37
View File
@@ -1,10 +1,9 @@
// SPDX-License-Identifier: MIT
//! Exercise the SDK's host-only BM13xx HAL simulator with a captured job.
//! Exercise the SDK's host-only BM1366 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;
const HEADER: [u8; 80] = [
0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38, 0x9d,
@@ -14,46 +13,20 @@ const HEADER: [u8; 80] = [
0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00,
];
const BM1362_HEADER_HEX: &str = concat!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
"b4213a0503969b7384e1215aace8cfc65dae22d8493ad48fec0b7ac3b0ad7b4e7",
"fb0c5c0012e6a8f06021700000000"
);
fn bm1362_header() -> Result<[u8; 80], io::Error> {
let mut header = [0_u8; 80];
for (index, pair) in BM1362_HEADER_HEX.as_bytes().chunks_exact(2).enumerate() {
let digits = std::str::from_utf8(pair).map_err(io::Error::other)?;
header[index] = u8::from_str_radix(digits, 16).map_err(io::Error::other)?;
}
Ok(header)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut args = std::env::args().skip(1);
let path = args
.next()
.ok_or("usage: simulator_replay_probe SOCKET_PATH [BM1366|BM1362]")?;
let chip = args.next().unwrap_or_else(|| "BM1366".to_owned());
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),
_ => return Err("unsupported captured chip".into()),
};
let path = std::env::args()
.nth(1)
.ok_or("usage: simulator_replay_probe SOCKET_PATH")?;
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)
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];
target[26..28].fill(0xff);
miner.submit(header, target, 0x18)?;
let share = miner.poll()?.ok_or("missing captured nonce report")?;
miner.submit(HEADER, target, 0x18)?;
let share = miner.poll()?.ok_or("missing BM1366 nonce report")?;
miner.stop()?;
assert_eq!(share.nonce, nonce);
println!("{chip} captured report verified at difficulty 1");
assert_eq!(share.nonce, 0xedad_ff38);
println!("BM1366 captured report verified at difficulty 1");
Ok(())
}
-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);
}
}
+6 -18
View File
@@ -4,7 +4,6 @@
use crate::HardwareBackend;
use std::fmt;
use std::io::{self, Read, Write};
use std::net::Shutdown;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixStream;
@@ -109,11 +108,6 @@ pub struct HalClient {
}
impl HalClient {
fn poison(&mut self) {
self.poisoned = true;
let _ = self.stream.shutdown(Shutdown::Both);
}
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?;
Self::from_stream(stream)
@@ -139,9 +133,7 @@ impl HalClient {
let result = self.exchange_inner(opcode, payload);
if let Err(ref error) = result {
if !matches!(error, HalError::Device(_)) {
self.poison();
// A backend power lease must expire on disconnect. Reusing a
// desynchronized stream could silently discard an off request.
self.poisoned = true;
}
}
result
@@ -187,7 +179,7 @@ impl HalClient {
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
if !self.exchange(opcode, payload)?.is_empty() {
self.poison();
self.poisoned = true;
return Err(HalError::Protocol("unexpected response data"));
}
Ok(())
@@ -360,12 +352,12 @@ impl HardwareBackend for HalClient {
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
let body = self.exchange(RECEIVE_FRAME, &request)?;
if body.len() < 2 {
self.poison();
self.poisoned = true;
return Err(HalError::Protocol("missing receive length"));
}
let count = u16::from_le_bytes([body[0], body[1]]) as usize;
if count > frame.len() || body.len() != count + 2 {
self.poison();
self.poisoned = true;
return Err(HalError::Protocol("invalid received frame size"));
}
frame[..count].copy_from_slice(&body[2..]);
@@ -388,7 +380,7 @@ impl HardwareBackend for HalClient {
let bytes: [u8; 4] = match body.try_into() {
Ok(bytes) => bytes,
Err(_) => {
self.poison();
self.poisoned = true;
return Err(HalError::Protocol("invalid temperature response"));
}
};
@@ -396,10 +388,6 @@ impl HardwareBackend for HalClient {
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
let result = self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]);
if !enabled && result.is_err() {
self.poison();
}
result
self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)])
}
}
-7
View File
@@ -3,20 +3,13 @@
//! 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;
pub mod stratum_client;
pub mod stratum_session;
pub mod stratum_submit;
pub mod stratum_v1;
pub mod stratum_wire;
pub mod stratum_work;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+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();
}
}
+7 -99
View File
@@ -1,26 +1,17 @@
// 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),
AlreadyRunning,
NotRunning,
Faulted,
WorkIdInUse(u8),
UnsafeTemperature(i32),
InvalidWork,
InvalidReport(ReportError),
@@ -34,12 +25,10 @@ impl<E: fmt::Display> fmt::Display for MinerError<E> {
Self::Backend(error) => write!(f, "hardware backend: {error}"),
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::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,16 +53,13 @@ struct Work {
pub struct Bm1366Miner<'a, B: HardwareBackend> {
backend: &'a mut B,
chip: ChipModel,
chain: u8,
sensor: u8,
fan: u8,
fan_percent: u8,
max_temperature_mc: i32,
running: bool,
faulted: bool,
work: [Option<Work>; 32],
used_work_ids: [bool; 32],
}
impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
@@ -85,43 +71,19 @@ 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,
fan_percent,
max_temperature_mc,
running: false,
faulted: false,
work: [None; 32],
used_work_ids: [false; 32],
})
}
@@ -130,14 +92,11 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
match self.backend.set_psu_enabled(false) {
Ok(()) => {
self.running = false;
self.faulted = false;
self.used_work_ids = [false; 32];
Ok(())
}
Err(error) => {
// The backend may have left power on. Drop retries shutdown.
self.running = true;
self.faulted = true;
Err(error)
}
}
@@ -187,29 +146,6 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
self.power_off()
}
/// Flush the ASIC's in-flight work before reusing any work IDs. A reset
/// failure shuts the PSU down because old reports may still arrive.
pub fn reset_chain(&mut self) -> Result<(), MinerError<B::Error>> {
if !self.running {
return Err(MinerError::NotRunning);
}
if self.faulted {
return Err(MinerError::Faulted);
}
self.work = [None; 32];
self.check_temperature()?;
if let Err(error) = self.backend.set_chain_reset(self.chain, true) {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
if let Err(error) = self.backend.set_chain_reset(self.chain, false) {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
self.used_work_ids = [false; 32];
Ok(())
}
pub fn submit(
&mut self,
header: [u8; 80],
@@ -219,26 +155,13 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
if !self.running {
return Err(MinerError::NotRunning);
}
if self.faulted {
return Err(MinerError::Faulted);
}
let frame = encode_work(&header, work_id).ok_or(MinerError::InvalidWork)?;
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 slot = usize::from(work_id >> 3);
if self.used_work_ids[slot] {
return Err(MinerError::WorkIdInUse(work_id));
}
// A failed send may still have reached the ASIC, so reserve first.
self.used_work_ids[slot] = true;
if let Err(error) = self.backend.send_frame(self.chain, &frame) {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
self.work[slot] = Some(Work {
self.work[usize::from(work_id >> 3)] = Some(Work {
header,
target_le,
id: work_id,
@@ -247,8 +170,7 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
}
/// Forget prior pool jobs after `clean_jobs`, while leaving the ASIC powered.
/// Reports already in flight are then classified as stale. Their work IDs
/// remain reserved until a confirmed chain reset or PSU shutdown.
/// Reports already in flight are then classified as stale.
pub fn clear_work(&mut self) {
self.work = [None; 32];
}
@@ -257,9 +179,6 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
if !self.running {
return Err(MinerError::NotRunning);
}
if self.faulted {
return Err(MinerError::Faulted);
}
self.check_temperature()?;
let mut frame = [0_u8; REPORT_BYTES];
let length = match self.backend.receive_frame(self.chain, &mut frame) {
@@ -305,17 +224,6 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
hash_le: check.hash_le,
}))
}
/// Keep thermal supervision active while pool share replies are pending.
pub fn supervise(&mut self) -> Result<(), MinerError<B::Error>> {
if !self.running {
return Err(MinerError::NotRunning);
}
if self.faulted {
return Err(MinerError::Faulted);
}
self.check_temperature()
}
}
impl<B: HardwareBackend> Drop for Bm1366Miner<'_, B> {
-170
View File
@@ -1,170 +0,0 @@
// SPDX-License-Identifier: MIT
//! Litecoin's fixed scrypt proof-of-work hash for validating reported shares.
//! This module hashes one supplied header and never searches for a nonce.
use crate::pow::sha256;
const N: usize = 1024;
fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
let mut block = [0_u8; 64];
if key.len() > block.len() {
block[..32].copy_from_slice(&sha256(key));
} else {
block[..key.len()].copy_from_slice(key);
}
let mut inner = Vec::with_capacity(64 + message.len());
inner.extend(block.iter().map(|byte| byte ^ 0x36));
inner.extend_from_slice(message);
let inner_hash = sha256(&inner);
let mut outer = [0_u8; 96];
for (destination, byte) in outer[..64].iter_mut().zip(block) {
*destination = byte ^ 0x5c;
}
outer[64..].copy_from_slice(&inner_hash);
sha256(&outer)
}
// PBKDF2-HMAC-SHA256 with the fixed single iteration specified for scrypt.
fn pbkdf2_one(password: &[u8], salt: &[u8], output: &mut [u8]) {
let mut message = Vec::with_capacity(salt.len() + 4);
message.extend_from_slice(salt);
message.extend_from_slice(&[0_u8; 4]);
for (index, chunk) in output.chunks_mut(32).enumerate() {
let block = u32::try_from(index + 1).expect("fixed scrypt output fits u32");
message[salt.len()..].copy_from_slice(&block.to_be_bytes());
chunk.copy_from_slice(&hmac_sha256(password, &message)[..chunk.len()]);
}
}
fn salsa20_8(input: &mut [u32; 16]) {
let original = *input;
let mut x = original;
for _ in 0..4 {
x[4] ^= x[0].wrapping_add(x[12]).rotate_left(7);
x[8] ^= x[4].wrapping_add(x[0]).rotate_left(9);
x[12] ^= x[8].wrapping_add(x[4]).rotate_left(13);
x[0] ^= x[12].wrapping_add(x[8]).rotate_left(18);
x[9] ^= x[5].wrapping_add(x[1]).rotate_left(7);
x[13] ^= x[9].wrapping_add(x[5]).rotate_left(9);
x[1] ^= x[13].wrapping_add(x[9]).rotate_left(13);
x[5] ^= x[1].wrapping_add(x[13]).rotate_left(18);
x[14] ^= x[10].wrapping_add(x[6]).rotate_left(7);
x[2] ^= x[14].wrapping_add(x[10]).rotate_left(9);
x[6] ^= x[2].wrapping_add(x[14]).rotate_left(13);
x[10] ^= x[6].wrapping_add(x[2]).rotate_left(18);
x[3] ^= x[15].wrapping_add(x[11]).rotate_left(7);
x[7] ^= x[3].wrapping_add(x[15]).rotate_left(9);
x[11] ^= x[7].wrapping_add(x[3]).rotate_left(13);
x[15] ^= x[11].wrapping_add(x[7]).rotate_left(18);
x[1] ^= x[0].wrapping_add(x[3]).rotate_left(7);
x[2] ^= x[1].wrapping_add(x[0]).rotate_left(9);
x[3] ^= x[2].wrapping_add(x[1]).rotate_left(13);
x[0] ^= x[3].wrapping_add(x[2]).rotate_left(18);
x[6] ^= x[5].wrapping_add(x[4]).rotate_left(7);
x[7] ^= x[6].wrapping_add(x[5]).rotate_left(9);
x[4] ^= x[7].wrapping_add(x[6]).rotate_left(13);
x[5] ^= x[4].wrapping_add(x[7]).rotate_left(18);
x[11] ^= x[10].wrapping_add(x[9]).rotate_left(7);
x[8] ^= x[11].wrapping_add(x[10]).rotate_left(9);
x[9] ^= x[8].wrapping_add(x[11]).rotate_left(13);
x[10] ^= x[9].wrapping_add(x[8]).rotate_left(18);
x[12] ^= x[15].wrapping_add(x[14]).rotate_left(7);
x[13] ^= x[12].wrapping_add(x[15]).rotate_left(9);
x[14] ^= x[13].wrapping_add(x[12]).rotate_left(13);
x[15] ^= x[14].wrapping_add(x[13]).rotate_left(18);
}
for ((word, initial), mixed) in input.iter_mut().zip(original).zip(x) {
*word = initial.wrapping_add(mixed);
}
}
fn block_mix(input: &[u32; 32]) -> [u32; 32] {
let mut x: [u32; 16] = input[16..].try_into().expect("fixed block size");
let mut output = [0_u32; 32];
for (index, chunk) in input.chunks_exact(16).enumerate() {
for (word, source) in x.iter_mut().zip(chunk) {
*word ^= source;
}
salsa20_8(&mut x);
output[index * 16..(index + 1) * 16].copy_from_slice(&x);
}
output
}
/// Hash one 80-byte Litecoin header with scrypt(N=1024, r=1, p=1, dkLen=32).
/// The return value is the raw little-endian PoW digest.
pub fn scrypt_1024_1_1_256(header: &[u8; 80]) -> [u8; 32] {
let mut initial = [0_u8; 128];
pbkdf2_one(header, header, &mut initial);
let mut x = [0_u32; 32];
for (word, bytes) in x.iter_mut().zip(initial.chunks_exact(4)) {
*word = u32::from_le_bytes(bytes.try_into().expect("four-byte word"));
}
let mut memory = vec![[0_u32; 32]; N];
for saved in &mut memory {
*saved = x;
x = block_mix(&x);
}
for _ in 0..N {
let index = x[16] as usize & (N - 1);
for (word, saved) in x.iter_mut().zip(memory[index]) {
*word ^= saved;
}
x = block_mix(&x);
}
for (word, bytes) in x.iter().zip(initial.chunks_exact_mut(4)) {
bytes.copy_from_slice(&word.to_le_bytes());
}
let mut digest = [0_u8; 32];
pbkdf2_one(header, &initial, &mut digest);
digest
}
/// Validate one supplied header against an exact little-endian pool target.
pub fn verify_scrypt_header(header: &[u8; 80], target_le: &[u8; 32]) -> ([u8; 32], bool) {
let digest = scrypt_1024_1_1_256(header);
let meets_target = digest.iter().rev().cmp(target_le.iter().rev()).is_le();
(digest, meets_target)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn litecoin_block_29255_matches_published_scrypt_pow() {
let header_hex = concat!(
"01000000f615f7ce3b4fc6b8f61e8f89aedb1d0852507650533a9e3b10b9bbcc30639f27",
"9fcaa86746e1ef52d3edb3c4ad8259920d509bd073605c9bf1d59983752a6b06b817bb4",
"ea78e011d012d59d4"
);
let mut header = [0_u8; 80];
for (byte, pair) in header.iter_mut().zip(header_hex.as_bytes().chunks_exact(2)) {
*byte = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap();
}
let expected_big = "0000000110c8357966576df46f3b802ca897deb7ad18b12f1c24ecff6386ebd9";
let mut expected = [0_u8; 32];
for (byte, pair) in expected
.iter_mut()
.rev()
.zip(expected_big.as_bytes().chunks_exact(2))
{
*byte = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap();
}
let (digest, accepted) = verify_scrypt_header(&header, &expected);
assert_eq!(digest, expected);
assert!(accepted);
assert!(!verify_scrypt_header(&header, &[0_u8; 32]).1);
}
#[test]
fn fixed_header_matches_independent_openssl_scrypt() {
let header = core::array::from_fn(|index| index as u8);
let expected = "bc540a1a801df96e493005c71e010e2d387607fbf0fec416fd3c2645aa1ba9d2";
let actual = scrypt_1024_1_1_256(&header);
let actual_hex: String = actual.iter().map(|byte| format!("{byte:02x}")).collect();
assert_eq!(actual_hex, expected);
}
}
-510
View File
@@ -1,510 +0,0 @@
// SPDX-License-Identifier: MIT
//! One bounded pool connection with ordered jobs and verified share replies.
use crate::miner::{Bm1366Miner, MinerError, ValidShare};
use crate::stratum_session::{DispatchError, IssuedWork, PoolSession, SessionError};
use crate::stratum_v1::{parse_boolean_response, PoolMessageError};
use crate::stratum_wire::{HandshakeError, PoolHandshake, StratumWire, WireError};
use crate::HardwareBackend;
use serde_json::Value;
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::time::{Duration, Instant};
const MAX_PENDING_SHARES: usize = 32;
const SHARE_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_REPORTS_PER_CYCLE: usize = 256;
const POOL_WRITE_DEADLINE: Duration = Duration::from_millis(100);
#[derive(Debug)]
pub enum ClientError<E> {
Wire(WireError),
Pool(PoolMessageError),
Session(SessionError),
Dispatch(DispatchError<E>),
UnexpectedResponse,
TooManyPending,
RequestIdsExhausted,
ShareReplyTimeout,
EmergencyShutdown(E),
}
#[derive(Debug)]
pub enum PoolEvent {
Idle,
Control,
Work(IssuedWork),
ShareAccepted(u64),
ShareRejected(u64),
}
#[derive(Debug, Eq, PartialEq)]
pub enum ReportEvent {
Stale,
BelowTarget,
Submitted(u64),
Backpressured,
}
#[derive(Debug)]
pub enum CycleError<E> {
Pool(ClientError<E>),
Miner(MinerError<E>),
Submit(ClientError<()>),
EmergencyShutdown(E),
}
pub struct PoolConnection {
wire: StratumWire,
session: PoolSession,
worker: String,
early: VecDeque<Vec<u8>>,
next_request_id: u64,
pending: Vec<PendingShare>,
accepted: u64,
rejected: u64,
}
struct PendingShare {
id: u64,
sent_at: Instant,
}
impl PoolConnection {
pub fn connect(
address: SocketAddr,
agent: &str,
worker: &str,
password: &str,
io_timeout: Duration,
handshake_timeout: Duration,
) -> Result<Self, HandshakeError> {
let mut wire = StratumWire::connect(address, io_timeout).map_err(HandshakeError::Wire)?;
let handshake = wire.handshake(agent, worker, password, handshake_timeout)?;
Self::from_handshake(wire, handshake, worker)
.map_err(|_| HandshakeError::Pool(PoolMessageError::InvalidField))
}
fn from_handshake(
mut wire: StratumWire,
handshake: PoolHandshake,
worker: &str,
) -> Result<Self, SessionError> {
let session = PoolSession::new(
handshake.subscription,
handshake.configure.version_mask,
handshake.configure.subscribe_extranonce,
)?;
wire.cap_write_timeout(POOL_WRITE_DEADLINE);
Ok(Self {
wire,
session,
worker: worker.to_owned(),
early: handshake.early_notifications.into(),
next_request_id: 4,
pending: Vec::new(),
accepted: 0,
rejected: 0,
})
}
pub fn step<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<PoolEvent, ClientError<B::Error>> {
let result = self.step_inner(miner);
if result.is_err() {
self.wire.close();
if let Err(error) = miner.stop() {
return Err(ClientError::EmergencyShutdown(error));
}
}
result
}
fn step_inner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<PoolEvent, ClientError<B::Error>> {
if self
.pending
.first()
.is_some_and(|share| share.sent_at.elapsed() >= SHARE_REPLY_TIMEOUT)
{
return Err(ClientError::ShareReplyTimeout);
}
let line = if let Some(line) = self.early.pop_front() {
line
} else {
match self.wire.try_read_line() {
Ok(Some(line)) => line,
Ok(None) => return Ok(PoolEvent::Idle),
Err(error) => return Err(ClientError::Wire(error)),
}
};
let message: Value =
serde_json::from_slice(&line).map_err(|_| ClientError::Pool(PoolMessageError::Json))?;
if let Some(id) = message.get("id").and_then(Value::as_u64) {
if !self.pending.iter().any(|share| share.id == id) {
return Err(ClientError::UnexpectedResponse);
}
let accepted = parse_boolean_response(&line, id).map_err(ClientError::Pool)?;
self.pending.retain(|pending| pending.id != id);
if accepted {
self.accepted = self.accepted.saturating_add(1);
return Ok(PoolEvent::ShareAccepted(id));
}
self.rejected = self.rejected.saturating_add(1);
return Ok(PoolEvent::ShareRejected(id));
}
if !message.get("id").is_none_or(Value::is_null) {
return Err(ClientError::Pool(PoolMessageError::WrongMessage));
}
match message.get("method").and_then(Value::as_str) {
Some("mining.notify") => {
let issued = match self.session.issue_to_miner(miner, &line) {
Err(DispatchError::Session(SessionError::WorkIdsExhausted)) => {
miner
.reset_chain()
.map_err(|error| ClientError::Dispatch(DispatchError::Miner(error)))?;
self.after_hardware_reset(miner);
self.session.issue_to_miner(miner, &line)
}
result => result,
};
issued.map(PoolEvent::Work).map_err(ClientError::Dispatch)
}
Some("mining.set_difficulty" | "mining.set_version_mask" | "mining.set_extranonce") => {
self.session
.control_with_miner(miner, &line)
.map_err(ClientError::Session)?;
Ok(PoolEvent::Control)
}
_ => Err(ClientError::Pool(PoolMessageError::WrongMessage)),
}
}
/// Send only a nonce already verified by the miner and session. A sent
/// request remains pending until its matching boolean pool reply arrives.
pub fn submit_share(&mut self, share: ValidShare) -> Result<u64, ClientError<()>> {
if self.pending.len() >= MAX_PENDING_SHARES {
return Err(ClientError::TooManyPending);
}
let id = self.next_request_id;
let next = id.checked_add(1).ok_or(ClientError::RequestIdsExhausted)?;
let line = self
.session
.submission(share, &self.worker, id)
.map_err(ClientError::Session)?;
self.wire
.send_line(line.as_bytes())
.map_err(ClientError::Wire)?;
self.next_request_id = next;
self.pending.push(PendingShare {
id,
sent_at: Instant::now(),
});
Ok(id)
}
pub fn share_counts(&self) -> (u64, u64, usize) {
(self.accepted, self.rejected, self.pending.len())
}
/// Process one pool message, then drain a bounded burst of ASIC reports.
/// A reported nonce is verified before sending. The caller must cycle
/// continuously; hardware still requires an independent power watchdog.
pub fn cycle<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<(PoolEvent, Vec<ReportEvent>), CycleError<B::Error>> {
let pool = self.step(miner).map_err(CycleError::Pool)?;
let mut reports = Vec::new();
for _ in 0..MAX_REPORTS_PER_CYCLE {
if self.pending.len() >= MAX_PENDING_SHARES {
miner.supervise().map_err(CycleError::Miner)?;
reports.push(ReportEvent::Backpressured);
break;
}
let event = match miner.poll() {
Ok(None) => break,
Ok(Some(share)) => {
let id = match self.submit_share(share) {
Ok(id) => id,
Err(error) => {
self.wire.close();
miner.stop().map_err(CycleError::EmergencyShutdown)?;
return Err(CycleError::Submit(error));
}
};
ReportEvent::Submitted(id)
}
Err(MinerError::StaleReport) => ReportEvent::Stale,
Err(MinerError::BelowTarget) => ReportEvent::BelowTarget,
Err(error) => return Err(CycleError::Miner(error)),
};
reports.push(event);
}
Ok((pool, reports))
}
/// Call only after an actual chain reset flushes old hardware reports.
pub fn after_hardware_reset<B: HardwareBackend>(&mut self, miner: &mut Bm1366Miner<'_, B>) {
miner.clear_work();
self.session.after_hardware_reset();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stratum_v1::Subscription;
use std::cell::Cell;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
#[derive(Default)]
struct Backend {
sent: Vec<Vec<u8>>,
powered: Rc<Cell<bool>>,
reports_remaining: usize,
reset_assertions: usize,
}
impl HardwareBackend for Backend {
type Error = ();
fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
self.sent.push(frame.to_vec());
Ok(())
}
fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
if self.reports_remaining == 0 {
return Ok(0);
}
self.reports_remaining -= 1;
frame[..11].copy_from_slice(&[
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
]);
Ok(11)
}
fn set_chain_reset(&mut self, _chain: u8, asserted: bool) -> Result<(), Self::Error> {
if asserted {
self.reset_assertions += 1;
}
Ok(())
}
fn set_fan_target(&mut self, _fan: u8, _percent: u8) -> Result<(), Self::Error> {
Ok(())
}
fn read_temperature_mc(&mut self, _sensor: u8) -> Result<i32, Self::Error> {
Ok(50_000)
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.powered.set(enabled);
Ok(())
}
}
fn test_link(input: &'static [u8]) -> (PoolConnection, thread::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let (ready, received) = mpsc::channel();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.write_all(input).unwrap();
ready.send(()).unwrap();
});
let stream = TcpStream::connect(address).unwrap();
let wire = StratumWire::from_stream(stream, Duration::from_secs(2)).unwrap();
received.recv_timeout(Duration::from_secs(2)).unwrap();
let handshake = PoolHandshake {
subscription: Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
},
configure: crate::stratum_v1::ConfigureResult {
version_mask: None,
subscribe_extranonce: false,
},
early_notifications: Vec::new(),
};
(
PoolConnection::from_handshake(wire, handshake, "miner.worker").unwrap(),
server,
)
}
#[test]
fn pool_controls_then_dispatches_one_synthetic_job() {
let (mut link, server) = test_link(
concat!(
"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n",
"{\"id\":null,\"method\":\"mining.notify\",\"params\":[\"job-1\",",
"\"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\",",
"\"616263\",\"78797a\",[],\"20000000\",\"1d00ffff\",\"66554433\",true]}\n"
)
.as_bytes(),
);
let mut backend = Backend::default();
{
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert!(matches!(
link.cycle(&mut miner).unwrap(),
(PoolEvent::Control, reports) if reports.is_empty()
));
match link.cycle(&mut miner).unwrap() {
(PoolEvent::Work(work), reports) if reports.is_empty() => {
assert_eq!(work.work_id, 0)
}
_ => panic!("expected job"),
}
}
assert_eq!(backend.sent.len(), 1);
server.join().unwrap();
}
#[test]
fn thirty_third_job_flushes_asic_before_reusing_work_id() {
let (mut link, server) = test_link(b"");
link.early.push_back(
b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n".to_vec(),
);
let notify = concat!(
"{\"id\":null,\"method\":\"mining.notify\",\"params\":[\"job\",",
"\"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\",",
"\"616263\",\"78797a\",[],\"20000000\",\"1d00ffff\",\"66554433\",true]}\n"
);
for _ in 0..33 {
link.early.push_back(notify.as_bytes().to_vec());
}
let mut backend = Backend::default();
let powered = Rc::clone(&backend.powered);
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert!(matches!(link.step(&mut miner), Ok(PoolEvent::Control)));
let mut first_header = None;
for index in 0..33 {
let PoolEvent::Work(work) = link.step(&mut miner).unwrap() else {
panic!("expected work");
};
if index == 0 {
first_header = Some(work.header);
}
if index == 32 {
assert_eq!(work.work_id, 0);
assert_ne!(Some(work.header), first_header);
}
}
assert!(powered.get());
miner.stop().unwrap();
drop(miner);
assert_eq!(backend.reset_assertions, 2);
assert_eq!(backend.sent.len(), 33);
server.join().unwrap();
}
#[test]
fn share_replies_match_pending_ids_and_count_accepts_separately() {
let (mut link, server) = test_link(
concat!(
"{\"id\":4,\"result\":true,\"error\":null}\n",
"{\"id\":5,\"result\":false,\"error\":[23,\"stale\"]}\n",
"{\"id\":6,\"result\":true,\"error\":null}\n"
)
.as_bytes(),
);
link.pending.extend([4, 5].map(|id| PendingShare {
id,
sent_at: Instant::now(),
}));
let mut backend = Backend::default();
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
assert!(matches!(
link.step(&mut miner).unwrap(),
PoolEvent::ShareAccepted(4)
));
assert!(matches!(
link.step(&mut miner).unwrap(),
PoolEvent::ShareRejected(5)
));
assert_eq!(link.share_counts(), (1, 1, 0));
assert!(matches!(
link.step(&mut miner),
Err(ClientError::UnexpectedResponse)
));
server.join().unwrap();
}
#[test]
fn untracked_report_cannot_be_sent_to_pool() {
let (mut link, server) = test_link(b"");
let report = ValidShare {
nonce: 1,
work_id: 0,
rolled_version: 0x2000_0000,
hash_le: [0; 32],
};
assert!(matches!(
link.submit_share(report),
Err(ClientError::Session(SessionError::StaleShare))
));
assert_eq!(link.share_counts(), (0, 0, 0));
server.join().unwrap();
}
#[test]
fn unanswered_share_closes_pool_connection() {
let (mut link, server) = test_link(b"");
link.pending.push(PendingShare {
id: 4,
sent_at: Instant::now() - SHARE_REPLY_TIMEOUT - Duration::from_secs(1),
});
let mut backend = Backend::default();
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
assert!(matches!(
link.step(&mut miner),
Err(ClientError::ShareReplyTimeout)
));
assert!(link.wire.is_closed());
server.join().unwrap();
}
#[test]
fn malformed_pool_message_stops_miner_before_returning() {
let (mut link, server) = test_link(b"{}\n");
let mut backend = Backend::default();
let powered = Rc::clone(&backend.powered);
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert!(powered.get());
assert!(matches!(link.cycle(&mut miner), Err(CycleError::Pool(_))));
assert!(!powered.get());
server.join().unwrap();
}
#[test]
fn idle_pool_does_not_limit_asic_report_burst_to_one() {
let (mut link, server) =
test_link(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n");
let mut backend = Backend {
reports_remaining: MAX_REPORTS_PER_CYCLE + 3,
..Backend::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
let (pool, reports) = link.cycle(&mut miner).unwrap();
assert!(matches!(pool, PoolEvent::Control));
assert_eq!(reports.len(), MAX_REPORTS_PER_CYCLE);
assert!(reports
.iter()
.all(|event| matches!(event, ReportEvent::Stale)));
drop(miner);
assert_eq!(backend.reports_remaining, 3);
server.join().unwrap();
}
}
-378
View File
@@ -1,378 +0,0 @@
// SPDX-License-Identifier: MIT
//! Bounded pool-job bookkeeping for one BM1366 chain and one Stratum V1 session.
use crate::difficulty::PoolDifficulty;
use crate::miner::{Bm1366Miner, MinerError, ValidShare};
use crate::pow::{sha256d, VersionMask};
use crate::stratum_submit::{format_submission, Submission, SubmitError};
use crate::stratum_v1::{
parse_control_notification, parse_notify, PoolMessageError, PoolNotification, Subscription,
};
use crate::stratum_work::JobError;
use crate::HardwareBackend;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionError {
InvalidSubscription,
Pool(PoolMessageError),
Work(JobError),
MissingDifficulty,
ExtranonceExhausted,
WorkIdsExhausted,
StaleShare,
UnverifiedShare,
Submit(SubmitError),
}
#[derive(Debug, Eq, PartialEq)]
pub enum DispatchError<E> {
Session(SessionError),
Miner(MinerError<E>),
}
#[derive(Debug)]
pub struct IssuedWork {
pub work_id: u8,
pub header: [u8; 80],
pub target_le: [u8; 32],
/// The hardware miner must forget prior work before submitting this job.
pub clean_jobs: bool,
}
struct TrackedWork {
job_id: String,
header: [u8; 80],
target_le: [u8; 32],
extranonce2: Vec<u8>,
ntime: u32,
base_version: u32,
}
struct NonceSpace {
template: [u8; 80],
next: [u8; 32],
exhausted: bool,
}
const MAX_NONCE_SPACES: usize = 4096;
pub struct PoolSession {
subscription: Subscription,
version_mask: Option<VersionMask>,
subscribe_extranonce: bool,
pending_difficulty: Option<PoolDifficulty>,
active_difficulty: Option<PoolDifficulty>,
nonce_spaces: Vec<NonceSpace>,
zero_extranonce_headers: Vec<[u8; 80]>,
tracked: [Option<TrackedWork>; 32],
next_slot: usize,
}
impl PoolSession {
pub fn new(
subscription: Subscription,
version_mask: Option<VersionMask>,
subscribe_extranonce: bool,
) -> Result<Self, SessionError> {
if subscription.extranonce1.len() > 32 || subscription.extranonce2_size > 32 {
return Err(SessionError::InvalidSubscription);
}
Ok(Self {
subscription,
version_mask,
subscribe_extranonce,
pending_difficulty: None,
active_difficulty: None,
nonce_spaces: Vec::new(),
zero_extranonce_headers: Vec::new(),
tracked: std::array::from_fn(|_| None),
next_slot: 0,
})
}
/// Apply a control message in wire order. A true result means the caller
/// must call the hardware miner's `clear_work` before accepting reports.
pub fn control(&mut self, line: &[u8]) -> Result<bool, SessionError> {
let control = parse_control_notification(
line,
self.version_mask.is_some(),
self.subscribe_extranonce,
)
.map_err(SessionError::Pool)?;
match control {
PoolNotification::SetDifficulty(difficulty) => {
self.pending_difficulty = Some(difficulty);
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)
}
PoolNotification::SetExtranonce(subscription) => {
self.subscription = subscription;
self.nonce_spaces.clear();
self.zero_extranonce_headers.clear();
self.tracked = std::array::from_fn(|_| None);
Ok(true)
}
}
}
/// Apply a pool control message and invalidate the hardware miner's work
/// when an extranonce or version-mask change makes earlier jobs stale.
pub fn control_with_miner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
line: &[u8],
) -> Result<(), SessionError> {
if self.control(line)? {
miner.clear_work();
}
Ok(())
}
/// Allocate one unique extranonce and ASIC work ID for a pool job. The
/// caller must pass this header, target, and ID to `Bm1366Miner::submit`.
/// On `clean_jobs`, clear the hardware miner's work first. Work IDs are
/// never reused on the same chain without an explicit hardware reset.
pub fn issue_notify(&mut self, line: &[u8]) -> Result<IssuedWork, SessionError> {
let job = parse_notify(line, &self.subscription).map_err(SessionError::Pool)?;
let difficulty = self
.pending_difficulty
.or(self.active_difficulty)
.ok_or(SessionError::MissingDifficulty)?;
if self.next_slot == self.tracked.len() {
return Err(SessionError::WorkIdsExhausted);
}
let size = self.subscription.extranonce2_size;
let template = if size == 0 {
None
} else {
Some(
job.work
.nonce_zero_header(&vec![0; size], job.work.ntime)
.map_err(SessionError::Work)?,
)
};
let space_index = template.and_then(|header| {
self.nonce_spaces
.iter()
.position(|space| space.template == header)
});
if size != 0 && space_index.is_none() && self.nonce_spaces.len() == MAX_NONCE_SPACES {
return Err(SessionError::ExtranonceExhausted);
}
let extranonce2 = match space_index {
Some(index) if self.nonce_spaces[index].exhausted => {
return Err(SessionError::ExtranonceExhausted)
}
Some(index) => self.nonce_spaces[index].next[..size].to_vec(),
None => vec![0; size],
};
let header = job
.work
.nonce_zero_header(&extranonce2, job.work.ntime)
.map_err(SessionError::Work)?;
if size == 0 && self.zero_extranonce_headers.contains(&header) {
return Err(SessionError::ExtranonceExhausted);
}
let target_le = difficulty.target_le();
if job.clean_jobs {
self.tracked = std::array::from_fn(|_| None);
}
self.active_difficulty = Some(difficulty);
self.pending_difficulty = None;
let slot = self.next_slot;
self.next_slot += 1;
self.tracked[slot] = Some(TrackedWork {
job_id: job.id,
header,
target_le,
extranonce2,
ntime: job.work.ntime,
base_version: job.work.version,
});
if size == 0 {
self.zero_extranonce_headers.push(header);
} else {
let space = match space_index {
Some(index) => &mut self.nonce_spaces[index],
None => {
self.nonce_spaces.push(NonceSpace {
template: template.expect("nonzero extranonce has a template"),
next: [0; 32],
exhausted: false,
});
self.nonce_spaces.last_mut().expect("just pushed")
}
};
let mut carry = true;
for byte in space.next[..size].iter_mut().rev() {
let (new, overflow) = byte.overflowing_add(u8::from(carry));
*byte = new;
carry = overflow;
if !carry {
break;
}
}
space.exhausted = carry;
}
Ok(IssuedWork {
work_id: (slot as u8) << 3,
header,
target_le,
clean_jobs: job.clean_jobs,
})
}
/// Preserve pool-message order while dispatching one job to the hardware
/// miner. A failed dispatch consumes its ASIC work ID to avoid ambiguity
/// with any frame that may have reached the device before the error.
pub fn issue_to_miner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
line: &[u8],
) -> Result<IssuedWork, DispatchError<B::Error>> {
let issued = self.issue_notify(line).map_err(DispatchError::Session)?;
if issued.clean_jobs {
miner.clear_work();
}
if let Err(error) = miner.submit(issued.header, issued.target_le, issued.work_id) {
self.tracked[usize::from(issued.work_id >> 3)] = None;
return Err(DispatchError::Miner(error));
}
Ok(issued)
}
/// Recheck the hardware-reported share and format its pool submission.
/// This method verifies one reported nonce; it never searches for one.
pub fn submission(
&self,
share: ValidShare,
worker: &str,
request_id: u64,
) -> Result<String, SessionError> {
let tracked = self
.tracked
.get(usize::from(share.work_id >> 3))
.and_then(Option::as_ref)
.ok_or(SessionError::StaleShare)?;
if share.work_id & 7 != 0 {
return Err(SessionError::StaleShare);
}
let mut header = tracked.header;
header[..4].copy_from_slice(&share.rolled_version.to_le_bytes());
header[76..80].copy_from_slice(&share.nonce.to_le_bytes());
let hash_le = sha256d(&header);
if hash_le != share.hash_le
|| hash_le
.iter()
.rev()
.cmp(tracked.target_le.iter().rev())
.is_gt()
{
return Err(SessionError::UnverifiedShare);
}
format_submission(&Submission {
request_id,
worker,
job_id: &tracked.job_id,
extranonce2: &tracked.extranonce2,
ntime: tracked.ntime,
nonce: share.nonce,
base_version: tracked.base_version,
rolled_version: share.rolled_version,
version_mask: self.version_mask,
})
.map_err(SessionError::Submit)
}
/// Call only after the chain has actually reset and prior reports cannot
/// arrive. A pool `clean_jobs` notification alone is insufficient.
pub fn after_hardware_reset(&mut self) {
self.tracked = std::array::from_fn(|_| None);
self.next_slot = 0;
self.zero_extranonce_headers.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bytes(text: &str) -> Vec<u8> {
text.as_bytes()
.chunks_exact(2)
.map(|part| u8::from_str_radix(std::str::from_utf8(part).unwrap(), 16).unwrap())
.collect()
}
#[test]
fn captured_report_is_rechecked_and_formatted_for_pool() {
let header: [u8; 80] = bytes(concat!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
"b4213a43ae1052ebd44443068fe178e2c61ca4994846fd133addb04aab2b382c5",
"b4c74c1012e6a8f06021700000000"
))
.try_into()
.unwrap();
let hash_le: [u8; 32] =
bytes("4b5e00850cf9de9809f822f8858eda39e49996d9d40f634f1043290000000000")
.try_into()
.unwrap();
let mut target_le = [0_u8; 32];
target_le[26..28].fill(0xff);
let mut session = PoolSession::new(
Subscription {
extranonce1: vec![],
extranonce2_size: 4,
},
VersionMask::new(0x1fff_e000),
false,
)
.unwrap();
session.tracked[3] = Some(TrackedWork {
job_id: "captured-job".into(),
header,
target_le,
extranonce2: vec![0, 0, 0, 1],
ntime: u32::from_le_bytes(header[68..72].try_into().unwrap()),
base_version: 0x2000_0000,
});
let share = ValidShare {
nonce: 0xedad_ff38,
work_id: 0x18,
rolled_version: 0x2096_6000,
hash_le,
};
let submit = session.submission(share, "miner.worker", 7).unwrap();
assert!(submit.contains("\"mining.submit\""));
assert!(submit.contains("\"captured-job\""));
assert!(submit.contains("\"edadff38\",\"00966000\""));
assert_eq!(
session.submission(
ValidShare {
hash_le: [0; 32],
..share
},
"miner.worker",
8
),
Err(SessionError::UnverifiedShare)
);
assert_eq!(
session.control(
b"{\"id\":null,\"method\":\"mining.set_version_mask\",\"params\":[\"00002000\"]}"
),
Ok(true)
);
assert_eq!(
session.submission(share, "miner.worker", 8),
Err(SessionError::StaleShare)
);
}
}
+3 -60
View File
@@ -7,7 +7,7 @@ use crate::pow::VersionMask;
use crate::stratum_work::{JobError, Sha256Job};
use serde_json::Value;
pub const MAX_POOL_LINE_BYTES: usize = 131_072;
const MAX_LINE_BYTES: usize = 131_072;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PoolMessageError {
@@ -26,12 +26,6 @@ pub struct Subscription {
pub extranonce2_size: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ConfigureResult {
pub version_mask: Option<VersionMask>,
pub subscribe_extranonce: bool,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PoolNotification {
SetDifficulty(PoolDifficulty),
@@ -46,7 +40,7 @@ pub struct PoolJob {
}
fn parse_json(line: &[u8]) -> Result<Value, PoolMessageError> {
if line.len() > MAX_POOL_LINE_BYTES {
if line.len() > MAX_LINE_BYTES {
return Err(PoolMessageError::TooLarge);
}
serde_json::from_slice(line).map_err(|_| PoolMessageError::Json)
@@ -139,7 +133,7 @@ pub fn parse_configure_response(
.and_then(Value::as_object)
.ok_or(PoolMessageError::InvalidField)?;
match result.get("version-rolling") {
Some(Value::Bool(false) | Value::String(_)) => Ok(None),
Some(Value::Bool(false)) => Ok(None),
Some(Value::Bool(true)) => {
let mask = hex_u32(
result
@@ -154,44 +148,6 @@ pub fn parse_configure_response(
}
}
/// Decode both offered BIP310 extensions. An omitted extranonce extension is
/// unsupported; its notifications cannot be used without an explicit grant.
pub fn parse_configure_result(
line: &[u8],
request_id: u64,
) -> Result<ConfigureResult, PoolMessageError> {
let version_mask = parse_configure_response(line, request_id)?;
let message = parse_json(line)?;
let result = message
.get("result")
.and_then(Value::as_object)
.ok_or(PoolMessageError::InvalidField)?;
let subscribe_extranonce = match result.get("subscribe-extranonce") {
Some(Value::Bool(value)) => *value,
Some(Value::String(_)) | None => false,
_ => return Err(PoolMessageError::InvalidField),
};
Ok(ConfigureResult {
version_mask,
subscribe_extranonce,
})
}
/// Decode a matching authorization or share-submission result. A false
/// result is an ordinary pool rejection and must not count as an accept.
pub fn parse_boolean_response(line: &[u8], request_id: u64) -> Result<bool, PoolMessageError> {
let message = parse_json(line)?;
if message.get("id").and_then(Value::as_u64) != Some(request_id) {
return Err(PoolMessageError::WrongMessage);
}
match message.get("result") {
Some(Value::Bool(true)) if message.get("error").is_none_or(Value::is_null) => Ok(true),
Some(Value::Bool(false)) => Ok(false),
Some(Value::Null) if !message.get("error").is_none_or(Value::is_null) => Ok(false),
_ => Err(PoolMessageError::InvalidField),
}
}
/// Decode pool control notifications. The caller applies them in stream order:
/// difficulty to the next job, extranonce to subsequent work, and the version
/// mask immediately to all pending submissions.
@@ -293,16 +249,3 @@ pub fn parse_notify(line: &[u8], subscription: &Subscription) -> Result<PoolJob,
work,
})
}
#[cfg(test)]
mod configure_tests {
use super::*;
#[test]
fn omitted_extranonce_extension_is_unsupported() {
let line = br#"{"id":1,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000"},"error":null}"#;
let result = parse_configure_result(line, 1).unwrap();
assert!(result.version_mask.is_some());
assert!(!result.subscribe_extranonce);
}
}
-408
View File
@@ -1,408 +0,0 @@
// SPDX-License-Identifier: MIT
//! Bounded newline-framed TCP transport for Bitcoin Stratum V1 pools.
use crate::stratum_v1::MAX_POOL_LINE_BYTES;
use crate::stratum_v1::{
parse_boolean_response, parse_configure_result, parse_subscription, ConfigureResult,
PoolMessageError, Subscription,
};
use serde_json::json;
use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpStream};
use std::time::{Duration, Instant};
const MAX_EARLY_NOTIFICATIONS: usize = 32;
const MAX_EARLY_NOTIFICATION_BYTES: usize = 262_144;
const READ_SLICE: Duration = Duration::from_millis(1);
const MAX_PARTIAL_AGE: Duration = Duration::from_secs(2);
#[derive(Debug)]
pub enum WireError {
InvalidRequest,
LineTooLong,
Timeout,
Eof,
Closed,
Io(io::Error),
}
#[derive(Debug)]
pub enum HandshakeError {
Wire(WireError),
Pool(PoolMessageError),
Rejected,
TooManyNotifications,
}
pub struct PoolHandshake {
pub subscription: Subscription,
pub configure: ConfigureResult,
/// Notifications received during negotiation, in original wire order.
pub early_notifications: Vec<Vec<u8>>,
}
pub struct StratumWire {
stream: TcpStream,
buffered: Vec<u8>,
partial_started: Option<Instant>,
timeout: Duration,
write_timeout: Duration,
closed: bool,
}
impl StratumWire {
pub fn connect(address: SocketAddr, timeout: Duration) -> Result<Self, WireError> {
if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() {
return Err(WireError::InvalidRequest);
}
let stream = TcpStream::connect_timeout(&address, timeout).map_err(WireError::Io)?;
stream.set_nodelay(true).map_err(WireError::Io)?;
Ok(Self {
stream,
buffered: Vec::new(),
partial_started: None,
timeout,
write_timeout: timeout,
closed: false,
})
}
pub fn from_stream(stream: TcpStream, timeout: Duration) -> Result<Self, WireError> {
if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() {
return Err(WireError::InvalidRequest);
}
stream.set_nodelay(true).map_err(WireError::Io)?;
Ok(Self {
stream,
buffered: Vec::new(),
partial_started: None,
timeout,
write_timeout: timeout,
closed: false,
})
}
pub(crate) fn close(&mut self) {
self.closed = true;
let _ = self.stream.shutdown(Shutdown::Both);
}
pub fn is_closed(&self) -> bool {
self.closed
}
pub(crate) fn cap_write_timeout(&mut self, limit: Duration) {
self.write_timeout = self.write_timeout.min(limit);
}
fn remaining(deadline: Instant) -> Result<Duration, WireError> {
deadline
.checked_duration_since(Instant::now())
.filter(|remaining| !remaining.is_zero())
.ok_or(WireError::Timeout)
}
fn transport_error(error: io::Error) -> WireError {
match error.kind() {
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock => WireError::Timeout,
_ => WireError::Io(error),
}
}
fn read_line_before(&mut self, deadline: Instant) -> Result<Vec<u8>, WireError> {
if self.closed {
return Err(WireError::Closed);
}
loop {
if let Some(end) = self.buffered.iter().position(|byte| *byte == b'\n') {
if end + 1 > MAX_POOL_LINE_BYTES {
self.close();
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()))
};
return Ok(line);
}
if self.buffered.len() >= MAX_POOL_LINE_BYTES {
self.close();
return Err(WireError::LineTooLong);
}
let remaining = match Self::remaining(deadline) {
Ok(value) => value,
Err(error) => {
if !self.buffered.is_empty() {
self.close();
}
return Err(error);
}
};
if let Err(error) = self.stream.set_read_timeout(Some(remaining)) {
self.close();
return Err(WireError::Io(error));
}
let mut chunk = [0_u8; 4096];
match self.stream.read(&mut chunk) {
Ok(0) => {
self.close();
return Err(WireError::Eof);
}
Ok(length) => {
if self.buffered.is_empty() {
self.partial_started = Some(Instant::now());
}
self.buffered.extend_from_slice(&chunk[..length]);
}
Err(error) => {
let error = Self::transport_error(error);
if !matches!(error, WireError::Timeout) || !self.buffered.is_empty() {
self.close();
}
return Err(error);
}
}
}
}
pub fn read_line(&mut self) -> Result<Vec<u8>, WireError> {
self.read_line_before(Instant::now() + self.timeout)
}
/// Check one socket slice without coupling ASIC polling to pool silence.
/// An unfinished line has its own absolute deadline across calls.
pub fn try_read_line(&mut self) -> Result<Option<Vec<u8>>, WireError> {
if self.closed {
return Err(WireError::Closed);
}
if let Some(line) = self.try_read_line_buffered()? {
return Ok(Some(line));
}
if self
.partial_started
.is_some_and(|start| start.elapsed() >= MAX_PARTIAL_AGE)
{
self.close();
return Err(WireError::Timeout);
}
self.stream
.set_read_timeout(Some(READ_SLICE))
.map_err(WireError::Io)?;
let mut chunk = [0_u8; 4096];
match self.stream.read(&mut chunk) {
Ok(0) => {
self.close();
Err(WireError::Eof)
}
Ok(length) => {
if self.buffered.is_empty() {
self.partial_started = Some(Instant::now());
}
self.buffered.extend_from_slice(&chunk[..length]);
self.try_read_line_buffered()
}
Err(error)
if matches!(
error.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) =>
{
Ok(None)
}
Err(error) => {
self.close();
Err(WireError::Io(error))
}
}
}
fn try_read_line_buffered(&mut self) -> Result<Option<Vec<u8>>, WireError> {
if let Some(end) = self.buffered.iter().position(|byte| *byte == b'\n') {
if end + 1 > MAX_POOL_LINE_BYTES {
self.close();
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()))
};
return Ok(Some(line));
}
if self.buffered.len() >= MAX_POOL_LINE_BYTES {
self.close();
return Err(WireError::LineTooLong);
}
Ok(None)
}
fn send_line_before(&mut self, line: &[u8], deadline: Instant) -> Result<(), WireError> {
if self.closed {
return Err(WireError::Closed);
}
if line.is_empty()
|| line.len() > MAX_POOL_LINE_BYTES
|| line.last() != Some(&b'\n')
|| line[..line.len() - 1].contains(&b'\n')
{
return Err(WireError::InvalidRequest);
}
let mut sent = 0;
while sent < line.len() {
let remaining = match Self::remaining(deadline) {
Ok(value) => value,
Err(error) => {
self.close();
return Err(error);
}
};
if let Err(error) = self.stream.set_write_timeout(Some(remaining)) {
self.close();
return Err(WireError::Io(error));
}
match self.stream.write(&line[sent..]) {
Ok(0) => {
self.close();
return Err(WireError::Eof);
}
Ok(length) => sent += length,
Err(error) => {
self.close();
return Err(Self::transport_error(error));
}
}
}
Ok(())
}
pub fn send_line(&mut self, line: &[u8]) -> Result<(), WireError> {
self.send_line_before(line, Instant::now() + self.write_timeout)
}
fn read_reply(
&mut self,
request_id: u64,
deadline: Instant,
early: &mut Vec<Vec<u8>>,
early_bytes: &mut usize,
) -> Result<Vec<u8>, HandshakeError> {
loop {
let line = self
.read_line_before(deadline)
.map_err(HandshakeError::Wire)?;
let message: serde_json::Value = serde_json::from_slice(&line)
.map_err(|_| HandshakeError::Pool(PoolMessageError::Json))?;
if message.get("id").and_then(serde_json::Value::as_u64) == Some(request_id) {
return Ok(line);
}
if !message.get("id").is_none_or(serde_json::Value::is_null)
|| !matches!(
message.get("method").and_then(serde_json::Value::as_str),
Some(
"mining.set_difficulty"
| "mining.set_version_mask"
| "mining.set_extranonce"
| "mining.notify"
)
)
{
return Err(HandshakeError::Pool(PoolMessageError::WrongMessage));
}
*early_bytes += line.len();
if early.len() >= MAX_EARLY_NOTIFICATIONS || *early_bytes > MAX_EARLY_NOTIFICATION_BYTES
{
return Err(HandshakeError::TooManyNotifications);
}
early.push(line);
}
}
/// Negotiate BIP310, subscribe, and authorize in that order. The entire
/// handshake shares one absolute deadline; early notifications are kept
/// for the caller to apply before reading new pool lines.
pub fn handshake(
&mut self,
agent: &str,
worker: &str,
password: &str,
timeout: Duration,
) -> Result<PoolHandshake, HandshakeError> {
let result = self.handshake_inner(agent, worker, password, timeout);
if result.is_err() {
self.close();
}
result
}
fn handshake_inner(
&mut self,
agent: &str,
worker: &str,
password: &str,
timeout: Duration,
) -> Result<PoolHandshake, HandshakeError> {
let deadline = Instant::now()
.checked_add(timeout)
.filter(|_| !timeout.is_zero())
.ok_or(HandshakeError::Wire(WireError::InvalidRequest))?;
let subscribe = subscribe_request(2, agent).map_err(HandshakeError::Wire)?;
let authorize = authorize_request(3, worker, password).map_err(HandshakeError::Wire)?;
let mut early_notifications = Vec::new();
let mut early_bytes = 0;
self.send_line_before(configure_request(1).as_bytes(), deadline)
.map_err(HandshakeError::Wire)?;
let configure = self.read_reply(1, deadline, &mut early_notifications, &mut early_bytes)?;
let configure = parse_configure_result(&configure, 1).map_err(HandshakeError::Pool)?;
self.send_line_before(subscribe.as_bytes(), deadline)
.map_err(HandshakeError::Wire)?;
let subscription =
self.read_reply(2, deadline, &mut early_notifications, &mut early_bytes)?;
let subscription = parse_subscription(&subscription, 2).map_err(HandshakeError::Pool)?;
self.send_line_before(authorize.as_bytes(), deadline)
.map_err(HandshakeError::Wire)?;
let authorized =
self.read_reply(3, deadline, &mut early_notifications, &mut early_bytes)?;
if !parse_boolean_response(&authorized, 3).map_err(HandshakeError::Pool)? {
return Err(HandshakeError::Rejected);
}
Ok(PoolHandshake {
subscription,
configure,
early_notifications,
})
}
}
/// Offer BIP310 version rolling and extranonce updates before subscribing.
pub fn configure_request(id: u64) -> String {
json!({
"id": id,
"method": "mining.configure",
"params": [
["version-rolling", "subscribe-extranonce"],
{"version-rolling.mask": "1fffe000", "version-rolling.min-bit-count": 0}
]
})
.to_string()
+ "\n"
}
pub fn subscribe_request(id: u64, agent: &str) -> Result<String, WireError> {
if agent.is_empty() || agent.len() > 128 {
return Err(WireError::InvalidRequest);
}
Ok(json!({"id": id, "method": "mining.subscribe", "params": [agent]}).to_string() + "\n")
}
pub fn authorize_request(id: u64, worker: &str, password: &str) -> Result<String, WireError> {
if worker.is_empty() || worker.len() > 128 || password.len() > 256 {
return Err(WireError::InvalidRequest);
}
Ok(
json!({"id": id, "method": "mining.authorize", "params": [worker, password]}).to_string()
+ "\n",
)
}
+8 -277
View File
@@ -1,55 +1,21 @@
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;
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,
};
use alkane_os::stratum_v1::{parse_control_notification, parse_notify, Subscription};
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};
use std::time::Instant;
fn sample(iterations: u64, f: &mut impl FnMut()) -> Duration {
fn measure(name: &str, iterations: u64, mut f: impl FnMut()) {
let started = Instant::now();
for _ in 0..iterations {
f();
}
started.elapsed()
}
fn measure(name: &str, minimum_iterations: u64, mut f: impl FnMut()) {
for _ in 0..minimum_iterations.min(1000) {
f();
}
let mut iterations = minimum_iterations.max(1);
while sample(iterations, &mut f) < Duration::from_millis(20) && iterations < 100_000_000 {
iterations = (iterations * 2).min(100_000_000);
}
let mut measurements = [0_f64; 7];
for value in &mut measurements {
*value = sample(iterations, &mut f).as_nanos() as f64 / iterations as f64;
}
measurements.sort_by(f64::total_cmp);
let ns = measurements[measurements.len() / 2];
let ns = started.elapsed().as_nanos() as f64 / iterations as f64;
println!("BENCH {name} {ns:.3} ns/op");
}
@@ -73,24 +39,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() {
@@ -106,16 +54,6 @@ fn bench_share_verification() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_scrypt_share_verification() {
let header = [0_u8; 80];
let target = [0xff_u8; 32];
measure("scrypt_share_verification", 4, || {
black_box(verify_scrypt_header(black_box(&header), black_box(&target)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1366_work_encoding() {
@@ -125,48 +63,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() {
@@ -219,48 +115,6 @@ fn bench_stratum_submission() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_authorize_format() {
measure("stratum_authorize_format", 20_000, || {
black_box(authorize_request(black_box(3), "miner.worker", "password").unwrap());
});
}
#[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() {
@@ -292,15 +146,6 @@ fn bench_stratum_control_parse() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_configure_parse() {
let line = br#"{"id":1,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","subscribe-extranonce":true},"error":null}"#;
measure("stratum_configure_parse", 20_000, || {
black_box(parse_configure_result(black_box(line), 1).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_difficulty_target() {
@@ -311,39 +156,7 @@ fn bench_difficulty_target() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_job_issue() {
let line = serde_json::json!({
"id": null,
"method": "mining.notify",
"params": [
"job-1", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"616263", "78797a", [], "20000000", "1d00ffff", "66554433", true
]
})
.to_string();
let mut session = PoolSession::new(
Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
},
None,
false,
)
.unwrap();
session
.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
measure("stratum_job_issue", 5_000, || {
session.after_hardware_reset();
black_box(session.issue_notify(black_box(line.as_bytes())).unwrap());
});
}
struct BenchBackend {
report: Option<[u8; 11]>,
}
struct BenchBackend;
impl HardwareBackend for BenchBackend {
type Error = ();
@@ -352,13 +165,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 +188,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 +198,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 -46
View File
@@ -76,11 +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();
let mut one = [0_u8; 1];
assert_eq!(server.read(&mut one).unwrap(), 0);
reply(&mut server, &header, &[0]);
});
let mut backend = HalClient::from_stream(client).unwrap();
assert!(matches!(
@@ -94,47 +90,6 @@ fn rejects_wrong_response_sequence() {
worker.join().unwrap();
}
#[test]
fn failed_power_off_ends_backend_power_lease() {
let (client, mut server) = UnixStream::pair().unwrap();
let worker = thread::spawn(move || {
let mut header = [0_u8; 16];
server.read_exact(&mut header).unwrap();
let mut body = [0_u8; 1];
server.read_exact(&mut body).unwrap();
assert_eq!(header[5], 6);
assert_eq!(body, [0]);
reply(&mut server, &header, &[3]);
assert_eq!(server.read(&mut body).unwrap(), 0);
});
let mut backend = HalClient::from_stream(client).unwrap();
assert!(matches!(
backend.set_psu_enabled(false),
Err(HalError::Device(3))
));
worker.join().unwrap();
}
#[test]
fn malformed_temperature_response_disconnects_power_lease() {
let (client, mut server) = UnixStream::pair().unwrap();
let worker = thread::spawn(move || {
let mut header = [0_u8; 16];
server.read_exact(&mut header).unwrap();
let mut request = [0_u8; 1];
server.read_exact(&mut request).unwrap();
assert_eq!(header[5], 5);
reply(&mut server, &header, &[0, 1]);
assert_eq!(server.read(&mut request).unwrap(), 0);
});
let mut backend = HalClient::from_stream(client).unwrap();
assert!(matches!(
backend.read_temperature_mc(1),
Err(HalError::Protocol("invalid temperature response"))
));
worker.join().unwrap();
}
#[test]
fn rejects_malformed_error_response_and_poisoned_connection() {
for body in [&[4_u8][..], &[3_u8, 99][..]] {
+1 -141
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] = [
@@ -27,8 +27,6 @@ struct FakeBackend {
powered: bool,
fail_off_call: usize,
off_calls: usize,
fail_reset_call: usize,
reset_calls: usize,
report: Option<[u8; REPORT_BYTES]>,
additional_reports: Vec<[u8; REPORT_BYTES]>,
sent: Vec<u8>,
@@ -56,10 +54,6 @@ impl HardwareBackend for FakeBackend {
fn set_chain_reset(&mut self, _chain: u8, asserted: bool) -> Result<(), Self::Error> {
assert!(self.powered);
self.reset_calls += 1;
if self.reset_calls == self.fail_reset_call {
return Err("reset failed");
}
self.events
.push(if asserted { "reset-on" } else { "reset-off" });
Ok(())
@@ -124,44 +118,6 @@ fn captured_nonce_passes_a_started_miner() {
);
}
#[test]
fn real_bm1362_capture_uses_its_job_format_and_shared_report() {
// 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!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503b4213a",
"0503969b7384e1215aace8cfc65dae22d8493ad48fec0b7ac3b0ad7b4e7fb0c5",
"c0012e6a8f06021700000000"
);
let mut header = [0_u8; 80];
for (byte, pair) in header.iter_mut().zip(header_hex.as_bytes().chunks_exact(2)) {
*byte = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap();
}
let report = [
0xaa, 0x55, 0x33, 0x25, 0x0b, 0x63, 0x00, 0x18, 0x67, 0x6b, 0x95,
];
let mut backend = FakeBackend {
temperatures: vec![50_000; 3],
report: Some(report),
..Default::default()
};
{
let mut miner =
Bm1366Miner::new_for_chip(&mut backend, ChipModel::Bm1362, 0, 0, 0, 100, 80_000)
.unwrap();
miner.start().unwrap();
miner.submit(header, diff_one(), 0x18).unwrap();
let share = miner.poll().unwrap().unwrap();
assert_eq!(share.nonce, 0x630b_2533);
assert_eq!(share.work_id, 0x18);
assert_eq!(share.rolled_version, 0x2ced_6000);
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]);
}
#[test]
fn hot_or_missing_sensor_stops_power() {
let mut hot = FakeBackend {
@@ -262,99 +218,3 @@ fn failed_power_off_is_retried_on_drop() {
assert_eq!(backend.off_calls, 3);
assert!(!backend.powered);
}
#[test]
fn failed_chain_flush_powers_off_before_work_id_reuse() {
let mut backend = FakeBackend {
temperatures: vec![50_000, 50_000],
fail_reset_call: 3,
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert_eq!(
miner.reset_chain(),
Err(MinerError::Backend("reset failed"))
);
assert_eq!(
miner.submit(HEADER, diff_one(), 0),
Err(MinerError::NotRunning)
);
drop(miner);
assert!(!backend.powered);
}
#[test]
fn work_id_stays_reserved_until_confirmed_chain_reset() {
let mut backend = FakeBackend {
temperatures: vec![50_000; 6],
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner.submit(HEADER, diff_one(), 0x18).unwrap();
assert_eq!(
miner.submit(HEADER, diff_one(), 0x18),
Err(MinerError::WorkIdInUse(0x18))
);
miner.clear_work();
assert_eq!(
miner.submit(HEADER, diff_one(), 0x18),
Err(MinerError::WorkIdInUse(0x18))
);
miner.reset_chain().unwrap();
miner.submit(HEADER, diff_one(), 0x18).unwrap();
miner.stop().unwrap();
drop(miner);
assert_eq!(
backend
.events
.iter()
.filter(|event| **event == "send")
.count(),
2
);
assert!(!backend.powered);
}
#[test]
fn duplicate_work_request_still_checks_temperature() {
let mut backend = FakeBackend {
temperatures: vec![50_000, 50_000, 90_000],
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner.submit(HEADER, diff_one(), 0x18).unwrap();
assert_eq!(
miner.submit(HEADER, diff_one(), 0x18),
Err(MinerError::UnsafeTemperature(90_000))
);
drop(miner);
assert!(!backend.powered);
}
#[test]
fn unconfirmed_power_off_blocks_mining_until_shutdown_retries() {
let mut backend = FakeBackend {
temperatures: vec![50_000],
fail_off_call: 2,
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert_eq!(miner.stop(), Err("power-off did not complete"));
assert_eq!(
miner.submit(HEADER, diff_one(), 0),
Err(MinerError::Faulted)
);
assert_eq!(miner.poll(), Err(MinerError::Faulted));
assert_eq!(miner.reset_chain(), Err(MinerError::Faulted));
miner.stop().unwrap();
assert_eq!(
miner.submit(HEADER, diff_one(), 0),
Err(MinerError::NotRunning)
);
drop(miner);
assert!(!backend.powered);
}
-260
View File
@@ -1,260 +0,0 @@
// SPDX-License-Identifier: MIT
use alkane_os::miner::{Bm1366Miner, MinerError, ValidShare};
use alkane_os::pow::VersionMask;
use alkane_os::stratum_session::{DispatchError, PoolSession, SessionError};
use alkane_os::stratum_v1::Subscription;
use alkane_os::HardwareBackend;
fn session() -> PoolSession {
PoolSession::new(
Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
},
Some(VersionMask::new(0x1fff_e000).unwrap()),
true,
)
.unwrap()
}
fn notify(id: &str, clean: bool) -> String {
serde_json::json!({
"id": null,
"method": "mining.notify",
"params": [
id,
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"616263", "78797a", [], "20000000", "1d00ffff", "66554433", clean
]
})
.to_string()
}
#[test]
fn difficulty_changes_on_next_job_and_old_work_keeps_its_target() {
let mut pool = session();
assert_eq!(
pool.issue_notify(notify("early", true).as_bytes()).err(),
Some(SessionError::MissingDifficulty)
);
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
let first = pool.issue_notify(notify("first", true).as_bytes()).unwrap();
assert!(first.clean_jobs);
assert_eq!(first.work_id, 0);
assert_eq!(&first.target_le[26..28], &[0xff, 0xff]);
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[2]}"#)
.unwrap();
let second = pool
.issue_notify(notify("second", false).as_bytes())
.unwrap();
assert!(!second.clean_jobs);
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)
);
let clean = pool.issue_notify(notify("third", true).as_bytes()).unwrap();
assert!(clean.clean_jobs);
assert_eq!(clean.work_id, 16);
let old = ValidShare {
nonce: 0xedad_ff38,
work_id: first.work_id,
rolled_version: 0x2000_0000,
hash_le: [0; 32],
};
assert_eq!(
pool.submission(old, "worker", 10),
Err(SessionError::StaleShare)
);
}
#[test]
fn extranonce_change_invalidates_jobs_without_reusing_asic_ids() {
let mut pool = session();
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
let old = pool.issue_notify(notify("old", true).as_bytes()).unwrap();
assert!(pool
.control(br#"{"id":null,"method":"mining.set_extranonce","params":["aabbccdd",4]}"#)
.unwrap());
let new = pool.issue_notify(notify("new", false).as_bytes()).unwrap();
assert_eq!(new.work_id, 8);
assert_ne!(old.header, new.header);
for index in 2..32 {
let work = pool.issue_notify(notify("more", false).as_bytes()).unwrap();
assert_eq!(work.work_id, (index as u8) << 3);
}
assert_eq!(
pool.issue_notify(notify("exhausted", false).as_bytes())
.err(),
Some(SessionError::WorkIdsExhausted)
);
pool.after_hardware_reset();
assert_eq!(
pool.issue_notify(notify("after-reset", false).as_bytes())
.unwrap()
.work_id,
0
);
}
#[test]
fn zero_length_extranonce_requires_distinct_header_until_hardware_reset() {
let mut pool = PoolSession::new(
Subscription {
extranonce1: vec![1],
extranonce2_size: 0,
},
None,
false,
)
.unwrap();
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
pool.issue_notify(notify("one", true).as_bytes()).unwrap();
assert_eq!(
pool.issue_notify(notify("two", false).as_bytes()).err(),
Some(SessionError::ExtranonceExhausted)
);
let distinct = notify("two", true).replace("66554433", "66554434");
pool.issue_notify(distinct.as_bytes()).unwrap();
pool.after_hardware_reset();
pool.issue_notify(notify("three", true).as_bytes()).unwrap();
}
#[test]
fn one_byte_extranonce_restarts_only_for_a_distinct_header_template() {
let mut pool = PoolSession::new(
Subscription {
extranonce1: vec![1],
extranonce2_size: 1,
},
None,
false,
)
.unwrap();
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
for index in 0..256 {
if index != 0 && index % 32 == 0 {
pool.after_hardware_reset();
}
pool.issue_notify(notify("same", false).as_bytes()).unwrap();
}
pool.after_hardware_reset();
assert_eq!(
pool.issue_notify(notify("same", false).as_bytes()).err(),
Some(SessionError::ExtranonceExhausted)
);
let distinct = notify("new", false).replace("66554433", "66554434");
pool.issue_notify(distinct.as_bytes()).unwrap();
pool.after_hardware_reset();
for index in 0..256_u32 {
if index != 0 && index % 32 == 0 {
pool.after_hardware_reset();
}
let ntime = format!("{index:08x}");
let next = notify("fresh", false).replace("66554433", &ntime);
pool.issue_notify(next.as_bytes()).unwrap();
}
}
struct FakeBackend {
powered: bool,
sent: usize,
report: Option<[u8; 11]>,
}
impl HardwareBackend for FakeBackend {
type Error = &'static str;
fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
assert!(self.powered);
assert_eq!(&frame[..4], &[0x55, 0xaa, 0x21, 0x54]);
self.sent += 1;
Ok(())
}
fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
match self.report.take() {
Some(report) => {
frame[..11].copy_from_slice(&report);
Ok(11)
}
None => Ok(0),
}
}
fn set_chain_reset(&mut self, _chain: u8, _asserted: bool) -> Result<(), Self::Error> {
Ok(())
}
fn set_fan_target(&mut self, _fan: u8, _percent: u8) -> Result<(), Self::Error> {
Ok(())
}
fn read_temperature_mc(&mut self, _sensor: u8) -> Result<i32, Self::Error> {
Ok(50_000)
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.powered = enabled;
Ok(())
}
}
#[test]
fn pool_job_dispatch_and_version_mask_invalidation_reach_the_miner() {
let mut backend = FakeBackend {
powered: false,
sent: 0,
report: Some([
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
]),
};
{
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
let mut pool = session();
pool.control_with_miner(
&mut miner,
br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#,
)
.unwrap();
for index in 0..4 {
let work = pool
.issue_to_miner(&mut miner, notify("job", index == 0).as_bytes())
.unwrap();
assert_eq!(work.work_id, (index as u8) << 3);
}
pool.control_with_miner(
&mut miner,
br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#,
)
.unwrap();
assert_eq!(miner.poll(), Err(MinerError::StaleReport));
miner.stop().unwrap();
assert_eq!(
pool.issue_to_miner(&mut miner, notify("stopped", false).as_bytes())
.err(),
Some(DispatchError::Miner(MinerError::NotRunning))
);
}
assert!(!backend.powered);
assert_eq!(backend.sent, 4);
}
+2 -60
View File
@@ -1,9 +1,8 @@
// SPDX-License-Identifier: MIT
use alkane_os::difficulty::PoolDifficulty;
use alkane_os::stratum_v1::{
parse_boolean_response, parse_configure_response, parse_configure_result,
parse_control_notification, parse_notify, parse_subscription, PoolMessageError,
PoolNotification, Subscription,
parse_configure_response, parse_control_notification, parse_notify, parse_subscription,
PoolMessageError, PoolNotification, Subscription,
};
const SUBSCRIBE: &str =
@@ -106,63 +105,6 @@ fn version_rolling_negotiation_and_immediate_mask_change() {
);
}
#[test]
fn both_bip310_extensions_and_boolean_responses_are_checked() {
let accepted = br#"{"id":3,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","subscribe-extranonce":true},"error":null}"#;
let result = parse_configure_result(accepted, 3).unwrap();
assert_eq!(result.version_mask.unwrap().bits(), 0x1fff_e000);
assert!(result.subscribe_extranonce);
let declined =
br#"{"id":3,"result":{"version-rolling":false,"subscribe-extranonce":false},"error":null}"#;
let result = parse_configure_result(declined, 3).unwrap();
assert_eq!(result.version_mask, None);
assert!(!result.subscribe_extranonce);
let unavailable = br#"{"id":3,"result":{"version-rolling":"unavailable","subscribe-extranonce":"unsupported"},"error":null}"#;
let result = parse_configure_result(unavailable, 3).unwrap();
assert_eq!(result.version_mask, None);
assert!(!result.subscribe_extranonce);
assert_eq!(
parse_configure_result(
br#"{"id":3,"result":{"version-rolling":false},"error":null}"#,
3
),
Ok(alkane_os::stratum_v1::ConfigureResult {
version_mask: None,
subscribe_extranonce: false,
})
);
assert_eq!(
parse_configure_result(
br#"{"id":3,"result":{"version-rolling":false,"subscribe-extranonce":null},"error":null}"#,
3
),
Err(PoolMessageError::InvalidField)
);
assert_eq!(
parse_boolean_response(br#"{"id":5,"result":true,"error":null}"#, 5),
Ok(true)
);
assert_eq!(
parse_boolean_response(br#"{"id":5,"result":false,"error":[23,"stale"]}"#, 5),
Ok(false)
);
assert_eq!(
parse_boolean_response(
br#"{"id":5,"result":null,"error":[21,"Job not found",null]}"#,
5
),
Ok(false)
);
assert_eq!(
parse_boolean_response(br#"{"id":5,"result":true,"error":[23,"stale"]}"#, 5),
Err(PoolMessageError::InvalidField)
);
assert_eq!(
parse_boolean_response(br#"{"id":6,"result":true,"error":null}"#, 5),
Err(PoolMessageError::WrongMessage)
);
}
#[test]
fn difficulty_and_extranonce_notifications_validate_shape_and_negotiation() {
let difficulty = br#"{"id":null,"method":"mining.set_difficulty","params":[2048.5]}"#;
-249
View File
@@ -1,249 +0,0 @@
// SPDX-License-Identifier: MIT
use alkane_os::stratum_v1::MAX_POOL_LINE_BYTES;
use alkane_os::stratum_wire::{
authorize_request, configure_request, subscribe_request, HandshakeError, StratumWire, WireError,
};
use serde_json::Value;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::Duration;
#[test]
fn request_frames_escape_pool_credentials_and_advertise_supported_bits() {
let configure: Value = serde_json::from_str(&configure_request(1)).unwrap();
assert_eq!(configure["method"], "mining.configure");
assert_eq!(configure["params"][1]["version-rolling.mask"], "1fffe000");
assert_eq!(configure["params"][0][1], "subscribe-extranonce");
let subscribe: Value =
serde_json::from_str(&subscribe_request(2, "alkane-os/0.1").unwrap()).unwrap();
assert_eq!(subscribe["params"][0], "alkane-os/0.1");
let authorized = authorize_request(3, "worker\"name", "secret\nvalue").unwrap();
assert_eq!(authorized.as_bytes().last(), Some(&b'\n'));
let authorize: Value = serde_json::from_str(&authorized).unwrap();
assert_eq!(authorize["params"][0], "worker\"name");
assert_eq!(authorize["params"][1], "secret\nvalue");
assert!(matches!(
subscribe_request(2, ""),
Err(WireError::InvalidRequest)
));
assert!(matches!(
authorize_request(3, "", "pass"),
Err(WireError::InvalidRequest)
));
}
#[test]
fn loopback_frames_preserve_pipelined_lines_and_reject_invalid_sends() {
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"{\"id\":1}\n{\"id\":2}\n").unwrap();
let mut request = [0_u8; 3];
stream.read_exact(&mut request).unwrap();
assert_eq!(&request, b"{}\n");
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
assert_eq!(wire.read_line().unwrap(), b"{\"id\":1}\n");
assert_eq!(wire.read_line().unwrap(), b"{\"id\":2}\n");
assert!(matches!(
wire.send_line(b"bad\nline\n"),
Err(WireError::InvalidRequest)
));
wire.send_line(b"{}\n").unwrap();
server.join().unwrap();
}
#[test]
fn oversized_pool_line_poison_closes_the_connection() {
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();
let mut line = vec![b'a'; MAX_POOL_LINE_BYTES];
line.push(b'\n');
let _ = stream.write_all(&line);
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
assert!(matches!(wire.read_line(), Err(WireError::LineTooLong)));
assert!(matches!(wire.read_line(), Err(WireError::Closed)));
server.join().unwrap();
}
#[test]
fn trickled_pool_line_hits_the_absolute_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();
for byte in b"{123}\n" {
if stream.write_all(&[*byte]).is_err() {
break;
}
thread::sleep(Duration::from_millis(60));
}
});
let mut wire = StratumWire::connect(address, Duration::from_millis(130)).unwrap();
assert!(matches!(wire.read_line(), Err(WireError::Timeout)));
assert!(matches!(wire.send_line(b"{}\n"), Err(WireError::Closed)));
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();
let address = listener.local_addr().unwrap();
let (release, wait) = std::sync::mpsc::channel();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
wait.recv().unwrap();
stream
.write_all(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_millis(130)).unwrap();
assert!(matches!(wire.read_line(), Err(WireError::Timeout)));
release.send(()).unwrap();
assert_eq!(
serde_json::from_slice::<Value>(&wire.read_line().unwrap()).unwrap()["method"],
"mining.set_difficulty"
);
server.join().unwrap();
}
#[test]
fn handshake_preserves_early_notifications_and_authorizes_worker() {
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();
let mut input = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
input.read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&line).unwrap()["method"],
"mining.configure"
);
stream.write_all(b"{\"id\":1,\"result\":{\"version-rolling\":true,\"version-rolling.mask\":\"1fffe000\",\"subscribe-extranonce\":true},\"error\":null}\n").unwrap();
line.clear();
input.read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&line).unwrap()["method"],
"mining.subscribe"
);
stream.write_all(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n{\"id\":2,\"result\":[[],\"01020304\",4],\"error\":null}\n").unwrap();
line.clear();
input.read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&line).unwrap()["method"],
"mining.authorize"
);
stream
.write_all(b"{\"id\":3,\"result\":true,\"error\":null}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
let result = wire
.handshake(
"alkane-os/0.1",
"miner.worker",
"password",
Duration::from_secs(2),
)
.unwrap();
assert_eq!(result.subscription.extranonce1, [1, 2, 3, 4]);
assert_eq!(result.subscription.extranonce2_size, 4);
assert!(result.configure.subscribe_extranonce);
assert_eq!(result.configure.version_mask.unwrap().bits(), 0x1fff_e000);
assert_eq!(result.early_notifications.len(), 1);
assert_eq!(
serde_json::from_slice::<Value>(&result.early_notifications[0]).unwrap()["method"],
"mining.set_difficulty"
);
server.join().unwrap();
}
#[test]
fn rejected_worker_closes_the_handshake_connection() {
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();
let mut input = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
input.read_line(&mut line).unwrap();
stream.write_all(b"{\"id\":1,\"result\":{\"version-rolling\":false,\"subscribe-extranonce\":false},\"error\":null}\n").unwrap();
line.clear();
input.read_line(&mut line).unwrap();
stream
.write_all(b"{\"id\":2,\"result\":[[],\"01020304\",4],\"error\":null}\n")
.unwrap();
line.clear();
input.read_line(&mut line).unwrap();
stream
.write_all(b"{\"id\":3,\"result\":false,\"error\":[24,\"unauthorized\"]}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
assert!(matches!(
wire.handshake("alkane-os/0.1", "bad", "password", Duration::from_secs(2)),
Err(HandshakeError::Rejected)
));
assert!(matches!(wire.read_line(), Err(WireError::Closed)));
server.join().unwrap();
}
#[test]
fn wrong_handshake_reply_id_is_rejected_and_connection_closed() {
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();
let mut line = String::new();
BufReader::new(stream.try_clone().unwrap())
.read_line(&mut line)
.unwrap();
stream
.write_all(b"{\"id\":9,\"result\":true,\"error\":null}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
assert!(matches!(
wire.handshake(
"alkane-os/0.1",
"miner.worker",
"password",
Duration::from_secs(2)
),
Err(HandshakeError::Pool(
alkane_os::stratum_v1::PoolMessageError::WrongMessage
))
));
assert!(matches!(wire.read_line(), Err(WireError::Closed)));
server.join().unwrap();
}