Compare commits

..
24 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 befa97d82b Install Rust quality tools in CI
main-release-gate / verify-and-release (push) Failing after 1m1s
2026-10-13 11:59:11 -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
noah ab264f4923 Add measured badges and coverage reports
main-release-gate / verify-and-release (push) Failing after 8s
next-build / build (push) Successful in 8s
2026-10-13 11:45:56 -06:00
noah af8a33b1a0 Add target inventory executable for SDK images
main-release-gate / verify-and-release (push) Failing after 4s
next-build / build (push) Successful in 7s
2026-10-13 11:22:39 -06:00
noah 3ab9d1a4bf Initialize Alkane OS target matrix and release gates
main-release-gate / verify-and-release (push) Failing after 4s
next-build / build (push) Successful in 4s
2026-10-13 11:13:39 -06:00
550 changed files with 177947 additions and 2250 deletions
+5
View File
@@ -0,0 +1,5 @@
[source.crates-io]
replace-with = "vendored-sources"
[source.vendored-sources]
directory = "vendor"
+19
View File
@@ -0,0 +1,19 @@
name: completed-ci-badge
on:
workflow_run:
workflows: [main-release-gate, next-build]
types: [completed]
jobs:
publish:
runs-on: alkane-ci
permissions:
actions: read
contents: write
steps:
- uses: actions/checkout@v4
- name: Publish last completed attempt
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/last-attempt-badge.py
+97
View File
@@ -0,0 +1,97 @@
name: main-release-gate
on:
push:
branches: [main]
jobs:
verify-and-release:
runs-on: alkane-ci
permissions:
contents: write
actions: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Rust quality tools
run: rustup component add rustfmt clippy
- name: Formatting
run: cargo fmt --check
- name: Last-attempt badge checks
run: python3 ci/test-last-attempt-badge.py
- name: Benchmark history checks
run: python3 ci/test-bench-history.py
- name: Quality
run: cargo clippy --all-targets --locked -- -D warnings
- name: Build
run: cargo build --release --locked
- name: Unit and workflow tests
run: |
set -o pipefail
cargo test --locked 2>&1 | tee tests-current.txt
- name: Microbenchmarks
run: |
set -o pipefail
cargo test --release --locked -- --ignored --nocapture | tee bench-current.txt
- name: Coverage tool
run: |
rustup component add llvm-tools-preview
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
cargo install --locked cargo-llvm-cov --version 0.8.7
fi
- name: Unit test coverage
run: |
mkdir -p coverage
CARGO_TARGET_DIR=target/coverage-tests cargo llvm-cov --json \
--output-path coverage/tests.json --locked
- name: Microbenchmark coverage
run: |
CARGO_TARGET_DIR=target/coverage-bench cargo llvm-cov --json \
--output-path coverage/bench.json --locked -- --ignored
- name: Load previous main benchmark measurement
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py prepare
- name: Generate measured badges
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
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-os-metrics
path: |
badges/metrics.json
coverage/tests.json
coverage/bench.json
bench-current.txt
- name: Publish measured badges privately
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/publish-metrics.py
- name: Record private benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py publish
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-os-benchmark-site-preview
path: bench-site/index.html
- name: Pairing and simulator conformance
run: python3 ci/check-conformance.py
- name: Select release version
id: version
run: python3 ci/version.py main >> "$GITHUB_OUTPUT"
- name: Package source and benchmark result
if: steps.version.outputs.release == 'true'
run: |
mkdir -p dist
git archive --format=tar.gz --output="dist/alkane-os-${{ steps.version.outputs.version }}-source.tar.gz" HEAD
cp target/release/alkane-os dist/
cp bench-current.txt dist/
- name: Create private release
if: steps.version.outputs.release == 'true'
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
+29
View File
@@ -0,0 +1,29 @@
name: next-build
on:
push:
branches: [next]
jobs:
build:
runs-on: alkane-ci
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Build release candidate
run: cargo build --release --locked
- name: Select candidate version
id: version
run: python3 ci/version.py next >> "$GITHUB_OUTPUT"
- name: Package source and build output
if: steps.version.outputs.release == 'true'
run: |
mkdir -p dist
git archive --format=tar.gz --output="dist/alkane-os-${{ steps.version.outputs.version }}-source.tar.gz" HEAD
cp target/release/alkane-os dist/
- name: Create private prerelease
if: steps.version.outputs.release == 'true'
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
+4
View File
@@ -0,0 +1,4 @@
/target/
/dist/
/coverage/
__pycache__/
Generated
+105
View File
@@ -0,0 +1,105 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "alkane-os"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "alkane-os"
version = "0.1.0"
edition = "2021"
license = "MIT"
description = "Portable mining and tuning core for Alkane control boards"
[lib]
name = "alkane_os"
[dependencies]
serde_json = { version = "=1.0.154", features = ["arbitrary_precision"] }
[profile.release]
lto = true
codegen-units = 1
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2026 BlueFlare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+83 -2
View File
@@ -1,3 +1,84 @@
# CI badges
# Alkane OS
Machine-maintained status for the last completed main and next workflow attempts.
[![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)
![bench coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench-coverage.svg)
![lines of code](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/loc.svg)
![dependencies](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/dependencies.svg)
![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)
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
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 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.
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 fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
python3 ci/check-conformance.py
```
The last command currently fails because simulator and device evidence are
still pending. It is a release gate, not a unit test.
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.
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="157" height="20" role="img" aria-label="bench coverage: 11.0%"><rect width="110" height="20" rx="3" fill="#555"/><rect x="110" width="47" height="20" rx="3" fill="#dfb317"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="55.0" y="14">bench coverage</text><text x="133.5" y="14">11.0%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="157" height="20" role="img" aria-label="bench coverage: 32.6%"><rect width="110" height="20" rx="3" fill="#555"/><rect x="110" width="47" height="20" rx="3" fill="#dfb317"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="55.0" y="14">bench coverage</text><text x="133.5" y="14">32.6%</text></g></svg>

Before

Width:  |  Height:  |  Size: 397 B

After

Width:  |  Height:  |  Size: 397 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="150" height="20" role="img" aria-label="bench: +0.0% vs prev"><rect width="47" height="20" rx="3" fill="#555"/><rect x="47" width="103" height="20" rx="3" fill="#007ec6"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="23.5" y="14">bench</text><text x="98.5" y="14">+0.0% vs prev</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="143" height="20" role="img" aria-label="bench: baseline set"><rect width="47" height="20" rx="3" fill="#555"/><rect x="47" width="96" height="20" rx="3" fill="#007ec6"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="23.5" y="14">bench</text><text x="95.0" y="14">baseline set</text></g></svg>

Before

Width:  |  Height:  |  Size: 393 B

After

Width:  |  Height:  |  Size: 390 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20" role="img" aria-label="coverage: 85.7%"><rect width="68" height="20" rx="3" fill="#555"/><rect x="68" width="47" height="20" rx="3" fill="#4c1"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="34.0" y="14">coverage</text><text x="91.5" y="14">85.7%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20" role="img" aria-label="coverage: 69.6%"><rect width="68" height="20" rx="3" fill="#555"/><rect x="68" width="47" height="20" rx="3" fill="#dfb317"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="34.0" y="14">coverage</text><text x="91.5" y="14">69.6%</text></g></svg>

Before

Width:  |  Height:  |  Size: 379 B

After

Width:  |  Height:  |  Size: 382 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="122" height="20" role="img" aria-label="dependencies: 60"><rect width="96" height="20" rx="3" fill="#555"/><rect x="96" width="26" height="20" rx="3" fill="#007ec6"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="48.0" y="14">dependencies</text><text x="109.0" y="14">60</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20" role="img" aria-label="dependencies: 0"><rect width="96" height="20" rx="3" fill="#555"/><rect x="96" width="19" height="20" rx="3" fill="#007ec6"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="48.0" y="14">dependencies</text><text x="105.5" y="14">0</text></g></svg>

Before

Width:  |  Height:  |  Size: 385 B

After

Width:  |  Height:  |  Size: 383 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="150" height="20" role="img" aria-label="lines of code: 20.4K"><rect width="103" height="20" rx="3" fill="#555"/><rect x="103" width="47" height="20" rx="3" fill="#007ec6"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="51.5" y="14">lines of code</text><text x="126.5" y="14">20.4K</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="136" height="20" role="img" aria-label="lines of code: 485"><rect width="103" height="20" rx="3" fill="#555"/><rect x="103" width="33" height="20" rx="3" fill="#007ec6"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="51.5" y="14">lines of code</text><text x="119.5" y="14">485</text></g></svg>

Before

Width:  |  Height:  |  Size: 395 B

After

Width:  |  Height:  |  Size: 391 B

+8 -39
View File
@@ -1,45 +1,14 @@
{
"tests": 252,
"line_coverage_pct": 85.7,
"bench_coverage_pct": 11.0,
"tests": 2,
"line_coverage_pct": 69.6,
"bench_coverage_pct": 32.6,
"bench_ns_per_op": {
"bm1362_commands": 118.822,
"bm1362_job_encoding": 146.111,
"bm1362_work_encoding": 143.098,
"bm1366_captured_report_poll": 651.914,
"bm1366_report_decode": 54.195,
"bm1366_session_cycle": 178.176,
"bm1366_work_encoding": 140.373,
"bm13xx_crc16": 153.906,
"bm13xx_crc5": 25.409,
"difficulty_target": 330.048,
"hal_socket_exchange": 15816.499,
"power_policy": 0.478,
"scrypt_share_verification": 193545.438,
"share_verification": 554.416,
"stratum_accept_parse": 184.312,
"stratum_authorize_format": 288.78,
"stratum_configure_format": 497.344,
"stratum_configure_parse": 731.367,
"stratum_control_parse": 275.494,
"stratum_header": 2927.859,
"stratum_job_issue": 1931.006,
"stratum_notify_parse": 734.993,
"stratum_socket_round_trip": 16695.255,
"stratum_submission": 241.16,
"stratum_subscribe_format": 243.119,
"stratum_subscription_parse": 397.224,
"target_matrix": 18.798
"power_policy": 0.686,
"target_matrix": 33.929
},
"bench_improvement_pct": 0.01469655302288628,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 20375,
"dependencies": 60,
"bench_improvement_pct": null,
"lines_of_code": 485,
"dependencies": 0,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="80" height="20" role="img" aria-label="tests: 252"><rect width="47" height="20" rx="3" fill="#555"/><rect x="47" width="33" height="20" rx="3" fill="#4c1"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="23.5" y="14">tests</text><text x="63.5" y="14">252</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="66" height="20" role="img" aria-label="tests: 2"><rect width="47" height="20" rx="3" fill="#555"/><rect x="47" width="19" height="20" rx="3" fill="#4c1"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="23.5" y="14">tests</text><text x="56.5" y="14">2</text></g></svg>

Before

Width:  |  Height:  |  Size: 368 B

After

Width:  |  Height:  |  Size: 364 B

+54
View File
@@ -0,0 +1,54 @@
# SPDX-License-Identifier: MIT
"""Write small badge artifacts to the private Gitea CI badge branch."""
import base64
import json
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
BADGE_BRANCH = "ci-badges"
def request_json(url: str, token: str, method: str = "GET",
payload: dict | None = None) -> dict:
body = None if payload is None else json.dumps(payload).encode()
request = Request(url, data=body, method=method,
headers={"Authorization": f"token {token}",
"Content-Type": "application/json"})
with urlopen(request, timeout=20) as response:
return json.load(response)
def publish_file(api: str, repo: str, filename: str, data: bytes,
token: str, message: str, max_bytes: int = 65_536) -> None:
if not filename or filename.startswith("/") or any(
part in ("", ".", "..") for part in filename.split("/")):
raise ValueError("invalid badge path")
if len(data) > max_bytes:
raise ValueError("artifact exceeds size limit")
path = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}"
encoded = base64.b64encode(data).decode("ascii")
for attempt in range(3):
try:
current = request_json(path + "?ref=" + BADGE_BRANCH, token)
if base64.b64decode(current["content"]) == data:
return
sha = current["sha"]
method = "PUT"
except HTTPError as error:
if error.code != 404:
raise
sha = None
method = "POST"
payload = {"branch": BADGE_BRANCH, "content": encoded,
"message": message + " [skip ci]"}
if sha is not None:
payload["sha"] = sha
try:
request_json(path, token, method, payload)
return
except HTTPError as error:
if error.code not in (409, 422) or attempt == 2:
raise
raise RuntimeError("badge write did not complete")
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Keep measured main-branch benchmarks in the private CI artifact branch."""
import argparse
import base64
from datetime import datetime, timezone
import html
import json
import math
import os
from pathlib import Path
import re
import subprocess
from urllib.error import HTTPError
from urllib.parse import quote
from badge_store import BADGE_BRANCH, publish_file, request_json
INDEX = "history/index.json"
MAX_INDEX_ENTRIES = 50
def read_artifact(api: str, repo: str, token: str, filename: str):
url = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}?ref={BADGE_BRANCH}"
try:
value = request_json(url, token)
except HTTPError as error:
if error.code == 404:
return None
raise
return json.loads(base64.b64decode(value["content"]))
def valid_benches(metrics: dict) -> dict[str, float]:
values = metrics.get("bench_ns_per_op")
if not isinstance(values, dict) or not values:
raise ValueError("benchmark measurements are missing")
if any(not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key)
or not isinstance(value, (float, int)) or isinstance(value, bool)
or not math.isfinite(value) or value <= 0 for key, value in values.items()):
raise ValueError("benchmark measurements are invalid")
return values
def git_distance(ancestor: str, sha: str) -> int | None:
result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"),
capture_output=True, text=True, check=False)
if result.returncode != 0:
return None
ancestor_check = subprocess.run(("git", "merge-base", "--is-ancestor", ancestor, sha),
capture_output=True, check=False)
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
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
gap = distance(ancestor, sha)
if gap is not None and gap > 0:
choices.append((gap, entry))
if not choices:
return {}
return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"])
def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict:
if not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ValueError("invalid commit SHA")
valid_benches(metrics)
entries = [entry for entry in index.get("entries", []) if entry.get("sha") != sha]
entries.append({"sha": sha, "timestamp": timestamp, "metrics": metrics})
return {"schema": 1, "entries": entries[-MAX_INDEX_ENTRIES:]}
def render_html(index: dict) -> str:
entries = list(reversed(index.get("entries", [])))
names = sorted({name for entry in entries
for name in valid_benches(entry["metrics"])})
rows = []
for entry in entries:
sha = entry["sha"]
if not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ValueError("invalid commit SHA in history")
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"])
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>")
headings = "".join(f"<th scope=\"col\">{html.escape(name)} (ns/op)</th>" for name in names)
return ("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">"
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
"<title>Alkane OS benchmarks</title><style>"
"body{font:16px system-ui,sans-serif;max-width:1100px;margin:2rem auto;padding:0 1rem;color:#17212b}"
"h1{font-size:2rem}p{max-width:70ch;line-height:1.5}"
"table{border-collapse:collapse;min-width:100%}th,td{padding:.5rem;border-bottom:1px solid #ccd3da;text-align:right}"
"th:first-child,td:first-child{text-align:left}th:nth-child(2),td:nth-child(2){text-align:left}"
"th{background:#edf2f6;position:sticky;top:0}a{color:#145a9a}"
".scroll{overflow-x:auto}small{color:#55616d}</style></head><body>"
"<h1>Alkane OS microbenchmarks</h1>"
"<p>Measured on main CI. Lower ns/op is faster. Results depend on runner load and are "
"not board performance. A new benchmark has no earlier comparison.</p>"
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>{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"))
args = parser.parse_args()
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
sha = os.environ["GITHUB_SHA"]
index = read_artifact(api, repo, token, INDEX) or {"schema": 1, "entries": []}
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)
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
metrics = json.loads(Path("badges/metrics.json").read_text())
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
index = updated_index(index, sha, metrics, timestamp)
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
publish_file(api, repo, f"history/{sha}.json", record, token,
"Record Alkane OS benchmarks", max_bytes=1_048_576)
publish_file(api, repo, INDEX, json.dumps(index, indent=2).encode() + b"\n",
token, "Update Alkane OS benchmark index", max_bytes=1_048_576)
Path("bench-site").mkdir(exist_ok=True)
Path("bench-site/index.html").write_text(render_html(index))
print(f"Recorded benchmarks for {sha[:10]}")
if __name__ == "__main__":
main()
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Fail the final release gate until every target has traceable evidence."""
import json
import pathlib
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 = ("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")
+763
View File
@@ -0,0 +1,763 @@
{
"schema": 1,
"boards": [
"am335x-bb",
"zynq-7010",
"cv1835",
"a113d",
"allwinner-h3",
"allwinner-h6",
"allwinner-h616"
],
"chips": [
"BM1384",
"BM1387",
"BM1360",
"BM1362",
"BM1366",
"BM1368",
"BM1370",
"BM1396",
"BM1397",
"BM1398",
"BM1489",
"BM1491",
"BM1746",
"KF1950",
"ID-1968",
"ID-1980",
"ID-1990"
],
"vendors": {
"am335x-bb": "bitmain",
"zynq-7010": "bitmain",
"cv1835": "bitmain",
"a113d": "bitmain",
"allwinner-h3": "whatsminer",
"allwinner-h6": "whatsminer",
"allwinner-h616": "whatsminer",
"BM1384": "bitmain",
"BM1387": "bitmain",
"BM1360": "bitmain",
"BM1362": "bitmain",
"BM1366": "bitmain",
"BM1368": "bitmain",
"BM1370": "bitmain",
"BM1396": "bitmain",
"BM1397": "bitmain",
"BM1398": "bitmain",
"BM1489": "bitmain",
"BM1491": "bitmain",
"BM1746": "bitmain",
"KF1950": "whatsminer",
"ID-1968": "whatsminer",
"ID-1980": "whatsminer",
"ID-1990": "whatsminer"
},
"targets": [
{
"board": "am335x-bb",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "KF1950",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "ID-1968",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "ID-1980",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "ID-1990",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "KF1950",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "ID-1968",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "ID-1980",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "ID-1990",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "KF1950",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "ID-1968",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "ID-1980",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "ID-1990",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
}
]
}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
# 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
WORKFLOWS = {"main.yml": "main", "next.yml": "next"}
def badge(branch: str, conclusion: str, run_id: int) -> bytes:
passed = conclusion == "success"
word = "pass" if passed else "fail"
color = "#2ea043" if passed else "#d1242f"
title = f"CI {branch}: last completed attempt {word} (run {run_id})"
return (f'<svg xmlns="http://www.w3.org/2000/svg" width="102" height="20" '
f'role="img" aria-label="{title}"><title>{title}</title>'
'<rect width="102" height="20" rx="3" fill="#555"/>'
f'<path d="M39 0h60a3 3 0 0 1 3 3v14a3 3 0 0 1-3 3H39z" fill="{color}"/>'
'<text x="20" y="14" fill="#fff" text-anchor="middle" '
'font-family="sans-serif" font-size="11">CI</text>'
f'<text x="70" y="14" fill="#fff" text-anchor="middle" '
f'font-family="sans-serif" font-size="11">{word}</text></svg>\n').encode()
def latest_completed(api: str, repo: str, workflow: str, branch: str,
token: str) -> tuple[int, str]:
path = quote(workflow, safe="")
latest = None
for page in range(1, 21):
query = urlencode({"branch": branch, "limit": 50, "page": page})
url = f"{api}/repos/{repo}/actions/workflows/{path}/runs?{query}"
runs = request_json(url, token).get("workflow_runs", [])
for run in runs:
if run.get("head_branch") != branch or run.get("status") != "completed":
continue
if run.get("conclusion") not in ("success", "failure"):
continue
candidate = (int(run["id"]), run["conclusion"])
if latest is None or candidate[0] > latest[0]:
latest = candidate
if len(runs) < 50:
break
if latest is None:
raise RuntimeError(f"no completed {branch} run found for {workflow}")
return latest
def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None:
publish_file(api, repo, f"{branch}.svg", data, token,
f"Record completed {branch} CI attempt")
def main() -> None:
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"]
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__":
main()
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Generate reviewable metrics and self-contained badges from CI measurements."""
import argparse
import html
import json
import pathlib
import re
import tomllib
def coverage(path):
data = json.loads(pathlib.Path(path).read_text())
return data["data"][0]["totals"]["lines"]["percent"]
def bench_results(path):
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):
value = float(number)
units = ("", "K", "M", "G")
index = 0
while value >= 999.5 and index < len(units) - 1:
value /= 1000
index += 1
digits = 0 if value >= 100 else 1 if value >= 10 else 2
number = f"{value:.{digits}f}"
if digits:
number = number.rstrip("0").rstrip(".")
return number + units[index]
def svg(label, value, color):
label, value = html.escape(label), html.escape(value)
lw, vw = 12 + 7 * len(label), 12 + 7 * len(value)
return (f'<svg xmlns="http://www.w3.org/2000/svg" width="{lw + vw}" height="20" '
f'role="img" aria-label="{label}: {value}">'
f'<rect width="{lw}" height="20" rx="3" fill="#555"/>'
f'<rect x="{lw}" width="{vw}" height="20" rx="3" fill="{color}"/>'
f'<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11">'
f'<text x="{lw / 2}" y="14">{label}</text>'
f'<text x="{lw + vw / 2}" y="14">{value}</text></g></svg>\n')
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--tests-output", required=True)
parser.add_argument("--tests-coverage", required=True)
parser.add_argument("--bench-output", required=True)
parser.add_argument("--bench-coverage", 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()
tests = sum(map(int, re.findall(r"test result: ok\. (\d+) passed", test_output)))
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 {}
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"))
for path in parent.rglob("*") if path.suffix in (".rs", ".py", ".sh"))
lock = tomllib.loads(pathlib.Path("Cargo.lock").read_text())
dependencies = sum(item["name"] != "alkane-os" for item in lock["package"])
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,
"lines_of_code": loc, "dependencies": dependencies,
"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 = {
"tests": ("tests", str(tests), "#4c1"),
"coverage": ("coverage", f"{line_coverage:.1f}%", "#4c1" if line_coverage >= 80 else "#dfb317"),
"bench-coverage": ("bench coverage", f"{bench_coverage:.1f}%", "#4c1" if bench_coverage >= 80 else "#dfb317"),
"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", "A", "#4c1"),
"license": ("license", "MIT", "#007ec6"),
}
for name, (label, value, color) in badges.items():
pathlib.Path(f"badges/{name}.svg").write_text(svg(label, value, color))
print(json.dumps(metrics))
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish measured main-branch metric badges to the private badge branch."""
import os
from pathlib import Path
from badge_store import publish_file
ROOT = Path(__file__).resolve().parents[1]
NAMES = ("tests", "coverage", "bench", "bench-coverage", "loc",
"dependencies", "quality", "license")
def main() -> None:
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
for name in NAMES:
data = (ROOT / "badges" / f"{name}.svg").read_bytes()
if not data.lstrip().startswith(b"<svg"):
raise ValueError(f"invalid {name} SVG")
publish_file(api, repo, f"badges/{name}.svg", data, token,
f"Update measured {name} badge")
data = (ROOT / "badges/metrics.json").read_bytes()
publish_file(api, repo, "badges/metrics.json", data, token,
"Update measured badge data")
print(f"Published {len(NAMES)} measured badge SVGs and metrics.json")
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Create one Gitea release and attach files using the runner's scoped token."""
import json
import os
import pathlib
import sys
import urllib.error
import urllib.parse
import urllib.request
def request(url, payload, content_type):
headers = {
"Authorization": "token " + os.environ["GITEA_TOKEN"],
"Content-Type": content_type,
}
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, *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:
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__":
main()
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Exercise benchmark history selection and safe site rendering."""
import sys
from pathlib import Path
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
from bench_history import previous_measurement, render_html, updated_index
class HistoryTests(unittest.TestCase):
def test_retry_uses_previous_commit(self):
first = "a" * 40
second = "b" * 40
index = {"schema": 1, "entries": [
{"sha": first, "timestamp": "2026-01-01T00:00:00+00:00",
"metrics": {"bench_ns_per_op": {"hash": 10.0}}},
{"sha": second, "timestamp": "2026-01-02T00:00:00+00:00",
"metrics": {"bench_ns_per_op": {"hash": 8.0}}}]}
self.assertEqual(previous_measurement(index, second,
lambda ancestor, sha: 1 if ancestor == first else None),
{"hash": 10.0})
updated = updated_index(index, second, {"bench_ns_per_op": {"hash": 7.5}},
"2026-01-03T00:00:00+00:00")
self.assertEqual(len(updated["entries"]), 2)
self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5)
def test_invalid_measurement_and_sha_rejected(self):
with self.assertRaises(ValueError):
updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now")
with self.assertRaises(ValueError):
updated_index({}, "a" * 40, {"bench_ns_per_op": {"hash": -1}}, "now")
def test_site_escapes_history_content(self):
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
"metrics": {"bench_ns_per_op": {"hash": 10.0}}}
page = render_html({"entries": [entry]})
self.assertIn("&lt;script&gt;", page)
self.assertNotIn("<script>", page)
self.assertIn("10.000", page)
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check that queued CI runs do not displace the last completed result."""
import importlib.util
from pathlib import Path
from unittest.mock import patch
import xml.etree.ElementTree as ET
from badge_store import publish_file
path = Path(__file__).with_name("last-attempt-badge.py")
spec = importlib.util.spec_from_file_location("last_attempt_badge", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def runs(_url, _token):
return {"workflow_runs": [
{"id": 105, "head_branch": "main", "status": "completed", "conclusion": "cancelled"},
{"id": 104, "head_branch": "main", "status": "queued", "conclusion": None},
{"id": 103, "head_branch": "main", "status": "completed", "conclusion": "failure"},
{"id": 102, "head_branch": "main", "status": "completed", "conclusion": "success"},
]}
with patch.object(module, "request_json", runs):
assert module.latest_completed("https://example.invalid/api/v1", "owner/repo",
"main.yml", "main", "token") == (103, "failure")
svg = module.badge("main", "failure", 103)
root = ET.fromstring(svg)
assert root.attrib["aria-label"] == "CI main: last completed attempt fail (run 103)"
assert b">fail</text>" in svg
assert b"#d1242f" in svg
assert b">pass</text>" in module.badge("next", "success", 108)
for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"):
try:
publish_file("https://example.invalid/api/v1", "owner/repo", invalid,
b"<svg/>", "token", "test")
except ValueError:
pass
else:
raise AssertionError(f"unsafe badge path accepted: {invalid}")
print("last completed CI badge: queued run ignored, pass/fail SVGs valid")
+1
View File
@@ -0,0 +1 @@
0
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Select a release tag from Git history. The major version is manual."""
import argparse
import pathlib
import re
import subprocess
def git(*args):
return subprocess.check_output(["git", *args], text=True).strip()
def versions(branch):
suffix = r"" if branch == "main" else r"-rc\.(\d+)"
pattern = re.compile(r"^v(\d+)\.(\d+)\.(\d+)" + suffix + r"$")
result = []
for tag in git("tag", "-l", "v*").splitlines():
match = pattern.fullmatch(tag)
if match:
result.append((tuple(map(int, match.groups())), tag))
return sorted(result)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("branch", choices=("main", "next"))
args = parser.parse_args()
major = int(pathlib.Path("ci/version-x.txt").read_text().strip())
finals = versions("main")
previous = finals[-1] if finals else None
if previous and previous[0][0] > major:
raise SystemExit("manual major version is behind the latest release")
if previous and previous[0][0] == major:
_, minor, patch = previous[0]
changed = git("diff", "--name-only", previous[1], "HEAD").splitlines()
if not changed:
print("release=false")
return
feature = any(path.startswith("src/") or path == "Cargo.toml" for path in changed)
minor, patch = (minor + 1, 0) if feature else (minor, patch + 1)
else:
minor, patch = (1, 0) if major == 0 else (0, 0)
base = f"v{major}.{minor}.{patch}"
if args.branch == "next":
candidates = [parts[0][3] for parts in versions("next") if parts[0][:3] == (major, minor, patch)]
tag = f"{base}-rc.{max(candidates, default=0) + 1}"
else:
tag = base
print("release=true")
print(f"tag={tag}")
print(f"version={tag[1:]}")
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: MIT
//! Exercise the SDK's host-only BM1366 HAL simulator with a captured job.
use alkane_os::hal_wire::HalClient;
use alkane_os::miner::Bm1366Miner;
use std::error::Error;
const 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,
];
fn main() -> Result<(), Box<dyn Error>> {
let path = std::env::args()
.nth(1)
.ok_or("usage: simulator_replay_probe SOCKET_PATH")?;
let mut backend = HalClient::connect(path)?;
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 BM1366 nonce report")?;
miner.stop()?;
assert_eq!(share.nonce, 0xedad_ff38);
println!("BM1366 captured report verified at difficulty 1");
Ok(())
}
@@ -1,49 +0,0 @@
{
"sha": "0c9731a8f94bfd865df59164dbb03ff1e5528fb7",
"timestamp": "2026-10-17T07:13:35+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 165.617,
"bm1362_job_encoding": 201.374,
"bm1362_work_encoding": 201.031,
"bm1366_captured_report_poll": 991.977,
"bm1366_report_decode": 83.607,
"bm1366_session_cycle": 255.529,
"bm1366_work_encoding": 207.648,
"bm13xx_crc16": 219.14,
"bm13xx_crc5": 34.822,
"difficulty_target": 656.388,
"hal_socket_exchange": 36781.484,
"power_policy": 0.877,
"scrypt_share_verification": 256913.781,
"share_verification": 887.985,
"stratum_accept_parse": 426.494,
"stratum_authorize_format": 664.446,
"stratum_configure_format": 1200.607,
"stratum_configure_parse": 1665.166,
"stratum_control_parse": 728.588,
"stratum_header": 4721.786,
"stratum_job_issue": 3712.656,
"stratum_notify_parse": 1477.922,
"stratum_socket_round_trip": 57735.305,
"stratum_submission": 551.557,
"stratum_subscribe_format": 583.6,
"stratum_subscription_parse": 928.84,
"target_matrix": 31.78
},
"bench_improvement_pct": 10.177633367079036,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5780,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "148a0ce5e4daa4582a7a34489fe47a56dd95ca2e",
"timestamp": "2026-10-17T07:08:13+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 129.337,
"bm1362_job_encoding": 152.174,
"bm1362_work_encoding": 153.276,
"bm1366_captured_report_poll": 708.34,
"bm1366_report_decode": 57.134,
"bm1366_session_cycle": 183.153,
"bm1366_work_encoding": 148.746,
"bm13xx_crc16": 160.021,
"bm13xx_crc5": 26.347,
"difficulty_target": 342.74,
"hal_socket_exchange": 15917.646,
"power_policy": 0.488,
"scrypt_share_verification": 193904.781,
"share_verification": 582.904,
"stratum_accept_parse": 184.808,
"stratum_authorize_format": 324.428,
"stratum_configure_format": 504.974,
"stratum_configure_parse": 738.614,
"stratum_control_parse": 278.135,
"stratum_header": 3139.763,
"stratum_job_issue": 1898.936,
"stratum_notify_parse": 1010.965,
"stratum_socket_round_trip": 19381.315,
"stratum_submission": 271.733,
"stratum_subscribe_format": 267.703,
"stratum_subscription_parse": 435.592,
"target_matrix": 19.871
},
"bench_improvement_pct": -6.571618825769334,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5776,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "1d000e037bbbc37ba586245f04d988eeb20d2c4e",
"timestamp": "2026-10-19T02:49:25+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 242.157,
"bm1362_job_encoding": 286.811,
"bm1362_work_encoding": 236.946,
"bm1366_captured_report_poll": 1427.465,
"bm1366_report_decode": 93.29,
"bm1366_session_cycle": 408.666,
"bm1366_work_encoding": 338.106,
"bm13xx_crc16": 313.61,
"bm13xx_crc5": 44.221,
"difficulty_target": 1194.541,
"hal_socket_exchange": 37791.399,
"power_policy": 0.958,
"scrypt_share_verification": 322385.789,
"share_verification": 1420.128,
"stratum_accept_parse": 523.608,
"stratum_authorize_format": 787.622,
"stratum_configure_format": 2076.944,
"stratum_configure_parse": 1829.266,
"stratum_control_parse": 796.057,
"stratum_header": 5512.653,
"stratum_job_issue": 4009.455,
"stratum_notify_parse": 1744.167,
"stratum_socket_round_trip": 66408.86,
"stratum_submission": 736.476,
"stratum_subscribe_format": 767.041,
"stratum_subscription_parse": 1417.268,
"target_matrix": 46.073
},
"bench_improvement_pct": -5.355437076345111,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5802,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,38 +0,0 @@
{
"sha": "1d0c275a043d3067cc7d2d0d617c1b5de815b9bd",
"timestamp": "2026-10-17T04:01:28+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 165.354,
"bm1362_job_encoding": 200.286,
"bm1366_report_decode": 83.727,
"bm1366_session_cycle": 223.244,
"bm1366_work_encoding": 209.351,
"difficulty_target": 661.52,
"power_policy": 0.825,
"scrypt_share_verification": 270686.164,
"share_verification": 958.951,
"stratum_authorize_format": 683.429,
"stratum_configure_parse": 1641.642,
"stratum_control_parse": 604.253,
"stratum_header": 5196.406,
"stratum_job_issue": 4004.139,
"stratum_notify_parse": 1463.534,
"stratum_submission": 520.837,
"target_matrix": 30.431
},
"bench_improvement_pct": 12.990854943787838,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "23a67af7db1c59d48ed052d2f399f53852fba7fd",
"timestamp": "2026-10-17T06:22:39+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 118.466,
"bm1362_job_encoding": 141.095,
"bm1362_work_encoding": 140.218,
"bm1366_captured_report_poll": 619.37,
"bm1366_report_decode": 54.631,
"bm1366_session_cycle": 174.583,
"bm1366_work_encoding": 140.707,
"bm13xx_crc16": 154.111,
"bm13xx_crc5": 25.45,
"difficulty_target": 330.927,
"hal_socket_exchange": 16029.276,
"power_policy": 0.488,
"scrypt_share_verification": 193320.875,
"share_verification": 577.433,
"stratum_accept_parse": 181.167,
"stratum_authorize_format": 287.414,
"stratum_configure_format": 488.179,
"stratum_configure_parse": 703.635,
"stratum_control_parse": 263.262,
"stratum_header": 2946.961,
"stratum_job_issue": 1830.304,
"stratum_notify_parse": 743.751,
"stratum_socket_round_trip": 16392.885,
"stratum_submission": 270.776,
"stratum_subscribe_format": 259.584,
"stratum_subscription_parse": 404.322,
"target_matrix": 18.848
},
"bench_improvement_pct": -2.5965982435089954,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5776,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "361a6f45872bac472719eb1205440627734b9dc0",
"timestamp": "2026-10-19T02:42:52+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 232.262,
"bm1362_job_encoding": 268.042,
"bm1362_work_encoding": 293.119,
"bm1366_captured_report_poll": 1005.482,
"bm1366_report_decode": 107.082,
"bm1366_session_cycle": 342.536,
"bm1366_work_encoding": 318.703,
"bm13xx_crc16": 294.818,
"bm13xx_crc5": 43.289,
"difficulty_target": 909.418,
"hal_socket_exchange": 41358.24,
"power_policy": 0.916,
"scrypt_share_verification": 363389.156,
"share_verification": 1773.295,
"stratum_accept_parse": 543.03,
"stratum_authorize_format": 858.969,
"stratum_configure_format": 1298.086,
"stratum_configure_parse": 2120.089,
"stratum_control_parse": 607.363,
"stratum_header": 6954.921,
"stratum_job_issue": 5228.494,
"stratum_notify_parse": 2059.438,
"stratum_socket_round_trip": 45648.118,
"stratum_submission": 727.713,
"stratum_subscribe_format": 731.331,
"stratum_subscription_parse": 1136.976,
"target_matrix": 41.489
},
"bench_improvement_pct": -18.46436035258768,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5802,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "484f479b90eff4fcc7772d323ff4c9b6a4b93771",
"timestamp": "2026-11-12T22:58:16+00:00",
"metrics": {
"tests": 252,
"line_coverage_pct": 85.7,
"bench_coverage_pct": 11.0,
"bench_ns_per_op": {
"bm1362_commands": 275.944,
"bm1362_job_encoding": 312.568,
"bm1362_work_encoding": 326.845,
"bm1366_captured_report_poll": 1718.903,
"bm1366_report_decode": 135.625,
"bm1366_session_cycle": 378.843,
"bm1366_work_encoding": 325.481,
"bm13xx_crc16": 331.899,
"bm13xx_crc5": 62.62,
"difficulty_target": 861.822,
"hal_socket_exchange": 33430.247,
"power_policy": 1.164,
"scrypt_share_verification": 406989.328,
"share_verification": 1563.182,
"stratum_accept_parse": 666.681,
"stratum_authorize_format": 1155.103,
"stratum_configure_format": 1917.635,
"stratum_configure_parse": 2337.488,
"stratum_control_parse": 913.604,
"stratum_header": 8352.213,
"stratum_job_issue": 5823.769,
"stratum_notify_parse": 2406.618,
"stratum_socket_round_trip": 66469.58,
"stratum_submission": 865.538,
"stratum_subscribe_format": 1011.42,
"stratum_subscription_parse": 1294.617,
"target_matrix": 55.748
},
"bench_improvement_pct": null,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "Intel(R) Xeon(R) CPU E5-2620 v2 @ 2.10GHz",
"logical_cpus": 4
},
"lines_of_code": 20375,
"dependencies": 60,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,38 +0,0 @@
{
"sha": "5aab1e0131f1b86ef568c59e06a1d68b39a97dc7",
"timestamp": "2026-10-17T01:14:10+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.4,
"bench_coverage_pct": 35.2,
"bench_ns_per_op": {
"bm1362_commands": 181.12,
"bm1362_job_encoding": 212.353,
"bm1366_report_decode": 83.909,
"bm1366_session_cycle": 217.569,
"bm1366_work_encoding": 218.388,
"difficulty_target": 692.324,
"power_policy": 0.845,
"scrypt_share_verification": 298371.453,
"share_verification": 934.966,
"stratum_authorize_format": 783.436,
"stratum_configure_parse": 1568.098,
"stratum_control_parse": 852.454,
"stratum_header": 5480.384,
"stratum_job_issue": 3591.099,
"stratum_notify_parse": 1770.242,
"stratum_submission": 555.39,
"target_matrix": 34.08
},
"bench_improvement_pct": -1.2856187431122177,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5227,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,39 +0,0 @@
{
"sha": "5faeb774113d09d150ad8cfa5bee3951fae0d8e8",
"timestamp": "2026-10-17T04:02:08+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 118.16,
"bm1362_job_encoding": 140.788,
"bm1366_report_decode": 54.245,
"bm1366_session_cycle": 154.963,
"bm1366_work_encoding": 141.589,
"difficulty_target": 323.774,
"power_policy": 0.461,
"scrypt_share_verification": 186319.641,
"share_verification": 550.887,
"stratum_authorize_format": 294.061,
"stratum_configure_parse": 711.528,
"stratum_control_parse": 254.993,
"stratum_header": 2969.331,
"stratum_job_issue": 1825.709,
"stratum_notify_parse": 689.88,
"stratum_submission": 249.138,
"target_matrix": 19.153
},
"bench_improvement_pct": null,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "871a2cd3f782bbe4ca171fb89f4a9a546e07e0d7",
"timestamp": "2026-10-19T03:52:23+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 120.796,
"bm1362_job_encoding": 141.136,
"bm1362_work_encoding": 143.088,
"bm1366_captured_report_poll": 638.604,
"bm1366_report_decode": 54.562,
"bm1366_session_cycle": 174.175,
"bm1366_work_encoding": 144.601,
"bm13xx_crc16": 155.011,
"bm13xx_crc5": 25.634,
"difficulty_target": 333.155,
"hal_socket_exchange": 15028.565,
"power_policy": 0.478,
"scrypt_share_verification": 188387.836,
"share_verification": 576.683,
"stratum_accept_parse": 182.574,
"stratum_authorize_format": 298.237,
"stratum_configure_format": 565.741,
"stratum_configure_parse": 717.721,
"stratum_control_parse": 257.534,
"stratum_header": 2940.601,
"stratum_job_issue": 1793.692,
"stratum_notify_parse": 697.719,
"stratum_socket_round_trip": 15954.266,
"stratum_submission": 252.056,
"stratum_subscribe_format": 258.863,
"stratum_subscription_parse": 429.497,
"target_matrix": 18.526
},
"bench_improvement_pct": 0.9487568131159643,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5837,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,27 +0,0 @@
{
"sha": "a2d03658137b3426d3feb0311dc74640a2a4a9fd",
"timestamp": "2026-10-16T07:36:30+00:00",
"metrics": {
"tests": 30,
"line_coverage_pct": 86.5,
"bench_coverage_pct": 46.9,
"bench_ns_per_op": {
"bm1366_session_cycle": 153.229,
"bm1366_work_encoding": 160.908,
"power_policy": 0.616,
"bm1366_report_decode": 57.895,
"difficulty_target": 351.668,
"stratum_control_parse": 411.535,
"share_verification": 701.448,
"target_matrix": 20.303,
"stratum_header": 3184.797,
"stratum_notify_parse": 792.362,
"stratum_submission": 463.577
},
"bench_improvement_pct": null,
"lines_of_code": 2458,
"dependencies": 11,
"code_quality": "A",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "a4f499ce124412ddd34d42b8375c5625c6a64f3b",
"timestamp": "2026-10-17T15:28:32+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 120.203,
"bm1362_job_encoding": 142.7,
"bm1362_work_encoding": 142.153,
"bm1366_captured_report_poll": 649.73,
"bm1366_report_decode": 55.762,
"bm1366_session_cycle": 179.294,
"bm1366_work_encoding": 144.509,
"bm13xx_crc16": 158.162,
"bm13xx_crc5": 26.395,
"difficulty_target": 336.608,
"hal_socket_exchange": 15741.728,
"power_policy": 0.491,
"scrypt_share_verification": 198707.742,
"share_verification": 584.64,
"stratum_accept_parse": 182.362,
"stratum_authorize_format": 299.346,
"stratum_configure_format": 501.471,
"stratum_configure_parse": 708.574,
"stratum_control_parse": 260.388,
"stratum_header": 3092.729,
"stratum_job_issue": 1895.633,
"stratum_notify_parse": 709.715,
"stratum_socket_round_trip": 16433.906,
"stratum_submission": 246.741,
"stratum_subscribe_format": 253.29,
"stratum_subscription_parse": 415.463,
"target_matrix": 19.494
},
"bench_improvement_pct": 9.825072287666742,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5796,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "ae7745772ae51cc196a60bd433b3d933ed512eae",
"timestamp": "2026-10-19T05:01:58+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 280.556,
"bm1362_job_encoding": 331.654,
"bm1362_work_encoding": 279.539,
"bm1366_captured_report_poll": 1519.435,
"bm1366_report_decode": 133.258,
"bm1366_session_cycle": 447.576,
"bm1366_work_encoding": 269.042,
"bm13xx_crc16": 341.921,
"bm13xx_crc5": 55.941,
"difficulty_target": 1096.821,
"hal_socket_exchange": 46202.277,
"power_policy": 1.47,
"scrypt_share_verification": 497556.016,
"share_verification": 1543.566,
"stratum_accept_parse": 736.83,
"stratum_authorize_format": 920.035,
"stratum_configure_format": 2086.944,
"stratum_configure_parse": 2439.709,
"stratum_control_parse": 998.693,
"stratum_header": 8158.071,
"stratum_job_issue": 6180.409,
"stratum_notify_parse": 2500.056,
"stratum_socket_round_trip": 66973.135,
"stratum_submission": 1065.12,
"stratum_subscribe_format": 1295.934,
"stratum_subscription_parse": 1605.76,
"target_matrix": 88.817
},
"bench_improvement_pct": -26.37049020368169,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5837,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "b1eb641729e77c6451bfe646288d36dd4364aa7e",
"timestamp": "2026-10-16T19:19:28+00:00",
"metrics": {
"tests": 62,
"line_coverage_pct": 88.5,
"bench_coverage_pct": 35.5,
"bench_ns_per_op": {
"bm1366_report_decode": 80.406,
"bm1366_session_cycle": 229.356,
"bm1366_work_encoding": 205.691,
"difficulty_target": 669.365,
"power_policy": 0.849,
"scrypt_share_verification": 286639.148,
"share_verification": 882.469,
"stratum_authorize_format": 697.138,
"stratum_configure_parse": 1646.612,
"stratum_control_parse": 822.593,
"stratum_header": 5209.663,
"stratum_job_issue": 3602.652,
"stratum_notify_parse": 1521.427,
"stratum_submission": 568.883,
"target_matrix": 34.432
},
"bench_improvement_pct": 5.279824105907481,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 4914,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "b9686af9c8f80feaf6dc893699e4d975a59f5949",
"timestamp": "2026-10-17T10:17:58+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 174.547,
"bm1362_job_encoding": 214.201,
"bm1362_work_encoding": 236.065,
"bm1366_captured_report_poll": 986.53,
"bm1366_report_decode": 83.521,
"bm1366_session_cycle": 279.829,
"bm1366_work_encoding": 271.038,
"bm13xx_crc16": 290.546,
"bm13xx_crc5": 49.464,
"difficulty_target": 869.765,
"hal_socket_exchange": 35832.668,
"power_policy": 1.13,
"scrypt_share_verification": 290309.086,
"share_verification": 886.321,
"stratum_accept_parse": 426.084,
"stratum_authorize_format": 680.234,
"stratum_configure_format": 1204.431,
"stratum_configure_parse": 1749.496,
"stratum_control_parse": 562.863,
"stratum_header": 4986.07,
"stratum_job_issue": 3828.325,
"stratum_notify_parse": 1794.247,
"stratum_socket_round_trip": 46774.744,
"stratum_submission": 647.318,
"stratum_subscribe_format": 601.506,
"stratum_subscription_parse": 1172.352,
"target_matrix": 34.356
},
"bench_improvement_pct": -9.836890264091615,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5787,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "c13db2a5ba9b73ac1fa5b478b7a3032d1810b336",
"timestamp": "2026-10-19T03:40:55+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 224.556,
"bm1362_job_encoding": 300.77,
"bm1362_work_encoding": 246.604,
"bm1366_captured_report_poll": 1238.499,
"bm1366_report_decode": 119.342,
"bm1366_session_cycle": 274.465,
"bm1366_work_encoding": 266.664,
"bm13xx_crc16": 309.028,
"bm13xx_crc5": 52.466,
"difficulty_target": 973.075,
"hal_socket_exchange": 37957.504,
"power_policy": 1.147,
"scrypt_share_verification": 284277.391,
"share_verification": 1321.256,
"stratum_accept_parse": 596.537,
"stratum_authorize_format": 1332.566,
"stratum_configure_format": 2032.848,
"stratum_configure_parse": 2749.941,
"stratum_control_parse": 797.614,
"stratum_header": 6383.481,
"stratum_job_issue": 5409.785,
"stratum_notify_parse": 2303.943,
"stratum_socket_round_trip": 46976.996,
"stratum_submission": 797.677,
"stratum_subscribe_format": 750.893,
"stratum_subscription_parse": 917.124,
"target_matrix": 42.305
},
"bench_improvement_pct": -4.082790698433242,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5802,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "c7cda3064ec8e51072abd598f714dbee41436f44",
"timestamp": "2026-11-16T22:05:06+00:00",
"metrics": {
"tests": 252,
"line_coverage_pct": 85.7,
"bench_coverage_pct": 11.0,
"bench_ns_per_op": {
"bm1362_commands": 118.822,
"bm1362_job_encoding": 146.111,
"bm1362_work_encoding": 143.098,
"bm1366_captured_report_poll": 651.914,
"bm1366_report_decode": 54.195,
"bm1366_session_cycle": 178.176,
"bm1366_work_encoding": 140.373,
"bm13xx_crc16": 153.906,
"bm13xx_crc5": 25.409,
"difficulty_target": 330.048,
"hal_socket_exchange": 15816.499,
"power_policy": 0.478,
"scrypt_share_verification": 193545.438,
"share_verification": 554.416,
"stratum_accept_parse": 184.312,
"stratum_authorize_format": 288.78,
"stratum_configure_format": 497.344,
"stratum_configure_parse": 731.367,
"stratum_control_parse": 275.494,
"stratum_header": 2927.859,
"stratum_job_issue": 1931.006,
"stratum_notify_parse": 734.993,
"stratum_socket_round_trip": 16695.255,
"stratum_submission": 241.16,
"stratum_subscribe_format": 243.119,
"stratum_subscription_parse": 397.224,
"target_matrix": 18.798
},
"bench_improvement_pct": 0.01469655302288628,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 20375,
"dependencies": 60,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "cc14543ced1621d4565882a311773c48f5d3614c",
"timestamp": "2026-11-12T21:22:45+00:00",
"metrics": {
"tests": 250,
"line_coverage_pct": 85.6,
"bench_coverage_pct": 11.1,
"bench_ns_per_op": {
"bm1362_commands": 225.644,
"bm1362_job_encoding": 328.479,
"bm1362_work_encoding": 309.737,
"bm1366_captured_report_poll": 1359.428,
"bm1366_report_decode": 114.877,
"bm1366_session_cycle": 389.925,
"bm1366_work_encoding": 331.867,
"bm13xx_crc16": 290.487,
"bm13xx_crc5": 54.944,
"difficulty_target": 1124.235,
"hal_socket_exchange": 45278.473,
"power_policy": 1.052,
"scrypt_share_verification": 418213.531,
"share_verification": 1196.389,
"stratum_accept_parse": 657.239,
"stratum_authorize_format": 1235.067,
"stratum_configure_format": 1755.29,
"stratum_configure_parse": 2531.665,
"stratum_control_parse": 800.904,
"stratum_header": 7417.373,
"stratum_job_issue": 5545.003,
"stratum_notify_parse": 2787.602,
"stratum_socket_round_trip": 57270.365,
"stratum_submission": 827.388,
"stratum_subscribe_format": 908.918,
"stratum_subscription_parse": 1413.105,
"target_matrix": 52.823
},
"bench_improvement_pct": -37.70168914723892,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 20288,
"dependencies": 60,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,39 +0,0 @@
{
"sha": "e83ced0e20ca4de09cdf967d051da4a4c678a7b8",
"timestamp": "2026-10-17T04:04:54+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 224.772,
"bm1362_job_encoding": 223.29,
"bm1366_report_decode": 86.828,
"bm1366_session_cycle": 238.508,
"bm1366_work_encoding": 276.985,
"difficulty_target": 741.29,
"power_policy": 1.119,
"scrypt_share_verification": 323664.125,
"share_verification": 909.603,
"stratum_authorize_format": 805.021,
"stratum_configure_parse": 1718.245,
"stratum_control_parse": 709.261,
"stratum_header": 5112.093,
"stratum_job_issue": 3901.994,
"stratum_notify_parse": 1956.082,
"stratum_submission": 556.537,
"target_matrix": 32.949
},
"bench_improvement_pct": -13.93138021432414,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "e8faf398f5fa947cedf9f6ed1d96c4b06a2bc9fe",
"timestamp": "2026-10-17T09:20:34+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 130.267,
"bm1362_job_encoding": 148.2,
"bm1362_work_encoding": 145.577,
"bm1366_captured_report_poll": 670.107,
"bm1366_report_decode": 57.707,
"bm1366_session_cycle": 182.859,
"bm1366_work_encoding": 148.095,
"bm13xx_crc16": 162.08,
"bm13xx_crc5": 26.493,
"difficulty_target": 350.947,
"hal_socket_exchange": 15814.126,
"power_policy": 0.503,
"scrypt_share_verification": 201815.781,
"share_verification": 606.034,
"stratum_accept_parse": 198.899,
"stratum_authorize_format": 469.782,
"stratum_configure_format": 606.131,
"stratum_configure_parse": 754.196,
"stratum_control_parse": 276.155,
"stratum_header": 3225.103,
"stratum_job_issue": 2011.455,
"stratum_notify_parse": 772.011,
"stratum_socket_round_trip": 21484.808,
"stratum_submission": 474.468,
"stratum_subscribe_format": 285.806,
"stratum_subscription_parse": 611.025,
"target_matrix": 24.21
},
"bench_improvement_pct": -7.99990807179019,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5787,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "e928140351830bac139efb98820e53804636c893",
"timestamp": "2026-10-21T12:04:09+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 179.018,
"bm1362_job_encoding": 205.43,
"bm1362_work_encoding": 227.761,
"bm1366_captured_report_poll": 987.287,
"bm1366_report_decode": 104.075,
"bm1366_session_cycle": 291.804,
"bm1366_work_encoding": 240.474,
"bm13xx_crc16": 321.653,
"bm13xx_crc5": 46.539,
"difficulty_target": 896.713,
"hal_socket_exchange": 34825.955,
"power_policy": 0.833,
"scrypt_share_verification": 300374.305,
"share_verification": 889.826,
"stratum_accept_parse": 460.427,
"stratum_authorize_format": 838.222,
"stratum_configure_format": 1193.101,
"stratum_configure_parse": 1507.419,
"stratum_control_parse": 595.072,
"stratum_header": 4761.147,
"stratum_job_issue": 4159.136,
"stratum_notify_parse": 1926.673,
"stratum_socket_round_trip": 50607.73,
"stratum_submission": 548.007,
"stratum_subscribe_format": 596.867,
"stratum_subscription_parse": 886.226,
"target_matrix": 32.376
},
"bench_improvement_pct": 32.8319410335087,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5841,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,38 +0,0 @@
{
"sha": "ea8030b707605cc7f974773438aab1a4f369b2ad",
"timestamp": "2026-10-17T01:17:31+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 164.352,
"bm1362_job_encoding": 201.856,
"bm1366_report_decode": 108.608,
"bm1366_session_cycle": 301.841,
"bm1366_work_encoding": 280.799,
"difficulty_target": 951.712,
"power_policy": 1.058,
"scrypt_share_verification": 347436.078,
"share_verification": 920.142,
"stratum_authorize_format": 670.238,
"stratum_configure_parse": 1618.133,
"stratum_control_parse": 675.35,
"stratum_header": 4941.007,
"stratum_job_issue": 5048.704,
"stratum_notify_parse": 1751.053,
"stratum_submission": 759.693,
"target_matrix": 32.171
},
"bench_improvement_pct": -11.111256562965927,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "ebea5f5cfd994118b7fa5b5870863df7bb3ede3a",
"timestamp": "2026-10-16T19:15:47+00:00",
"metrics": {
"tests": 62,
"line_coverage_pct": 88.5,
"bench_coverage_pct": 35.5,
"bench_ns_per_op": {
"bm1366_report_decode": 105.816,
"bm1366_session_cycle": 248.387,
"bm1366_work_encoding": 225.861,
"difficulty_target": 696.309,
"power_policy": 0.838,
"scrypt_share_verification": 269455.297,
"share_verification": 881.432,
"stratum_authorize_format": 740.798,
"stratum_configure_parse": 2156.62,
"stratum_control_parse": 754.595,
"stratum_header": 5139.92,
"stratum_job_issue": 3880.848,
"stratum_notify_parse": 2049.311,
"stratum_submission": 564.143,
"target_matrix": 31.667
},
"bench_improvement_pct": null,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 4914,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "f1b4780e2c29545f999a32d082d53d981cde1eab",
"timestamp": "2026-10-17T01:10:07+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.4,
"bench_coverage_pct": 32.9,
"bench_ns_per_op": {
"bm1366_report_decode": 85.369,
"bm1366_session_cycle": 217.528,
"bm1366_work_encoding": 211.19,
"difficulty_target": 699.086,
"power_policy": 0.833,
"scrypt_share_verification": 289038.242,
"share_verification": 1156.075,
"stratum_authorize_format": 704.473,
"stratum_configure_parse": 1625.25,
"stratum_control_parse": 597.014,
"stratum_header": 5390.022,
"stratum_job_issue": 3546.33,
"stratum_notify_parse": 2066.816,
"stratum_submission": 627.814,
"target_matrix": 32.316
},
"bench_improvement_pct": -2.9414495847373345,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5227,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "f6889940c3bc8f5f2d85ee45d992f485e2f00df9",
"timestamp": "2026-10-17T01:06:27+00:00",
"metrics": {
"tests": 62,
"line_coverage_pct": 86.7,
"bench_coverage_pct": 34.7,
"bench_ns_per_op": {
"bm1366_report_decode": 80.39,
"bm1366_session_cycle": 217.507,
"bm1366_work_encoding": 226.831,
"difficulty_target": 722.424,
"power_policy": 0.816,
"scrypt_share_verification": 268871.328,
"share_verification": 877.36,
"stratum_authorize_format": 720.309,
"stratum_configure_parse": 1798.745,
"stratum_control_parse": 608.061,
"stratum_header": 5195.553,
"stratum_job_issue": 4198.027,
"stratum_notify_parse": 1548.651,
"stratum_submission": 637.805,
"target_matrix": 32.238
},
"bench_improvement_pct": -0.8416320684715105,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5000,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
-1103
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="102" height="20" role="img" aria-label="CI main: last completed attempt fail (run 13252)"><title>CI main: last completed attempt fail (run 13252)</title><rect width="102" height="20" rx="3" fill="#555"/><path d="M39 0h60a3 3 0 0 1 3 3v14a3 3 0 0 1-3 3H39z" fill="#d1242f"/><text x="20" y="14" fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">CI</text><text x="70" y="14" fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">fail</text></svg>

Before

Width:  |  Height:  |  Size: 533 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="102" height="20" role="img" aria-label="CI next: last completed attempt pass (run 7374)"><title>CI next: last completed attempt pass (run 7374)</title><rect width="102" height="20" rx="3" fill="#555"/><path d="M39 0h60a3 3 0 0 1 3 3v14a3 3 0 0 1-3 3H39z" fill="#2ea043"/><text x="20" y="14" fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">CI</text><text x="70" y="14" fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">pass</text></svg>

Before

Width:  |  Height:  |  Size: 531 B

+149
View File
@@ -0,0 +1,149 @@
// SPDX-License-Identifier: MIT
//! BM1366 work and response framing. Nonces only come from a device or replay.
pub const WORK_BYTES: usize = 88;
pub const REPORT_BYTES: usize = 11;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NonceReport {
pub nonce: u32,
pub work_id: u8,
pub version_field: u16,
pub chip_address: u8,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReportError {
Length,
Preamble,
RegisterResponse,
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]> {
if header[76..80] != [0; 4] || work_id & 7 != 0 {
return None;
}
let mut frame = [0_u8; WORK_BYTES];
frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]);
frame[4] = work_id;
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]));
frame[50..82].copy_from_slice(&reverse_words(&header[4..36]));
frame[82..86].copy_from_slice(&header[..4]);
let checksum = crc16(&frame[2..86]);
frame[86..88].copy_from_slice(&checksum.to_be_bytes());
Some(frame)
}
/// Parse an observed nonce report; register replies must use a separate path.
pub fn decode_nonce_report(frame: &[u8]) -> Result<NonceReport, ReportError> {
if frame.len() != REPORT_BYTES {
return Err(ReportError::Length);
}
if frame[..2] != [0xaa, 0x55] {
return Err(ReportError::Preamble);
}
if frame[10] & 0x80 == 0 {
return Err(ReportError::RegisterResponse);
}
if crc5(&frame[2..]) != 0 {
return Err(ReportError::Checksum);
}
Ok(NonceReport {
nonce: u32::from_le_bytes(frame[2..6].try_into().expect("four-byte nonce")),
chip_address: frame[6],
work_id: frame[7] & 0xf8,
version_field: u16::from_be_bytes(frame[8..10].try_into().expect("version field")),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crc16_reference_vector() {
assert_eq!(crc16(b"123456789"), 0x29b1);
}
#[test]
fn captured_work_and_response() {
let header: [u8; 80] = hex_header();
let frame = encode_work(&header, 0x18).unwrap();
assert_eq!(&frame[..5], &[0x55, 0xaa, 0x21, 0x54, 0x18]);
assert_eq!(
crc16(&frame[2..86]),
u16::from_be_bytes([frame[86], frame[87]])
);
assert_eq!(&frame[10..14], &header[72..76]);
assert_eq!(&frame[82..86], &header[..4]);
assert!(encode_work(&header, 0x19).is_none());
let mut with_nonce = header;
with_nonce[76] = 1;
assert!(encode_work(&with_nonce, 0x18).is_none());
let report = [
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
];
let parsed = decode_nonce_report(&report).unwrap();
assert_eq!(parsed.nonce, 0xedad_ff38);
assert_eq!(parsed.work_id, 0x18);
assert_eq!(parsed.version_field, 0x04b3);
let mut corrupt = report;
corrupt[4] ^= 1;
assert_eq!(decode_nonce_report(&corrupt), Err(ReportError::Checksum));
}
fn hex_header() -> [u8; 80] {
let input = concat!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
"b4213a43ae1052ebd44443068fe178e2c61ca4994846fd133addb04aab2b382c5",
"b4c74c1012e6a8f06021700000000"
);
let mut header = [0_u8; 80];
for (index, bytes) in input.as_bytes().chunks_exact(2).enumerate() {
let pair = std::str::from_utf8(bytes).unwrap();
header[index] = u8::from_str_radix(pair, 16).unwrap();
}
header
}
}
+120
View File
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: MIT
//! Exact Bitcoin Stratum share target conversion; no floating point or nonce search.
use serde_json::Number;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DifficultyError {
Invalid,
OutOfRange,
}
/// A positive decimal difficulty represented exactly as numerator/denominator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PoolDifficulty {
numerator: u64,
denominator: u64,
}
impl PoolDifficulty {
pub fn from_json_number(number: &Number) -> Result<Self, DifficultyError> {
let text = number.as_str();
if text.len() > 128 || text.starts_with('-') {
return Err(DifficultyError::OutOfRange);
}
let (mantissa, exponent) = match text.split_once(['e', 'E']) {
Some((base, exponent)) => (
base,
exponent
.parse::<i32>()
.map_err(|_| DifficultyError::OutOfRange)?,
),
None => (text, 0),
};
let mut digits = Vec::with_capacity(mantissa.len());
let mut fractional = 0_i32;
let mut after_dot = false;
for byte in mantissa.bytes() {
match byte {
b'.' if !after_dot => after_dot = true,
b'0'..=b'9' => {
digits.push(byte - b'0');
if after_dot {
fractional += 1;
}
}
_ => return Err(DifficultyError::Invalid),
}
}
let first = digits
.iter()
.position(|digit| *digit != 0)
.ok_or(DifficultyError::Invalid)?;
let last = digits
.iter()
.rposition(|digit| *digit != 0)
.expect("nonzero digit");
let trailing = (digits.len() - last - 1) as i32;
let mut numerator = 0_u64;
for digit in &digits[first..=last] {
numerator = numerator
.checked_mul(10)
.and_then(|value| value.checked_add(u64::from(*digit)))
.ok_or(DifficultyError::OutOfRange)?;
}
let shift = exponent
.checked_sub(fractional)
.and_then(|value| value.checked_add(trailing))
.ok_or(DifficultyError::OutOfRange)?;
if !(-19..=19).contains(&shift) {
return Err(DifficultyError::OutOfRange);
}
let mut denominator = 1_u64;
if shift >= 0 {
for _ in 0..shift {
numerator = numerator
.checked_mul(10)
.ok_or(DifficultyError::OutOfRange)?;
}
} else {
for _ in 0..-shift {
denominator = denominator
.checked_mul(10)
.ok_or(DifficultyError::OutOfRange)?;
}
}
Ok(Self {
numerator,
denominator,
})
}
/// floor((0xFFFF << 208) / difficulty), capped at the 256-bit maximum.
/// The 320-bit intermediate permits all supported decimal denominators.
pub fn target_le(self) -> [u8; 32] {
let mut product = [0_u8; 40];
let mut carry = 0_u128;
for (index, byte) in product.iter_mut().enumerate() {
let diff_one_byte = if index == 26 || index == 27 { 0xff } else { 0 };
let value = (diff_one_byte as u128) * u128::from(self.denominator) + carry;
*byte = value as u8;
carry = value >> 8;
}
debug_assert_eq!(carry, 0);
let mut quotient = [0_u8; 40];
let mut remainder = 0_u128;
for index in (0..320).rev() {
let bit = (product[index / 8] >> (index % 8)) & 1;
remainder = (remainder << 1) | u128::from(bit);
if remainder >= u128::from(self.numerator) {
remainder -= u128::from(self.numerator);
quotient[index / 8] |= 1 << (index % 8);
}
}
if quotient[32..].iter().any(|byte| *byte != 0) {
return [0xff; 32];
}
quotient[..32].try_into().expect("256-bit quotient")
}
}
+393
View File
@@ -0,0 +1,393 @@
// SPDX-License-Identifier: MIT
//! Versioned local wire contract between Alkane OS and an SDK hardware backend.
use crate::HardwareBackend;
use std::fmt;
use std::io::{self, Read, Write};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::time::{Duration, Instant};
const MAGIC: [u8; 4] = *b"ALKH";
const VERSION: u8 = 1;
const RESPONSE: u16 = 1;
const HEADER_LEN: usize = 16;
const MAX_PAYLOAD: usize = 4096;
const IO_TIMEOUT: Duration = Duration::from_secs(2);
const SEND_FRAME: u8 = 1;
const RECEIVE_FRAME: u8 = 2;
const SET_CHAIN_RESET: u8 = 3;
const SET_FAN_TARGET: u8 = 4;
const READ_TEMPERATURE: u8 = 5;
const SET_PSU_ENABLED: u8 = 6;
#[cfg(not(target_os = "linux"))]
compile_error!("Alkane HAL sockets require Linux");
#[cfg(target_os = "linux")]
mod sys {
pub use std::ffi::{c_char as CChar, c_int as CInt, c_void as CVoid};
pub type SaFamily = u16;
pub type SocklenT = u32;
pub const AF_UNIX: CInt = 1;
pub const SOCK_STREAM: CInt = 1;
pub const SOCK_NONBLOCK: CInt = 0x800;
pub const SOCK_CLOEXEC: CInt = 0x80000;
pub const SOL_SOCKET: CInt = 1;
pub const SO_ERROR: CInt = 4;
pub const POLLOUT: i16 = 4;
pub const EAGAIN: CInt = 11;
pub const EISCONN: CInt = 106;
pub const EINPROGRESS: CInt = 115;
#[repr(C)]
pub struct SockaddrUn {
pub sun_family: SaFamily,
pub sun_path: [CChar; 108],
}
#[repr(C)]
pub struct PollFd {
pub fd: CInt,
pub events: i16,
pub revents: i16,
}
extern "C" {
pub fn socket(domain: CInt, socket_type: CInt, protocol: CInt) -> CInt;
pub fn connect(fd: CInt, address: *const CVoid, length: SocklenT) -> CInt;
pub fn poll(fds: *mut PollFd, count: usize, timeout_ms: CInt) -> CInt;
pub fn getsockopt(
fd: CInt,
level: CInt,
name: CInt,
value: *mut CVoid,
length: *mut SocklenT,
) -> CInt;
}
}
#[derive(Debug)]
pub enum HalError {
Io(io::Error),
Protocol(&'static str),
Device(u8),
FrameTooLong,
InvalidFanPercent,
}
impl fmt::Display for HalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => write!(f, "HAL I/O: {error}"),
Self::Protocol(message) => write!(f, "HAL protocol: {message}"),
Self::Device(code) => write!(f, "HAL device error: {code}"),
Self::FrameTooLong => f.write_str("HAL frame exceeds the wire limit"),
Self::InvalidFanPercent => f.write_str("HAL fan target exceeds 100 percent"),
}
}
}
impl std::error::Error for HalError {}
impl From<io::Error> for HalError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
/// Local client for the privileged board backend supplied by the SDK image.
pub struct HalClient {
stream: UnixStream,
sequence: u32,
poisoned: bool,
}
impl HalClient {
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)
}
pub fn from_stream(stream: UnixStream) -> Result<Self, HalError> {
stream.set_read_timeout(Some(IO_TIMEOUT))?;
stream.set_write_timeout(Some(IO_TIMEOUT))?;
Ok(Self {
stream,
sequence: 0,
poisoned: false,
})
}
fn exchange(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
if self.poisoned {
return Err(HalError::Protocol("connection is unusable"));
}
if payload.len() > MAX_PAYLOAD {
return Err(HalError::FrameTooLong);
}
let result = self.exchange_inner(opcode, payload);
if let Err(ref error) = result {
if !matches!(error, HalError::Device(_)) {
self.poisoned = true;
}
}
result
}
fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
let deadline = Instant::now() + IO_TIMEOUT;
self.sequence = self.sequence.wrapping_add(1);
let sequence = self.sequence;
let mut header = [0_u8; HEADER_LEN];
header[..4].copy_from_slice(&MAGIC);
header[4] = VERSION;
header[5] = opcode;
header[8..12].copy_from_slice(&sequence.to_le_bytes());
header[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
write_all_until(&mut self.stream, &header, deadline)?;
write_all_until(&mut self.stream, payload, deadline)?;
read_exact_until(&mut self.stream, &mut header, deadline)?;
if header[..4] != MAGIC || header[4] != VERSION || header[5] != opcode {
return Err(HalError::Protocol("response identity mismatch"));
}
if u16::from_le_bytes([header[6], header[7]]) != RESPONSE {
return Err(HalError::Protocol("response flag missing"));
}
if u32::from_le_bytes(header[8..12].try_into().unwrap()) != sequence {
return Err(HalError::Protocol("response sequence mismatch"));
}
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
if !(1..=MAX_PAYLOAD).contains(&length) {
return Err(HalError::Protocol("invalid response length"));
}
let mut body = vec![0_u8; length];
read_exact_until(&mut self.stream, &mut body, deadline)?;
if body[0] != 0 {
if !matches!(body[0], 1..=3) || body.len() != 1 {
return Err(HalError::Protocol("invalid error response"));
}
return Err(HalError::Device(body[0]));
}
Ok(body[1..].to_vec())
}
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
if !self.exchange(opcode, payload)?.is_empty() {
self.poisoned = true;
return Err(HalError::Protocol("unexpected response data"));
}
Ok(())
}
}
fn timeout_error() -> io::Error {
io::Error::new(io::ErrorKind::TimedOut, "HAL operation timed out")
}
fn remaining(deadline: Instant) -> io::Result<Duration> {
deadline
.checked_duration_since(Instant::now())
.filter(|duration| !duration.is_zero())
.ok_or_else(timeout_error)
}
fn write_all_until(stream: &mut UnixStream, mut data: &[u8], deadline: Instant) -> io::Result<()> {
while !data.is_empty() {
stream.set_write_timeout(Some(remaining(deadline)?))?;
match stream.write(data) {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"HAL socket closed",
))
}
Ok(count) => data = &data[count..],
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
}
Ok(())
}
fn read_exact_until(
stream: &mut UnixStream,
mut data: &mut [u8],
deadline: Instant,
) -> io::Result<()> {
while !data.is_empty() {
stream.set_read_timeout(Some(remaining(deadline)?))?;
match stream.read(data) {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"HAL socket closed",
))
}
Ok(count) => data = &mut data[count..],
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
}
Ok(())
}
fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
let bytes = path.as_os_str().as_bytes();
let max_path =
std::mem::size_of::<sys::SockaddrUn>() - std::mem::offset_of!(sys::SockaddrUn, sun_path);
if bytes.is_empty() || bytes.len() >= max_path || bytes.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid HAL socket path",
));
}
let raw = unsafe {
sys::socket(
sys::AF_UNIX,
sys::SOCK_STREAM | sys::SOCK_NONBLOCK | sys::SOCK_CLOEXEC,
0,
)
};
if raw < 0 {
return Err(io::Error::last_os_error());
}
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
let mut address: sys::SockaddrUn = unsafe { std::mem::zeroed() };
address.sun_family = sys::AF_UNIX as sys::SaFamily;
for (destination, source) in address.sun_path.iter_mut().zip(bytes) {
*destination = *source as sys::CChar;
}
let length =
(std::mem::offset_of!(sys::SockaddrUn, sun_path) + bytes.len() + 1) as sys::SocklenT;
loop {
let result = unsafe {
sys::connect(
fd.as_raw_fd(),
&address as *const _ as *const sys::CVoid,
length,
)
};
if result == 0 {
break;
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(sys::EISCONN) {
break;
}
if !matches!(
error.raw_os_error(),
Some(sys::EINPROGRESS) | Some(sys::EAGAIN)
) {
return Err(error);
}
let mut poll_fd = sys::PollFd {
fd: fd.as_raw_fd(),
events: sys::POLLOUT,
revents: 0,
};
let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32;
let polled = unsafe { sys::poll(&mut poll_fd, 1, wait.max(1)) };
if polled < 0 {
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted {
continue;
}
return Err(error);
}
if polled == 0 {
return Err(timeout_error());
}
let mut socket_error: sys::CInt = 0;
let mut socket_error_len = std::mem::size_of_val(&socket_error) as sys::SocklenT;
if unsafe {
sys::getsockopt(
fd.as_raw_fd(),
sys::SOL_SOCKET,
sys::SO_ERROR,
&mut socket_error as *mut _ as *mut sys::CVoid,
&mut socket_error_len,
)
} < 0
{
return Err(io::Error::last_os_error());
}
if socket_error != 0 {
return Err(io::Error::from_raw_os_error(socket_error));
}
if error.raw_os_error() == Some(sys::EINPROGRESS) {
break;
}
}
let stream = UnixStream::from(fd);
stream.set_nonblocking(false)?;
Ok(stream)
}
impl HardwareBackend for HalClient {
type Error = HalError;
fn send_frame(&mut self, chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
if frame.len() > MAX_PAYLOAD - 3 {
return Err(HalError::FrameTooLong);
}
let mut body = Vec::with_capacity(frame.len() + 3);
body.push(chain);
body.extend_from_slice(&(frame.len() as u16).to_le_bytes());
body.extend_from_slice(frame);
self.empty_reply(SEND_FRAME, &body)
}
fn receive_frame(&mut self, chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
if frame.len() > MAX_PAYLOAD - 3 {
return Err(HalError::FrameTooLong);
}
let mut request = [0_u8; 3];
request[0] = chain;
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
let body = self.exchange(RECEIVE_FRAME, &request)?;
if body.len() < 2 {
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.poisoned = true;
return Err(HalError::Protocol("invalid received frame size"));
}
frame[..count].copy_from_slice(&body[2..]);
Ok(count)
}
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error> {
self.empty_reply(SET_CHAIN_RESET, &[chain, u8::from(asserted)])
}
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error> {
if percent > 100 {
return Err(HalError::InvalidFanPercent);
}
self.empty_reply(SET_FAN_TARGET, &[fan, percent])
}
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error> {
let body = self.exchange(READ_TEMPERATURE, &[sensor])?;
let bytes: [u8; 4] = match body.try_into() {
Ok(bytes) => bytes,
Err(_) => {
self.poisoned = true;
return Err(HalError::Protocol("invalid temperature response"));
}
};
Ok(i32::from_le_bytes(bytes))
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)])
}
}
+234
View File
@@ -0,0 +1,234 @@
//! Board independent policy and hardware interfaces for Alkane OS.
//!
//! 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 bm1366;
pub mod difficulty;
pub mod hal_wire;
pub mod miner;
pub mod pow;
pub mod stratum_submit;
pub mod stratum_v1;
pub mod stratum_work;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vendor {
Bitmain,
Whatsminer,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Algorithm {
Sha256,
Scrypt,
Equihash,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ControlBoard {
pub id: &'static str,
pub vendor: Vendor,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HashChip {
pub id: &'static str,
pub vendor: Vendor,
pub algorithm: Algorithm,
}
pub const CONTROL_BOARDS: [ControlBoard; 7] = [
ControlBoard {
id: "am335x-bb",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "zynq-7010",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "cv1835",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "a113d",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "allwinner-h3",
vendor: Vendor::Whatsminer,
},
ControlBoard {
id: "allwinner-h6",
vendor: Vendor::Whatsminer,
},
ControlBoard {
id: "allwinner-h616",
vendor: Vendor::Whatsminer,
},
];
pub const HASH_CHIPS: [HashChip; 17] = [
HashChip {
id: "BM1384",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1387",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1360",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1362",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1366",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1368",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1370",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1396",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1397",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1398",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1489",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Scrypt,
},
HashChip {
id: "BM1491",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Scrypt,
},
HashChip {
id: "BM1746",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Equihash,
},
HashChip {
id: "KF1950",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "ID-1968",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "ID-1980",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "ID-1990",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Target {
pub control: ControlBoard,
pub chip: HashChip,
}
impl Target {
pub fn new(control: ControlBoard, chip: HashChip) -> Option<Self> {
(control.vendor == chip.vendor).then_some(Self { control, chip })
}
}
/// Every same-vendor theoretical pairing is in scope for Alkane OS.
pub fn target_matrix() -> impl Iterator<Item = Target> {
CONTROL_BOARDS.into_iter().flat_map(|control| {
HASH_CHIPS
.into_iter()
.filter_map(move |chip| Target::new(control, chip))
})
}
/// Hardware operations implemented by a board backend in the SDK image.
/// The methods deliberately expose no assumed UART, FPGA or Bitmicro layout.
pub trait HardwareBackend {
type Error;
fn send_frame(&mut self, chain: u8, frame: &[u8]) -> Result<(), Self::Error>;
fn receive_frame(&mut self, chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error>;
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error>;
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error>;
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error>;
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error>;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PowerDecision {
Hold,
Stop,
}
/// A safe starting policy: no hashing while temperature is unknown or unsafe.
/// Board-specific thresholds will come from measured, revision-specific data.
pub fn power_decision(temperature_mc: Option<i32>, max_mc: i32) -> PowerDecision {
match temperature_mc {
Some(value) if value < max_mc => PowerDecision::Hold,
_ => PowerDecision::Stop,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_theoretical_same_vendor_targets_are_included() {
let targets: Vec<_> = target_matrix().collect();
assert_eq!(targets.len(), 4 * 13 + 3 * 4);
assert!(targets.iter().all(|t| t.control.vendor == t.chip.vendor));
for control in CONTROL_BOARDS {
for chip in HASH_CHIPS {
assert_eq!(
targets.contains(&Target { control, chip }),
control.vendor == chip.vendor
);
}
}
}
#[test]
fn unknown_or_hot_sensor_stops_power() {
assert_eq!(power_decision(None, 80_000), PowerDecision::Stop);
assert_eq!(power_decision(Some(80_000), 80_000), PowerDecision::Stop);
assert_eq!(power_decision(Some(79_999), 80_000), PowerDecision::Hold);
}
}
+20
View File
@@ -0,0 +1,20 @@
use alkane_os::target_matrix;
fn main() {
match std::env::args().nth(1).as_deref() {
Some("--list-targets") => {
println!("control_board,hash_chip,algorithm");
for target in target_matrix() {
println!(
"{},{},{:?}",
target.control.id, target.chip.id, target.chip.algorithm
);
}
}
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
_ => {
eprintln!("usage: alkane-os --list-targets | --version");
std::process::exit(2);
}
}
}
+235
View File
@@ -0,0 +1,235 @@
// SPDX-License-Identifier: MIT
//! One-chain BM1366 mining control built on the SDK hardware backend.
//! This module never searches for nonces or chooses board safety thresholds.
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(Debug, Eq, PartialEq)]
pub enum MinerError<E> {
Backend(E),
AlreadyRunning,
NotRunning,
UnsafeTemperature(i32),
InvalidWork,
InvalidReport(ReportError),
StaleReport,
BelowTarget,
}
impl<E: fmt::Display> fmt::Display for MinerError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
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::UnsafeTemperature(value) => write!(f, "unsafe temperature: {value} mC"),
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"),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for MinerError<E> {}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ValidShare {
pub nonce: u32,
pub work_id: u8,
pub rolled_version: u32,
pub hash_le: [u8; 32],
}
#[derive(Clone, Copy)]
struct Work {
header: [u8; 80],
target_le: [u8; 32],
id: u8,
}
pub struct Bm1366Miner<'a, B: HardwareBackend> {
backend: &'a mut B,
chain: u8,
sensor: u8,
fan: u8,
fan_percent: u8,
max_temperature_mc: i32,
running: bool,
work: [Option<Work>; 32],
}
impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
/// The caller supplies a threshold validated for this board revision.
pub fn new(
backend: &'a mut B,
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,
chain,
sensor,
fan,
fan_percent,
max_temperature_mc,
running: false,
work: [None; 32],
})
}
fn power_off(&mut self) -> Result<(), B::Error> {
self.work = [None; 32];
match self.backend.set_psu_enabled(false) {
Ok(()) => {
self.running = false;
Ok(())
}
Err(error) => {
// The backend may have left power on. Drop retries shutdown.
self.running = true;
Err(error)
}
}
}
fn check_temperature(&mut self) -> Result<(), MinerError<B::Error>> {
let value = match self.backend.read_temperature_mc(self.sensor) {
Ok(value) => value,
Err(error) => {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
};
if power_decision(Some(value), self.max_temperature_mc) == PowerDecision::Stop {
let _ = self.power_off();
return Err(MinerError::UnsafeTemperature(value));
}
Ok(())
}
pub fn start(&mut self) -> Result<(), MinerError<B::Error>> {
if self.running {
return Err(MinerError::AlreadyRunning);
}
self.power_off().map_err(MinerError::Backend)?;
self.check_temperature()?;
self.backend
.set_fan_target(self.fan, self.fan_percent)
.map_err(MinerError::Backend)?;
if let Err(error) = self.backend.set_psu_enabled(true) {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
self.running = true;
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));
}
Ok(())
}
pub fn stop(&mut self) -> Result<(), B::Error> {
self.power_off()
}
pub fn submit(
&mut self,
header: [u8; 80],
target_le: [u8; 32],
work_id: u8,
) -> Result<(), MinerError<B::Error>> {
if !self.running {
return Err(MinerError::NotRunning);
}
let frame = encode_work(&header, work_id).ok_or(MinerError::InvalidWork)?;
self.check_temperature()?;
if let Err(error) = self.backend.send_frame(self.chain, &frame) {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
self.work[usize::from(work_id >> 3)] = Some(Work {
header,
target_le,
id: work_id,
});
Ok(())
}
/// Forget prior pool jobs after `clean_jobs`, while leaving the ASIC powered.
/// Reports already in flight are then classified as stale.
pub fn clear_work(&mut self) {
self.work = [None; 32];
}
pub fn poll(&mut self) -> Result<Option<ValidShare>, MinerError<B::Error>> {
if !self.running {
return Err(MinerError::NotRunning);
}
self.check_temperature()?;
let mut frame = [0_u8; REPORT_BYTES];
let length = match self.backend.receive_frame(self.chain, &mut frame) {
Ok(length) => length,
Err(error) => {
let _ = self.power_off();
return Err(MinerError::Backend(error));
}
};
if length == 0 {
return Ok(None);
}
let report = match decode_nonce_report(&frame[..length.min(REPORT_BYTES)]) {
Ok(report) if length == REPORT_BYTES => report,
Ok(_) => {
let _ = self.power_off();
return Err(MinerError::InvalidReport(ReportError::Length));
}
Err(error) => {
let _ = self.power_off();
return Err(MinerError::InvalidReport(error));
}
};
let Some(work) = self.work[usize::from(report.work_id >> 3)] else {
return Err(MinerError::StaleReport);
};
if report.work_id != work.id {
return Err(MinerError::StaleReport);
}
let check = verify_sha256_report(
&work.header,
report.nonce,
report.version_field,
&work.target_le,
);
if !check.meets_target {
return Err(MinerError::BelowTarget);
}
Ok(Some(ValidShare {
nonce: report.nonce,
work_id: report.work_id,
rolled_version: check.rolled_version,
hash_le: check.hash_le,
}))
}
}
impl<B: HardwareBackend> Drop for Bm1366Miner<'_, B> {
fn drop(&mut self) {
if self.running {
let _ = self.power_off();
}
}
}
+238
View File
@@ -0,0 +1,238 @@
// SPDX-License-Identifier: MIT
//! Verify reported SHA-256d shares. This module does not search for nonces.
const BM1366_VERSION_BITS: u32 = 0x1FFF_E000;
const ROUND: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
const INITIAL: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];
fn compress(state: &mut [u32; 8], block: &[u8]) {
let mut words = [0_u32; 64];
for (index, part) in block.chunks_exact(4).enumerate() {
words[index] = u32::from_be_bytes(part.try_into().expect("four-byte word"));
}
for index in 16..64 {
let a = words[index - 15];
let b = words[index - 2];
let small_zero = a.rotate_right(7) ^ a.rotate_right(18) ^ (a >> 3);
let small_one = b.rotate_right(17) ^ b.rotate_right(19) ^ (b >> 10);
words[index] = words[index - 16]
.wrapping_add(small_zero)
.wrapping_add(words[index - 7])
.wrapping_add(small_one);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state;
for index in 0..64 {
let choose = (e & f) ^ (!e & g);
let majority = (a & b) ^ (a & c) ^ (b & c);
let big_one = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let big_zero = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let first = h
.wrapping_add(big_one)
.wrapping_add(choose)
.wrapping_add(ROUND[index])
.wrapping_add(words[index]);
let second = big_zero.wrapping_add(majority);
h = g;
g = f;
f = e;
e = d.wrapping_add(first);
d = c;
c = b;
b = a;
a = first.wrapping_add(second);
}
for (current, result) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
*current = current.wrapping_add(result);
}
}
/// Compute SHA-256 for a message whose length fits the standard 64-bit field.
pub fn sha256(message: &[u8]) -> [u8; 32] {
let mut state = INITIAL;
let chunks = message.chunks_exact(64);
let remainder = chunks.remainder();
for chunk in chunks {
compress(&mut state, chunk);
}
let final_size = if remainder.len() >= 56 { 128 } else { 64 };
let mut final_blocks = [0_u8; 128];
final_blocks[..remainder.len()].copy_from_slice(remainder);
final_blocks[remainder.len()] = 0x80;
final_blocks[final_size - 8..final_size]
.copy_from_slice(&((message.len() as u64).wrapping_mul(8)).to_be_bytes());
for chunk in final_blocks[..final_size].chunks_exact(64) {
compress(&mut state, chunk);
}
let mut digest = [0_u8; 32];
for (word, bytes) in state.into_iter().zip(digest.chunks_exact_mut(4)) {
bytes.copy_from_slice(&word.to_be_bytes());
}
digest
}
/// Compute one double hash for verification, never for nonce search.
pub fn sha256d(message: &[u8]) -> [u8; 32] {
sha256(&sha256(message))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ShareCheck {
pub rolled_version: u32,
pub hash_le: [u8; 32],
pub meets_target: bool,
}
/// Decode the raw BM1366 version extension against the version sent to the ASIC.
/// The chip reports additional set bits; pool submission uses a separate mask.
pub fn decode_bm1366_version(job_version: u32, version_field: u16) -> u32 {
job_version | ((u32::from(version_field) << 13) & BM1366_VERSION_BITS)
}
/// The BIP310 mask negotiated with a pool, limited to BM1366 rolling bits.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VersionMask(u32);
impl VersionMask {
pub fn new(mask: u32) -> Option<Self> {
(mask & !BM1366_VERSION_BITS == 0).then_some(Self(mask))
}
pub fn apply_submission_bits(self, base_version: u32, version_bits: u32) -> Option<u32> {
(version_bits & !self.0 == 0).then_some((base_version & !self.0) | version_bits)
}
pub fn bits(self) -> u32 {
self.0
}
}
/// Check one ASIC-reported nonce against a little-endian 256-bit pool target.
pub fn verify_sha256_report(
nonce_zero_header: &[u8; 80],
nonce: u32,
version_field: u16,
target_le: &[u8; 32],
) -> ShareCheck {
let mut header = *nonce_zero_header;
let base_version = u32::from_le_bytes(header[..4].try_into().expect("version field"));
let rolled_version = decode_bm1366_version(base_version, version_field);
header[..4].copy_from_slice(&rolled_version.to_le_bytes());
header[76..80].copy_from_slice(&nonce.to_le_bytes());
let hash_le = sha256d(&header);
let meets_target = hash_le.iter().rev().cmp(target_le.iter().rev()).is_le();
ShareCheck {
rolled_version,
hash_le,
meets_target,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
#[test]
fn sha256_matches_standard_padding_vectors() {
let vectors: [(&[u8], &str); 6] = [
(
b"",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
),
(
b"abc",
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
),
(
&(0_u8..55).collect::<Vec<_>>(),
"463eb28e72f82e0a96c0a4cc53690c571281131f672aa229e0d45ae59b598b59",
),
(
&(0_u8..56).collect::<Vec<_>>(),
"da2ae4d6b36748f2a318f23e7ab1dfdf45acdc9d049bd80e59de82a60895f562",
),
(
&(0_u8..64).collect::<Vec<_>>(),
"fdeab9acf3710362bd2658cdc9a29e8f9c757fcf9811603a8c447cd1d9151108",
),
(
&(0_u8..100).collect::<Vec<_>>(),
"bce0aff19cf5aa6a7469a30d61d04e4376e4bbf6381052ee9e7f33925c954d52",
),
];
for (message, expected) in vectors {
assert_eq!(hex(&sha256(message)), expected);
}
}
#[test]
fn captured_bm1366_report_meets_diff_one_only_with_rolled_version() {
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 mut diff_one = [0_u8; 32];
diff_one[26..28].fill(0xff);
let result = verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &diff_one);
assert_eq!(result.rolled_version, 0x2096_6000);
assert_eq!(
hex(&result.hash_le),
"4b5e00850cf9de9809f822f8858eda39e49996d9d40f634f1043290000000000"
);
assert!(result.meets_target);
assert!(!verify_sha256_report(&header, 0xEDAD_FF38, 0, &diff_one).meets_target);
assert!(!verify_sha256_report(&header, 0xEDAD_FF39, 0x04B3, &diff_one).meets_target);
assert!(verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &[0xff; 32]).meets_target);
assert!(!verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &[0; 32]).meets_target);
}
#[test]
fn raw_asic_version_preserves_bits_sent_to_chip() {
assert_eq!(decode_bm1366_version(0x2100_0004, 1), 0x2100_2004);
assert_eq!(decode_bm1366_version(0x2000_0000, 0), 0x2000_0000);
}
#[test]
fn pool_version_bits_replace_only_negotiated_mask() {
let mask = VersionMask::new(0x0060_0000).expect("valid restricted mask");
assert_eq!(
mask.apply_submission_bits(0x2160_0004, 0x0020_0000),
Some(0x2120_0004)
);
assert_eq!(mask.apply_submission_bits(0x2160_0004, 0x0080_0000), None);
assert_eq!(
VersionMask::new(0)
.unwrap()
.apply_submission_bits(0x2100_0004, 0),
Some(0x2100_0004)
);
assert_eq!(
VersionMask::new(BM1366_VERSION_BITS)
.unwrap()
.apply_submission_bits(0x2160_0004, 0),
Some(0x2000_0004)
);
assert!(VersionMask::new(0x8000_0000).is_none());
}
}
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: MIT
//! Format one verified share for Stratum V1 and negotiated BIP310 submission.
//! Pool I/O and request tracking are owned by the caller.
use crate::pow::VersionMask;
use std::fmt::Write;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubmitError {
EmptyWorker,
EmptyJobId,
FieldTooLong,
ExtranonceTooLong,
UnrepresentableVersion,
}
pub struct Submission<'a> {
pub request_id: u64,
pub worker: &'a str,
pub job_id: &'a str,
pub extranonce2: &'a [u8],
pub ntime: u32,
pub nonce: u32,
pub base_version: u32,
pub rolled_version: u32,
/// The last pool mask, only after version rolling was accepted.
pub version_mask: Option<VersionMask>,
}
fn json_string(out: &mut String, value: &str) {
out.push('"');
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c <= '\u{001f}' => {
write!(out, "\\u{:04x}", c as u32).expect("write to String");
}
c => out.push(c),
}
}
out.push('"');
}
/// Emit one newline-terminated JSON request. The caller must have checked the
/// ASIC report against the pool target and retained the original job metadata.
pub fn format_submission(share: &Submission<'_>) -> Result<String, SubmitError> {
if share.worker.is_empty() {
return Err(SubmitError::EmptyWorker);
}
if share.job_id.is_empty() {
return Err(SubmitError::EmptyJobId);
}
if share.worker.len() > 128 || share.job_id.len() > 128 {
return Err(SubmitError::FieldTooLong);
}
if share.extranonce2.len() > 32 {
return Err(SubmitError::ExtranonceTooLong);
}
let version_bits = match share.version_mask {
Some(mask) => {
let bits = share.rolled_version & mask.bits();
if mask.apply_submission_bits(share.base_version, bits) != Some(share.rolled_version) {
return Err(SubmitError::UnrepresentableVersion);
}
Some(bits)
}
None if share.rolled_version == share.base_version => None,
None => return Err(SubmitError::UnrepresentableVersion),
};
let mut out = format!(
"{{\"id\":{},\"method\":\"mining.submit\",\"params\":[",
share.request_id
);
json_string(&mut out, share.worker);
out.push(',');
json_string(&mut out, share.job_id);
out.push_str(",\"");
for byte in share.extranonce2 {
write!(out, "{byte:02x}").expect("write to String");
}
write!(out, "\",\"{:08x}\",\"{:08x}\"", share.ntime, share.nonce).expect("write to String");
if let Some(bits) = version_bits {
write!(out, ",\"{bits:08x}\"").expect("write to String");
}
out.push_str("]}\n");
Ok(out)
}
+251
View File
@@ -0,0 +1,251 @@
// SPDX-License-Identifier: MIT
//! Bounded decoding of Bitcoin Stratum V1 subscription and job messages.
//! The network client must enforce a line limit before passing data here.
use crate::difficulty::PoolDifficulty;
use crate::pow::VersionMask;
use crate::stratum_work::{JobError, Sha256Job};
use serde_json::Value;
const MAX_LINE_BYTES: usize = 131_072;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PoolMessageError {
TooLarge,
Json,
WrongMessage,
Unnegotiated,
InvalidField,
InvalidHex,
InvalidWork(JobError),
}
#[derive(Debug, Eq, PartialEq)]
pub struct Subscription {
pub extranonce1: Vec<u8>,
pub extranonce2_size: usize,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PoolNotification {
SetDifficulty(PoolDifficulty),
SetExtranonce(Subscription),
SetVersionMask(VersionMask),
}
pub struct PoolJob {
pub id: String,
pub clean_jobs: bool,
pub work: Sha256Job,
}
fn parse_json(line: &[u8]) -> Result<Value, PoolMessageError> {
if line.len() > MAX_LINE_BYTES {
return Err(PoolMessageError::TooLarge);
}
serde_json::from_slice(line).map_err(|_| PoolMessageError::Json)
}
fn hex_bytes(text: &str) -> Result<Vec<u8>, PoolMessageError> {
let bytes = text.as_bytes();
if bytes.len() & 1 != 0 {
return Err(PoolMessageError::InvalidHex);
}
let mut result = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks_exact(2) {
let high = (pair[0] as char)
.to_digit(16)
.ok_or(PoolMessageError::InvalidHex)?;
let low = (pair[1] as char)
.to_digit(16)
.ok_or(PoolMessageError::InvalidHex)?;
result.push(((high << 4) | low) as u8);
}
Ok(result)
}
fn hex_fixed<const N: usize>(field: &Value) -> Result<[u8; N], PoolMessageError> {
let text = field.as_str().ok_or(PoolMessageError::InvalidField)?;
if text.len() != N * 2 {
return Err(PoolMessageError::InvalidField);
}
hex_bytes(text)?
.try_into()
.map_err(|_| PoolMessageError::InvalidField)
}
fn hex_u32(field: &Value) -> Result<u32, PoolMessageError> {
let text = field.as_str().ok_or(PoolMessageError::InvalidField)?;
if text.len() != 8 {
return Err(PoolMessageError::InvalidField);
}
u32::from_str_radix(text, 16).map_err(|_| PoolMessageError::InvalidHex)
}
fn valid_subscription(
extranonce1: Vec<u8>,
extranonce2_size: u64,
) -> Result<Subscription, PoolMessageError> {
if extranonce1.len() > 32 || extranonce2_size > 32 {
return Err(PoolMessageError::InvalidField);
}
Ok(Subscription {
extranonce1,
extranonce2_size: extranonce2_size as usize,
})
}
/// Parse the response to a matching `mining.subscribe` request.
pub fn parse_subscription(line: &[u8], request_id: u64) -> Result<Subscription, PoolMessageError> {
let message = parse_json(line)?;
if message.get("id").and_then(Value::as_u64) != Some(request_id)
|| !message.get("error").is_none_or(Value::is_null)
{
return Err(PoolMessageError::WrongMessage);
}
let result = message
.get("result")
.and_then(Value::as_array)
.ok_or(PoolMessageError::InvalidField)?;
if result.len() != 3 || !result[0].is_array() {
return Err(PoolMessageError::InvalidField);
}
let extranonce1 = hex_bytes(result[1].as_str().ok_or(PoolMessageError::InvalidField)?)?;
let extranonce2_size = result[2].as_u64().ok_or(PoolMessageError::InvalidField)?;
valid_subscription(extranonce1, extranonce2_size)
}
/// Decode the response to a BIP310 configure request that offered version
/// rolling. A pool mask outside this ASIC's changeable bits is unusable: the
/// pool would reconstruct a different block version for submitted shares.
pub fn parse_configure_response(
line: &[u8],
request_id: u64,
) -> Result<Option<VersionMask>, PoolMessageError> {
let message = parse_json(line)?;
if message.get("id").and_then(Value::as_u64) != Some(request_id)
|| !message.get("error").is_none_or(Value::is_null)
{
return Err(PoolMessageError::WrongMessage);
}
let result = message
.get("result")
.and_then(Value::as_object)
.ok_or(PoolMessageError::InvalidField)?;
match result.get("version-rolling") {
Some(Value::Bool(false)) => Ok(None),
Some(Value::Bool(true)) => {
let mask = hex_u32(
result
.get("version-rolling.mask")
.ok_or(PoolMessageError::InvalidField)?,
)?;
VersionMask::new(mask)
.map(Some)
.ok_or(PoolMessageError::InvalidField)
}
_ => 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.
pub fn parse_control_notification(
line: &[u8],
version_rolling: bool,
subscribe_extranonce: bool,
) -> Result<PoolNotification, PoolMessageError> {
let message = parse_json(line)?;
if !message.get("id").is_none_or(Value::is_null) {
return Err(PoolMessageError::WrongMessage);
}
let method = message
.get("method")
.and_then(Value::as_str)
.ok_or(PoolMessageError::WrongMessage)?;
let params = message
.get("params")
.and_then(Value::as_array)
.ok_or(PoolMessageError::InvalidField)?;
match method {
"mining.set_difficulty" if params.len() == 1 => {
let number = params[0]
.as_number()
.ok_or(PoolMessageError::InvalidField)?;
let difficulty = PoolDifficulty::from_json_number(number)
.map_err(|_| PoolMessageError::InvalidField)?;
Ok(PoolNotification::SetDifficulty(difficulty))
}
"mining.set_version_mask" if params.len() == 1 => {
if !version_rolling {
return Err(PoolMessageError::Unnegotiated);
}
let mask = hex_u32(&params[0])?;
let mask = VersionMask::new(mask).ok_or(PoolMessageError::InvalidField)?;
Ok(PoolNotification::SetVersionMask(mask))
}
"mining.set_extranonce" if params.len() == 2 => {
if !subscribe_extranonce {
return Err(PoolMessageError::Unnegotiated);
}
let extranonce1 = hex_bytes(params[0].as_str().ok_or(PoolMessageError::InvalidField)?)?;
let size = params[1].as_u64().ok_or(PoolMessageError::InvalidField)?;
Ok(PoolNotification::SetExtranonce(valid_subscription(
extranonce1,
size,
)?))
}
"mining.set_difficulty" | "mining.set_version_mask" | "mining.set_extranonce" => {
Err(PoolMessageError::InvalidField)
}
_ => Err(PoolMessageError::WrongMessage),
}
}
/// Parse exactly the nine Bitcoin `mining.notify` parameters into work.
pub fn parse_notify(line: &[u8], subscription: &Subscription) -> Result<PoolJob, PoolMessageError> {
let message = parse_json(line)?;
if message.get("method").and_then(Value::as_str) != Some("mining.notify")
|| !message.get("id").is_none_or(Value::is_null)
{
return Err(PoolMessageError::WrongMessage);
}
let params = message
.get("params")
.and_then(Value::as_array)
.ok_or(PoolMessageError::InvalidField)?;
if params.len() != 9 {
return Err(PoolMessageError::InvalidField);
}
let id = params[0].as_str().ok_or(PoolMessageError::InvalidField)?;
if id.is_empty() || id.len() > 128 {
return Err(PoolMessageError::InvalidField);
}
let branches = params[4].as_array().ok_or(PoolMessageError::InvalidField)?;
if branches.len() > 64 {
return Err(PoolMessageError::InvalidField);
}
let mut merkle_branches = Vec::with_capacity(branches.len());
for branch in branches {
merkle_branches.push(hex_fixed::<32>(branch)?);
}
let work = Sha256Job {
prevhash_stratum: hex_fixed::<32>(&params[1])?,
coinb1: hex_bytes(params[2].as_str().ok_or(PoolMessageError::InvalidField)?)?,
coinb2: hex_bytes(params[3].as_str().ok_or(PoolMessageError::InvalidField)?)?,
merkle_branches,
version: hex_u32(&params[5])?,
nbits: hex_u32(&params[6])?,
ntime: hex_u32(&params[7])?,
extranonce1: subscription.extranonce1.clone(),
extranonce2_size: subscription.extranonce2_size,
};
work.validate().map_err(PoolMessageError::InvalidWork)?;
let clean_jobs = params[8].as_bool().ok_or(PoolMessageError::InvalidField)?;
Ok(PoolJob {
id: id.to_owned(),
clean_jobs,
work,
})
}
+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: MIT
//! Construct SHA-256 Stratum V1 work after a protocol client decodes notify.
//! This module assembles headers; it never searches for nonces.
use crate::pow::sha256d;
const MAX_COINBASE_BYTES: usize = 65_536;
const MAX_MERKLE_BRANCHES: usize = 64;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JobError {
InvalidExtranonceSize,
CoinbaseTooLarge,
TooManyMerkleBranches,
ExtranonceLength,
}
/// Binary fields from `mining.notify`, plus `mining.subscribe` extranonce data.
/// `prevhash_stratum` is the eight word-swapped 32-bit words sent on the wire.
pub struct Sha256Job {
pub prevhash_stratum: [u8; 32],
pub coinb1: Vec<u8>,
pub coinb2: Vec<u8>,
pub merkle_branches: Vec<[u8; 32]>,
pub version: u32,
pub nbits: u32,
pub ntime: u32,
pub extranonce1: Vec<u8>,
pub extranonce2_size: usize,
}
impl Sha256Job {
pub fn validate(&self) -> Result<(), JobError> {
if self.extranonce1.len() > 32 || self.extranonce2_size > 32 {
return Err(JobError::InvalidExtranonceSize);
}
let total = self
.coinb1
.len()
.checked_add(self.extranonce1.len())
.and_then(|sum| sum.checked_add(self.extranonce2_size))
.and_then(|sum| sum.checked_add(self.coinb2.len()));
if total.is_none_or(|sum| sum > MAX_COINBASE_BYTES) {
return Err(JobError::CoinbaseTooLarge);
}
if self.merkle_branches.len() > MAX_MERKLE_BRANCHES {
return Err(JobError::TooManyMerkleBranches);
}
Ok(())
}
pub fn nonce_zero_header(&self, extranonce2: &[u8], ntime: u32) -> Result<[u8; 80], JobError> {
self.validate()?;
if extranonce2.len() != self.extranonce2_size {
return Err(JobError::ExtranonceLength);
}
let mut coinbase = Vec::with_capacity(
self.coinb1.len() + self.extranonce1.len() + extranonce2.len() + self.coinb2.len(),
);
coinbase.extend_from_slice(&self.coinb1);
coinbase.extend_from_slice(&self.extranonce1);
coinbase.extend_from_slice(extranonce2);
coinbase.extend_from_slice(&self.coinb2);
let mut root = sha256d(&coinbase);
for branch in &self.merkle_branches {
let mut pair = [0_u8; 64];
pair[..32].copy_from_slice(&root);
pair[32..].copy_from_slice(branch);
root = sha256d(&pair);
}
let mut header = [0_u8; 80];
header[..4].copy_from_slice(&self.version.to_le_bytes());
for (index, word) in self.prevhash_stratum.chunks_exact(4).enumerate() {
for (offset, byte) in word.iter().rev().enumerate() {
header[4 + index * 4 + offset] = *byte;
}
}
header[36..68].copy_from_slice(&root);
header[68..72].copy_from_slice(&ntime.to_le_bytes());
header[72..76].copy_from_slice(&self.nbits.to_le_bytes());
Ok(header)
}
}
+200
View File
@@ -0,0 +1,200 @@
use alkane_os::bm1366::{decode_nonce_report, encode_work};
use alkane_os::difficulty::PoolDifficulty;
use alkane_os::miner::Bm1366Miner;
use alkane_os::pow::verify_sha256_report;
use alkane_os::pow::VersionMask;
use alkane_os::stratum_submit::{format_submission, Submission};
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::time::Instant;
fn measure(name: &str, iterations: u64, mut f: impl FnMut()) {
let started = Instant::now();
for _ in 0..iterations {
f();
}
let ns = started.elapsed().as_nanos() as f64 / iterations as f64;
println!("BENCH {name} {ns:.3} ns/op");
}
#[test]
#[ignore = "microbenchmark"]
fn bench_target_matrix() {
measure("target_matrix", 20_000, || {
black_box(
target_matrix()
.filter(|target| black_box(target.chip.algorithm) == alkane_os::Algorithm::Sha256)
.count(),
);
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_power_policy() {
measure("power_policy", 100_000, || {
black_box(power_decision(black_box(Some(64_000)), 80_000));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_share_verification() {
let header = [0_u8; 80];
let target = [0xff_u8; 32];
measure("share_verification", 20_000, || {
black_box(verify_sha256_report(
black_box(&header),
black_box(0xEDAD_FF38),
black_box(0x04B3),
black_box(&target),
));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1366_work_encoding() {
let header = [0_u8; 80];
measure("bm1366_work_encoding", 20_000, || {
black_box(encode_work(black_box(&header), black_box(0x18)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_bm1366_report_decode() {
let report = [
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
];
measure("bm1366_report_decode", 100_000, || {
let _ = black_box(decode_nonce_report(black_box(&report)));
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_header() {
let job = Sha256Job {
prevhash_stratum: [0; 32],
coinb1: vec![0; 48],
coinb2: vec![0; 64],
merkle_branches: vec![[0; 32]; 4],
version: 0x2000_0000,
nbits: 0x1d00_ffff,
ntime: 0x6655_4433,
extranonce1: vec![0; 4],
extranonce2_size: 8,
};
measure("stratum_header", 5_000, || {
black_box(
job.nonce_zero_header(black_box(&[0; 8]), job.ntime)
.unwrap(),
);
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_submission() {
let share = Submission {
request_id: 1,
worker: "miner.worker",
job_id: "job-123",
extranonce2: &[0; 8],
ntime: 0x680f_6a2e,
nonce: 0xedad_ff38,
base_version: 0x2000_0000,
rolled_version: 0x2096_6000,
version_mask: Some(VersionMask::new(0x1fff_e000).unwrap()),
};
measure("stratum_submission", 20_000, || {
black_box(format_submission(black_box(&share)).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_notify_parse() {
let line = serde_json::json!({
"id": null,
"method": "mining.notify",
"params": [
"job-1",
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"616263", "78797a", [], "20000000", "1d00ffff", "66554433", true
]
})
.to_string();
let subscription = Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
};
measure("stratum_notify_parse", 20_000, || {
black_box(parse_notify(black_box(line.as_bytes()), &subscription).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_control_parse() {
let line = br#"{"id":null,"method":"mining.set_difficulty","params":[2048.5]}"#;
measure("stratum_control_parse", 20_000, || {
black_box(parse_control_notification(black_box(line), false, false).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_difficulty_target() {
let number = serde_json::from_str("2048.5").unwrap();
let difficulty = PoolDifficulty::from_json_number(&number).unwrap();
measure("difficulty_target", 20_000, || {
black_box(black_box(difficulty).target_le());
});
}
struct BenchBackend;
impl HardwareBackend for BenchBackend {
type Error = ();
fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
black_box(frame);
Ok(())
}
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(())
}
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> {
Ok(())
}
}
#[test]
#[ignore = "microbenchmark"]
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;
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner
.submit(black_box(header), black_box(target), 0x18)
.unwrap();
black_box(miner.poll().unwrap());
miner.stop().unwrap();
});
}
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: MIT
use alkane_os::difficulty::{DifficultyError, PoolDifficulty};
fn target(decimal: &str) -> String {
let number = serde_json::from_str(decimal).unwrap();
PoolDifficulty::from_json_number(&number)
.unwrap()
.target_le()
.iter()
.rev()
.map(|byte| format!("{byte:02x}"))
.collect()
}
#[test]
fn exact_share_targets_match_integer_reference() {
for (difficulty, expected) in [
(
"1",
"00000000ffff0000000000000000000000000000000000000000000000000000",
),
(
"2",
"000000007fff8000000000000000000000000000000000000000000000000000",
),
(
"0.5",
"00000001fffe0000000000000000000000000000000000000000000000000000",
),
(
"1.25",
"00000000cccc0000000000000000000000000000000000000000000000000000",
),
(
"2048.5",
"00000000001ffde021fde021fde021fde021fde021fde021fde021fde021fde0",
),
(
"0.000001",
"000f4230bdc00000000000000000000000000000000000000000000000000000",
),
(
"1000000000000000000",
"000000000000000000000012724b5f7471d95d3bbefee5e602a7b17261180d8e",
),
] {
assert_eq!(target(difficulty), expected, "difficulty {difficulty}");
}
assert_eq!(target("1.2e3"), target("1200"));
assert_eq!(target("1e-19"), "ff".repeat(32));
}
#[test]
fn invalid_or_unrepresentable_difficulty_is_rejected() {
let zero = serde_json::from_str("0").unwrap();
assert_eq!(
PoolDifficulty::from_json_number(&zero),
Err(DifficultyError::Invalid)
);
let negative = serde_json::from_str("-1").unwrap();
assert_eq!(
PoolDifficulty::from_json_number(&negative),
Err(DifficultyError::OutOfRange)
);
for value in ["1e20", "1e-20", "1.00000000000000000001"] {
let number = serde_json::from_str(value).unwrap();
assert_eq!(
PoolDifficulty::from_json_number(&number),
Err(DifficultyError::OutOfRange),
"difficulty {value}"
);
}
}
+169
View File
@@ -0,0 +1,169 @@
// SPDX-License-Identifier: MIT
use alkane_os::hal_wire::{HalClient, HalError};
use alkane_os::HardwareBackend;
use std::io::{Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::thread;
use std::time::{Duration, Instant};
fn reply(socket: &mut UnixStream, request: &[u8; 16], body: &[u8]) {
let mut header = *request;
header[6..8].copy_from_slice(&1_u16.to_le_bytes());
header[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
socket.write_all(&header).unwrap();
socket.write_all(body).unwrap();
}
#[test]
fn sdk_backend_round_trip_and_safety_limits() {
let (client, mut server) = UnixStream::pair().unwrap();
let worker = thread::spawn(move || {
let expected = [
(1, vec![2, 3, 0, 0x55, 0xaa, 0x21], vec![0]),
(2, vec![2, 8, 0], vec![0, 3, 0, 0xaa, 0x55, 0x01]),
(3, vec![2, 1], vec![0]),
(4, vec![0, 90], vec![0]),
(
5,
vec![1],
[vec![0], 72_500_i32.to_le_bytes().to_vec()].concat(),
),
(6, vec![1], vec![0]),
];
for (index, (opcode, request_body, response_body)) in expected.iter().enumerate() {
let mut header = [0_u8; 16];
server.read_exact(&mut header).unwrap();
assert_eq!(&header[..4], b"ALKH");
assert_eq!(header[4], 1);
assert_eq!(header[5], *opcode);
assert_eq!(
u32::from_le_bytes(header[8..12].try_into().unwrap()),
index as u32 + 1
);
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
let mut body = vec![0_u8; length];
server.read_exact(&mut body).unwrap();
assert_eq!(&body, request_body);
reply(&mut server, &header, response_body);
}
});
let mut backend = HalClient::from_stream(client).unwrap();
backend.send_frame(2, &[0x55, 0xaa, 0x21]).unwrap();
let mut buffer = [0_u8; 8];
assert_eq!(backend.receive_frame(2, &mut buffer).unwrap(), 3);
assert_eq!(&buffer[..3], &[0xaa, 0x55, 0x01]);
backend.set_chain_reset(2, true).unwrap();
backend.set_fan_target(0, 90).unwrap();
assert_eq!(backend.read_temperature_mc(1).unwrap(), 72_500);
backend.set_psu_enabled(true).unwrap();
assert!(matches!(
backend.set_fan_target(0, 101),
Err(HalError::InvalidFanPercent)
));
assert!(matches!(
backend.send_frame(0, &[0_u8; 4094]),
Err(HalError::FrameTooLong)
));
worker.join().unwrap();
}
#[test]
fn rejects_wrong_response_sequence() {
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();
header[8..12].copy_from_slice(&2_u32.to_le_bytes());
reply(&mut server, &header, &[0]);
});
let mut backend = HalClient::from_stream(client).unwrap();
assert!(matches!(
backend.set_psu_enabled(true),
Err(HalError::Protocol("response sequence mismatch"))
));
assert!(matches!(
backend.set_psu_enabled(true),
Err(HalError::Protocol("connection is unusable"))
));
worker.join().unwrap();
}
#[test]
fn rejects_malformed_error_response_and_poisoned_connection() {
for body in [&[4_u8][..], &[3_u8, 99][..]] {
let (client, mut server) = UnixStream::pair().unwrap();
let response = body.to_vec();
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();
reply(&mut server, &header, &response);
});
let mut backend = HalClient::from_stream(client).unwrap();
assert!(matches!(
backend.set_psu_enabled(true),
Err(HalError::Protocol("invalid error response"))
));
assert!(matches!(
backend.set_psu_enabled(true),
Err(HalError::Protocol("connection is unusable"))
));
worker.join().unwrap();
}
}
#[test]
fn slow_partial_response_hits_absolute_exchange_deadline() {
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();
header[6..8].copy_from_slice(&1_u16.to_le_bytes());
header[12..16].copy_from_slice(&1_u32.to_le_bytes());
for byte in header.into_iter().chain([0]) {
if server.write_all(&[byte]).is_err() {
break;
}
thread::sleep(Duration::from_millis(250));
}
});
let mut backend = HalClient::from_stream(client).unwrap();
let start = Instant::now();
assert!(matches!(
backend.set_psu_enabled(true),
Err(HalError::Io(_))
));
assert!(start.elapsed() < Duration::from_secs(4));
drop(backend);
worker.join().unwrap();
}
#[test]
fn connects_to_a_local_backend_socket() {
let path = std::env::temp_dir().join(format!(
"alkane-hal-{}-{}.sock",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let listener = UnixListener::bind(&path).unwrap();
let worker = thread::spawn(move || {
let (mut server, _) = listener.accept().unwrap();
let mut header = [0_u8; 16];
server.read_exact(&mut header).unwrap();
let mut request = [0_u8; 1];
server.read_exact(&mut request).unwrap();
reply(&mut server, &header, &[0]);
});
let mut backend = HalClient::connect(&path).unwrap();
backend.set_psu_enabled(true).unwrap();
worker.join().unwrap();
std::fs::remove_file(path).unwrap();
}
+220
View File
@@ -0,0 +1,220 @@
// SPDX-License-Identifier: MIT
use alkane_os::bm1366::REPORT_BYTES;
use alkane_os::miner::{Bm1366Miner, MinerError};
use alkane_os::HardwareBackend;
const 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 REPORT: [u8; REPORT_BYTES] = [
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
];
fn diff_one() -> [u8; 32] {
let mut target = [0_u8; 32];
target[26..28].fill(0xff);
target
}
#[derive(Default)]
struct FakeBackend {
events: Vec<&'static str>,
temperatures: Vec<i32>,
powered: bool,
fail_off_call: usize,
off_calls: usize,
report: Option<[u8; REPORT_BYTES]>,
additional_reports: Vec<[u8; REPORT_BYTES]>,
sent: Vec<u8>,
}
impl HardwareBackend for FakeBackend {
type Error = &'static str;
fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
assert!(self.powered);
self.events.push("send");
self.sent = frame.to_vec();
Ok(())
}
fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
self.events.push("receive");
if let Some(report) = self.report.take().or_else(|| self.additional_reports.pop()) {
frame[..REPORT_BYTES].copy_from_slice(&report);
Ok(REPORT_BYTES)
} else {
Ok(0)
}
}
fn set_chain_reset(&mut self, _chain: u8, asserted: bool) -> Result<(), Self::Error> {
assert!(self.powered);
self.events
.push(if asserted { "reset-on" } else { "reset-off" });
Ok(())
}
fn set_fan_target(&mut self, _fan: u8, percent: u8) -> Result<(), Self::Error> {
assert!(percent > 0);
self.events.push("fan");
Ok(())
}
fn read_temperature_mc(&mut self, _sensor: u8) -> Result<i32, Self::Error> {
self.events.push("temperature");
if self.temperatures.is_empty() {
return Err("sensor unavailable");
}
Ok(self.temperatures.remove(0))
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.events.push(if enabled { "psu-on" } else { "psu-off" });
if !enabled {
self.off_calls += 1;
if self.off_calls == self.fail_off_call {
return Err("power-off did not complete");
}
}
self.powered = enabled;
Ok(())
}
}
#[test]
fn captured_nonce_passes_a_started_miner() {
let mut backend = FakeBackend {
temperatures: vec![50_000, 50_000, 50_000],
report: Some(REPORT),
..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();
let share = miner.poll().unwrap().unwrap();
assert_eq!(share.nonce, 0xedad_ff38);
assert_eq!(share.work_id, 0x18);
assert_eq!(share.rolled_version, 0x2096_6000);
miner.stop().unwrap();
}
assert!(!backend.powered);
assert_eq!(&backend.sent[..5], &[0x55, 0xaa, 0x21, 0x54, 0x18]);
assert_eq!(
&backend.events[..6],
&[
"psu-off",
"temperature",
"fan",
"psu-on",
"reset-on",
"reset-off"
]
);
}
#[test]
fn hot_or_missing_sensor_stops_power() {
let mut hot = FakeBackend {
temperatures: vec![80_000],
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut hot, 0, 0, 0, 100, 80_000).unwrap();
assert_eq!(miner.start(), Err(MinerError::UnsafeTemperature(80_000)));
drop(miner);
assert!(!hot.powered);
assert!(!hot.events.contains(&"psu-on"));
let mut missing = FakeBackend::default();
let mut miner = Bm1366Miner::new(&mut missing, 0, 0, 0, 100, 80_000).unwrap();
assert_eq!(
miner.start(),
Err(MinerError::Backend("sensor unavailable"))
);
drop(miner);
assert!(!missing.powered);
}
#[test]
fn temperature_rise_stops_power_and_stale_reports_preserve_mining() {
let mut backend = FakeBackend {
temperatures: vec![50_000, 50_000, 90_000],
report: Some(REPORT),
..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.poll(), Err(MinerError::UnsafeTemperature(90_000)));
assert_eq!(miner.poll(), Err(MinerError::NotRunning));
drop(miner);
assert!(!backend.powered);
let mut backend = FakeBackend {
temperatures: vec![50_000; 5],
report: Some(REPORT),
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner.submit(HEADER, diff_one(), 0x20).unwrap();
assert_eq!(miner.poll(), Err(MinerError::StaleReport));
miner.submit(HEADER, diff_one(), 0x18).unwrap();
assert_eq!(miner.poll(), Ok(None));
drop(miner);
assert!(!backend.powered);
}
#[test]
fn earlier_in_flight_job_is_checked_against_its_own_target() {
let mut backend = FakeBackend {
temperatures: vec![50_000; 5],
report: Some(REPORT),
additional_reports: vec![REPORT],
..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();
miner.submit(HEADER, [0; 32], 0x20).unwrap();
assert_eq!(miner.poll().unwrap().unwrap().work_id, 0x18);
miner.clear_work();
assert_eq!(miner.poll(), Err(MinerError::StaleReport));
drop(miner);
assert!(!backend.powered);
}
#[test]
fn below_target_is_rejected_without_misreporting_a_share() {
let mut backend = FakeBackend {
temperatures: vec![50_000, 50_000, 50_000],
report: Some(REPORT),
..Default::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
miner.submit(HEADER, [0; 32], 0x18).unwrap();
assert_eq!(miner.poll(), Err(MinerError::BelowTarget));
drop(miner);
assert!(!backend.powered);
}
#[test]
fn failed_power_off_is_retried_on_drop() {
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"));
drop(miner);
assert_eq!(backend.off_calls, 3);
assert!(!backend.powered);
}
+67
View File
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: MIT
use alkane_os::pow::VersionMask;
use alkane_os::stratum_submit::{format_submission, Submission, SubmitError};
fn share() -> Submission<'static> {
Submission {
request_id: 7,
worker: "miner.worker",
job_id: "pool-job",
extranonce2: &[0, 1, 0xfe, 0xff],
ntime: 0x680f6a2e,
nonce: 0xedadff38,
base_version: 0x20000000,
rolled_version: 0x20966000,
version_mask: Some(VersionMask::new(0x1fffe000).unwrap()),
}
}
#[test]
fn captured_bm1366_version_is_represented_under_negotiated_mask() {
assert_eq!(
format_submission(&share()).unwrap(),
"{\"id\":7,\"method\":\"mining.submit\",\"params\":[\"miner.worker\",\"pool-job\",\"0001feff\",\"680f6a2e\",\"edadff38\",\"00966000\"]}\n"
);
}
#[test]
fn unnegotiated_or_narrow_mask_rejects_rolled_share() {
let mut value = share();
value.version_mask = None;
assert_eq!(
format_submission(&value),
Err(SubmitError::UnrepresentableVersion)
);
value.version_mask = Some(VersionMask::new(0x0060_0000).unwrap());
assert_eq!(
format_submission(&value),
Err(SubmitError::UnrepresentableVersion)
);
value.rolled_version = value.base_version;
value.version_mask = None;
assert_eq!(
format_submission(&value).unwrap(),
"{\"id\":7,\"method\":\"mining.submit\",\"params\":[\"miner.worker\",\"pool-job\",\"0001feff\",\"680f6a2e\",\"edadff38\"]}\n"
);
}
#[test]
fn pool_fields_are_escaped_and_bounded() {
let mut value = share();
value.worker = "worker\"\\\n";
value.job_id = "job\t\u{0001}";
let wire = format_submission(&value).unwrap();
assert!(wire.contains("\"worker\\\"\\\\\\n\""));
assert!(wire.contains("\"job\\t\\u0001\""));
value.worker = "";
assert_eq!(format_submission(&value), Err(SubmitError::EmptyWorker));
value.worker = "worker";
value.job_id = "";
assert_eq!(format_submission(&value), Err(SubmitError::EmptyJobId));
value.job_id = "job";
value.extranonce2 = &[0; 33];
assert_eq!(
format_submission(&value),
Err(SubmitError::ExtranonceTooLong)
);
}
+150
View File
@@ -0,0 +1,150 @@
// SPDX-License-Identifier: MIT
use alkane_os::difficulty::PoolDifficulty;
use alkane_os::stratum_v1::{
parse_configure_response, parse_control_notification, parse_notify, parse_subscription,
PoolMessageError, PoolNotification, Subscription,
};
const SUBSCRIBE: &str =
r#"{"id":1,"result":[[["mining.notify","session"]],"01020304",4],"error":null}"#;
fn notify() -> String {
serde_json::json!({
"id": null,
"method": "mining.notify",
"params": [
"job-1",
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"616263", "78797a",
["202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f"],
"20000000", "1d00ffff", "66554433", true
]
})
.to_string()
}
#[test]
fn subscribe_and_notify_construct_expected_asic_header() {
let subscription = parse_subscription(SUBSCRIBE.as_bytes(), 1).unwrap();
let line = notify();
let job = parse_notify(line.as_bytes(), &subscription).unwrap();
assert_eq!(job.id, "job-1");
assert!(job.clean_jobs);
let header = job
.work
.nonce_zero_header(&[5, 6, 7, 8], job.work.ntime)
.unwrap();
let hex: String = header.iter().map(|byte| format!("{byte:02x}")).collect();
assert_eq!(
hex,
concat!(
"0000002003020100070605040b0a09080f0e0d0c13121110171615141b1a19181f1e1d1c",
"9b9bc91f078af83ff63d00c6da09b5bc4dd26e2d8c0df8ab16b933a259a05881",
"33445566ffff001d00000000"
)
);
}
#[test]
fn malformed_pool_messages_fail_before_work_issuance() {
assert!(matches!(
parse_subscription(SUBSCRIBE.as_bytes(), 2),
Err(PoolMessageError::WrongMessage)
));
let subscription = parse_subscription(SUBSCRIBE.as_bytes(), 1).unwrap();
let malformed = notify().replace("66554433", "6655443g");
assert!(matches!(
parse_notify(malformed.as_bytes(), &subscription),
Err(PoolMessageError::InvalidHex)
));
let wrong_method = notify().replace("mining.notify", "mining.submit");
assert!(matches!(
parse_notify(wrong_method.as_bytes(), &subscription),
Err(PoolMessageError::WrongMessage)
));
let too_large = vec![b' '; 131_073];
assert!(matches!(
parse_notify(&too_large, &subscription),
Err(PoolMessageError::TooLarge)
));
let too_large_coinbase = notify().replace("616263", &"aa".repeat(65_537));
assert!(matches!(
parse_notify(too_large_coinbase.as_bytes(), &subscription),
Err(PoolMessageError::TooLarge)
));
}
#[test]
fn version_rolling_negotiation_and_immediate_mask_change() {
let response = br#"{"id":3,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000"},"error":null}"#;
let mask = parse_configure_response(response, 3).unwrap().unwrap();
assert_eq!(mask.bits(), 0x1fff_e000);
let update = br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#;
assert_eq!(
parse_control_notification(update, true, false).unwrap(),
PoolNotification::SetVersionMask(alkane_os::pow::VersionMask::new(0x6000).unwrap())
);
assert_eq!(
parse_control_notification(update, false, false),
Err(PoolMessageError::Unnegotiated)
);
assert_eq!(
parse_configure_response(response, 4),
Err(PoolMessageError::WrongMessage)
);
let declined = br#"{"id":3,"result":{"version-rolling":false},"error":null}"#;
assert_eq!(parse_configure_response(declined, 3), Ok(None));
let unsafe_mask = br#"{"id":3,"result":{"version-rolling":true,"version-rolling.mask":"ffffffff"},"error":null}"#;
assert_eq!(
parse_configure_response(unsafe_mask, 3),
Err(PoolMessageError::InvalidField)
);
let absent_mask = br#"{"id":3,"result":{"version-rolling":true},"error":null}"#;
assert_eq!(
parse_configure_response(absent_mask, 3),
Err(PoolMessageError::InvalidField)
);
}
#[test]
fn difficulty_and_extranonce_notifications_validate_shape_and_negotiation() {
let difficulty = br#"{"id":null,"method":"mining.set_difficulty","params":[2048.5]}"#;
assert_eq!(
parse_control_notification(difficulty, false, false),
Ok(PoolNotification::SetDifficulty(
PoolDifficulty::from_json_number(&serde_json::from_str("2048.5").unwrap()).unwrap()
))
);
let extranonce = br#"{"id":null,"method":"mining.set_extranonce","params":["aabbccdd",4]}"#;
assert_eq!(
parse_control_notification(extranonce, false, true),
Ok(PoolNotification::SetExtranonce(Subscription {
extranonce1: vec![0xaa, 0xbb, 0xcc, 0xdd],
extranonce2_size: 4,
}))
);
assert_eq!(
parse_control_notification(extranonce, false, false),
Err(PoolMessageError::Unnegotiated)
);
for value in ["0", "-1", "\"2\"", "null"] {
let line =
format!("{{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[{value}]}}");
assert_eq!(
parse_control_notification(line.as_bytes(), false, false),
Err(PoolMessageError::InvalidField)
);
}
let oversize = format!(
"{{\"id\":null,\"method\":\"mining.set_extranonce\",\"params\":[\"{}\",1]}}",
"ab".repeat(33)
);
assert_eq!(
parse_control_notification(oversize.as_bytes(), false, true),
Err(PoolMessageError::InvalidField)
);
let response_id = br#"{"id":5,"method":"mining.set_difficulty","params":[2]}"#;
assert_eq!(
parse_control_notification(response_id, false, false),
Err(PoolMessageError::WrongMessage)
);
}
+57
View File
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: MIT
use alkane_os::bm1366::encode_work;
use alkane_os::stratum_work::{JobError, Sha256Job};
fn fixture() -> Sha256Job {
let mut prevhash_stratum = [0_u8; 32];
let mut branch = [0_u8; 32];
for (index, byte) in prevhash_stratum.iter_mut().enumerate() {
*byte = index as u8;
}
for (index, byte) in branch.iter_mut().enumerate() {
*byte = (index + 32) as u8;
}
Sha256Job {
prevhash_stratum,
coinb1: b"abc".to_vec(),
coinb2: b"xyz".to_vec(),
merkle_branches: vec![branch],
version: 0x2000_0000,
nbits: 0x1d00_ffff,
ntime: 0x6655_4433,
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
}
}
#[test]
fn builds_cross_checked_header_and_asic_work() {
let job = fixture();
let header = job.nonce_zero_header(&[5, 6, 7, 8], job.ntime).unwrap();
let expected = concat!(
"0000002003020100070605040b0a09080f0e0d0c13121110171615141b1a19181f1e1d1c",
"9b9bc91f078af83ff63d00c6da09b5bc4dd26e2d8c0df8ab16b933a259a05881",
"33445566ffff001d00000000"
);
let actual: String = header.iter().map(|byte| format!("{byte:02x}")).collect();
assert_eq!(actual, expected);
let frame = encode_work(&header, 0x18).unwrap();
assert_eq!(&frame[10..14], &header[72..76]);
}
#[test]
fn rejects_invalid_pool_work_before_hashing() {
let mut job = fixture();
assert_eq!(
job.nonce_zero_header(&[5, 6], job.ntime),
Err(JobError::ExtranonceLength)
);
job.extranonce2_size = 33;
assert_eq!(job.validate(), Err(JobError::InvalidExtranonceSize));
job.extranonce2_size = 4;
job.coinb1.resize(65_536, 0);
assert_eq!(job.validate(), Err(JobError::CoinbaseTooLarge));
job.coinb1 = b"abc".to_vec();
job.merkle_branches.resize(65, [0; 32]);
assert_eq!(job.validate(), Err(JobError::TooManyMerkleBranches));
}
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"e0165305f3b22a9ab4217a121f85379aa56c2675caa7afedc0a7468fc187600b",".github/FUNDING.yml":"b017158736b3c9751a2d21edfce7fe61c8954e2fced8da8dd3013c2f3e295bd9",".github/workflows/ci.yml":"89c4f60223daf03217ea7c1e8879135b11d2554bd1e57dd9eff5c02f1adc7909","Cargo.lock":"1cd64090b8e883963bb08d91e6968cc1e83ffdba4f4b2f47651ce9d351a8a947","Cargo.toml":"894c215e4e7e973b556b0e9627bf9b6a719a043fac9b5af9838660816392a09f","Cargo.toml.orig":"44ca1ae5d9b48743305b57f3367051289512037e7836b8b3693b68d48dec0483","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"1305bd79675db0194915d9bc91bd0b3cf9487bc1126e05bf46b48ab43edce44b","benches/bench.rs":"29a0bdb973848007d681e571c57487e21e1bfb7aed5980c2190dba354498b154","src/lib.rs":"e962338e1886873aa7c3399ec89aa5378ccbfed712b9690f043628079390a34f","src/u128_ext.rs":"498cc94f13805e551248fd82f47cc318f51d953a5002a9f8698858cd12fbae3c","tests/test.rs":"b22f8a8ed89edcbb4140b74f5edd7f2adf3cb0e363990dd6010cd6ebe0dc36b7"},"package":"8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "af77385d0daf4d0e949e81f2588be2e44f69f086"
},
"path_in_vcs": ""
}
+1
View File
@@ -0,0 +1 @@
github: dtolnay
+126
View File
@@ -0,0 +1,126 @@
name: CI
on:
push:
pull_request:
workflow_dispatch:
schedule: [cron: "40 1 * * *"]
permissions:
contents: read
env:
RUSTFLAGS: -Dwarnings
jobs:
pre_ci:
uses: dtolnay/.github/.github/workflows/pre_ci.yml@master
test:
name: Rust ${{matrix.rust}}
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
rust: [nightly, beta, stable, 1.86.0]
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{matrix.rust}}
- name: Enable type layout randomization
run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV
if: matrix.rust == 'nightly'
- run: cargo build
- run: cargo test
- run: cargo test --release
- run: cargo build --no-default-features
- run: cargo test --tests --no-default-features
- run: cargo test --tests --no-default-features --release
- run: cargo build --tests --features no-panic --release
if: matrix.rust == 'nightly'
- run: cargo bench --no-run
if: matrix.rust == 'nightly'
- uses: actions/upload-artifact@v6
if: matrix.rust == 'nightly' && always()
with:
name: Cargo.lock
path: Cargo.lock
continue-on-error: true
msrv:
name: Rust 1.68.0
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@1.68
- run: cargo build
- run: cargo build --no-default-features
doc:
name: Documentation
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
timeout-minutes: 45
env:
RUSTDOCFLAGS: -Dwarnings
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- uses: dtolnay/install@cargo-docs-rs
- run: cargo docs-rs
miri:
name: Miri
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@miri
- run: cargo miri setup
- run: cargo miri test
env:
MIRIFLAGS: -Zmiri-strict-provenance
clippy:
name: Clippy
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@clippy
- run: cargo clippy --tests --benches -- -Dclippy::all -Dclippy::pedantic
fuzz:
name: Fuzz
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- uses: dtolnay/install@cargo-fuzz
- run: cargo fuzz check
outdated:
name: Outdated
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/install@cargo-outdated
- run: cargo outdated --workspace --exit-code 1
- run: cargo outdated --manifest-path fuzz/Cargo.toml --exit-code 1
+460
View File
@@ -0,0 +1,460 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "alloca"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4"
dependencies = [
"cc",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "autocfg"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.2.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clap"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "criterion"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3"
dependencies = [
"alloca",
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools",
"num-traits",
"oorandom",
"page_size",
"regex",
"serde",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "itoa"
version = "1.0.18"
dependencies = [
"criterion",
"no-panic",
]
[[package]]
name = "libc"
version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "no-panic"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f967505aabc8af5752d098c34146544a43684817cdba8f9725b292530cabbf53"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "page_size"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa 1.0.17",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zerocopy"
version = "0.8.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+66
View File
@@ -0,0 +1,66 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.68"
name = "itoa"
version = "1.0.18"
authors = ["David Tolnay <dtolnay@gmail.com>"]
build = false
exclude = ["*.png"]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Fast integer primitive to string conversion"
documentation = "https://docs.rs/itoa"
readme = "README.md"
keywords = ["integer"]
categories = [
"value-formatting",
"no-std",
"no-std::no-alloc",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/itoa"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--extern-html-root-url=core=https://doc.rust-lang.org",
"--extern-html-root-url=alloc=https://doc.rust-lang.org",
"--extern-html-root-url=std=https://doc.rust-lang.org",
]
[lib]
name = "itoa"
path = "src/lib.rs"
[[test]]
name = "test"
path = "tests/test.rs"
[[bench]]
name = "bench"
path = "benches/bench.rs"
harness = false
[dependencies.no-panic]
version = "0.1"
optional = true
[target."cfg(not(miri))".dev-dependencies.criterion]
version = "0.8"
default-features = false
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "itoa"
version = "1.0.18"
authors = ["David Tolnay <dtolnay@gmail.com>"]
categories = ["value-formatting", "no-std", "no-std::no-alloc"]
description = "Fast integer primitive to string conversion"
documentation = "https://docs.rs/itoa"
edition = "2021"
exclude = ["*.png"]
keywords = ["integer"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/itoa"
rust-version = "1.68"
[dependencies]
no-panic = { version = "0.1", optional = true }
[target.'cfg(not(miri))'.dev-dependencies]
criterion = { version = "0.8", default-features = false }
[[bench]]
name = "bench"
harness = false
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--extern-html-root-url=core=https://doc.rust-lang.org",
"--extern-html-root-url=alloc=https://doc.rust-lang.org",
"--extern-html-root-url=std=https://doc.rust-lang.org",
]
+176
View File
@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+23
View File
@@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+65
View File
@@ -0,0 +1,65 @@
itoa
====
[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/itoa-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/itoa)
[<img alt="crates.io" src="https://img.shields.io/crates/v/itoa.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/itoa)
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-itoa-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/itoa)
[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/itoa/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/itoa/actions?query=branch%3Amaster)
This crate provides a fast conversion of integer primitives to decimal strings.
The implementation comes straight from [libcore] but avoids the performance
penalty of going through [`core::fmt::Formatter`].
See also [`zmij`] for printing floating point primitives.
[libcore]: https://github.com/rust-lang/rust/blob/1.92.0/library/core/src/fmt/num.rs#L190-L253
[`core::fmt::Formatter`]: https://doc.rust-lang.org/std/fmt/struct.Formatter.html
[`zmij`]: https://github.com/dtolnay/zmij
```toml
[dependencies]
itoa = "1.0"
```
<br>
## Example
```rust
fn main() {
let mut buffer = itoa::Buffer::new();
let printed = buffer.format(128u64);
assert_eq!(printed, "128");
}
```
<br>
## Performance
The [itoa-benchmark] compares this library and other Rust integer formatting
implementations across a range of integer sizes. The vertical axis in this chart
shows nanoseconds taken by a single execution of
`itoa::Buffer::new().format(value)` so a lower result indicates a faster
library.
[itoa-benchmark]: https://github.com/dtolnay/itoa-benchmark
![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/itoa-benchmark.png)
<br>
#### License
<sup>
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
</sup>
<br>
<sub>
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.
</sub>
+41
View File
@@ -0,0 +1,41 @@
use criterion::{criterion_group, criterion_main, Criterion};
use std::fmt::Display;
use std::hint;
use std::io::Write;
fn do_bench(c: &mut Criterion, group_name: &str, int: impl itoa::Integer + Display) {
let mut group = c.benchmark_group(group_name);
group.bench_function("itoa", |b| {
let mut buf = itoa::Buffer::new();
b.iter(move || {
let int = hint::black_box(int);
let formatted = buf.format(int);
hint::black_box(formatted);
});
});
group.bench_function("std::fmt", |b| {
let mut buf = Vec::with_capacity(20);
b.iter(|| {
buf.clear();
let int = hint::black_box(int);
write!(&mut buf, "{int}").unwrap();
hint::black_box(buf.as_slice());
});
});
group.finish();
}
fn bench(c: &mut Criterion) {
do_bench(c, "u64[0]", 0u64);
do_bench(c, "u64[half]", u64::from(u32::MAX));
do_bench(c, "u64[max]", u64::MAX);
do_bench(c, "i16[0]", 0i16);
do_bench(c, "i16[min]", i16::MIN);
do_bench(c, "u128[0]", 0u128);
do_bench(c, "u128[max]", u128::MAX);
}
criterion_group!(benches, bench);
criterion_main!(benches);
+466
View File
@@ -0,0 +1,466 @@
//! [![github]](https://github.com/dtolnay/itoa)&ensp;[![crates-io]](https://crates.io/crates/itoa)&ensp;[![docs-rs]](https://docs.rs/itoa)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! This crate provides a fast conversion of integer primitives to decimal
//! strings. The implementation comes straight from [libcore] but avoids the
//! performance penalty of going through [`core::fmt::Formatter`].
//!
//! See also [`zmij`] for printing floating point primitives.
//!
//! [libcore]: https://github.com/rust-lang/rust/blob/1.92.0/library/core/src/fmt/num.rs#L190-L253
//! [`zmij`]: https://github.com/dtolnay/zmij
//!
//! # Example
//!
//! ```
//! fn main() {
//! let mut buffer = itoa::Buffer::new();
//! let printed = buffer.format(128u64);
//! assert_eq!(printed, "128");
//! }
//! ```
//!
//! # Performance
//!
//! The [itoa-benchmark] compares this library and other Rust integer formatting
//! implementations across a range of integer sizes. The vertical axis in this
//! chart shows nanoseconds taken by a single execution of
//! `itoa::Buffer::new().format(value)` so a lower result indicates a faster
//! library.
//!
//! [itoa-benchmark]: https://github.com/dtolnay/itoa-benchmark
//!
//! ![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/itoa-benchmark.png)
#![doc(html_root_url = "https://docs.rs/itoa/1.0.18")]
#![no_std]
#![allow(
clippy::cast_lossless,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::expl_impl_clone_on_copy,
clippy::identity_op,
clippy::items_after_statements,
clippy::must_use_candidate,
clippy::needless_doctest_main,
clippy::unreadable_literal
)]
mod u128_ext;
use core::hint;
use core::mem::{self, MaybeUninit};
use core::str;
#[cfg(feature = "no-panic")]
use no_panic::no_panic;
/// A correctly sized stack allocation for the formatted integer to be written
/// into.
///
/// # Example
///
/// ```
/// let mut buffer = itoa::Buffer::new();
/// let printed = buffer.format(1234);
/// assert_eq!(printed, "1234");
/// ```
pub struct Buffer {
bytes: [MaybeUninit<u8>; i128::MAX_STR_LEN],
}
impl Default for Buffer {
#[inline]
fn default() -> Buffer {
Buffer::new()
}
}
impl Copy for Buffer {}
#[allow(clippy::non_canonical_clone_impl)]
impl Clone for Buffer {
#[inline]
fn clone(&self) -> Self {
Buffer::new()
}
}
impl Buffer {
/// This is a cheap operation; you don't need to worry about reusing buffers
/// for efficiency.
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn new() -> Buffer {
let bytes = [MaybeUninit::<u8>::uninit(); i128::MAX_STR_LEN];
Buffer { bytes }
}
/// Print an integer into this buffer and return a reference to its string
/// representation within the buffer.
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn format<I: Integer>(&mut self, i: I) -> &str {
let buf_ptr = self.bytes.as_mut_ptr().cast::<I::Buffer>();
let string = i.write(unsafe { &mut *buf_ptr });
if string.len() > I::MAX_STR_LEN {
unsafe { hint::unreachable_unchecked() };
}
string
}
}
/// An integer that can be written into an [`itoa::Buffer`][Buffer].
///
/// This trait is sealed and cannot be implemented for types outside of itoa.
pub trait Integer: private::Sealed {
/// The maximum length of string that formatting an integer of this type can
/// produce on the current target platform.
const MAX_STR_LEN: usize;
}
// Seal to prevent downstream implementations of the Integer trait.
mod private {
#[doc(hidden)]
pub trait Sealed: Copy {
#[doc(hidden)]
type Buffer: 'static;
fn write(self, buf: &mut Self::Buffer) -> &str;
}
}
macro_rules! impl_Integer {
($Signed:ident, $Unsigned:ident) => {
const _: () = {
assert!($Signed::MIN < 0, "need signed");
assert!($Unsigned::MIN == 0, "need unsigned");
assert!($Signed::BITS == $Unsigned::BITS, "need counterparts");
};
impl Integer for $Unsigned {
const MAX_STR_LEN: usize = $Unsigned::MAX.ilog10() as usize + 1;
}
impl private::Sealed for $Unsigned {
type Buffer = [MaybeUninit<u8>; Self::MAX_STR_LEN];
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
fn write(self, buf: &mut Self::Buffer) -> &str {
let offset = Unsigned::fmt(self, buf);
// SAFETY: Starting from `offset`, all elements of the slice have been set.
unsafe { slice_buffer_to_str(buf, offset) }
}
}
impl Integer for $Signed {
const MAX_STR_LEN: usize = $Signed::MAX.ilog10() as usize + 2;
}
impl private::Sealed for $Signed {
type Buffer = [MaybeUninit<u8>; Self::MAX_STR_LEN];
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
fn write(self, buf: &mut Self::Buffer) -> &str {
let mut offset = Self::MAX_STR_LEN - $Unsigned::MAX_STR_LEN;
offset += Unsigned::fmt(
self.unsigned_abs(),
(&mut buf[offset..]).try_into().unwrap(),
);
if self < 0 {
offset -= 1;
buf[offset].write(b'-');
}
// SAFETY: Starting from `offset`, all elements of the slice have been set.
unsafe { slice_buffer_to_str(buf, offset) }
}
}
};
}
impl_Integer!(i8, u8);
impl_Integer!(i16, u16);
impl_Integer!(i32, u32);
impl_Integer!(i64, u64);
impl_Integer!(i128, u128);
macro_rules! impl_Integer_size {
($t:ty as $primitive:ident #[cfg(target_pointer_width = $width:literal)]) => {
#[cfg(target_pointer_width = $width)]
impl Integer for $t {
const MAX_STR_LEN: usize = <$primitive as Integer>::MAX_STR_LEN;
}
#[cfg(target_pointer_width = $width)]
impl private::Sealed for $t {
type Buffer = <$primitive as private::Sealed>::Buffer;
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
fn write(self, buf: &mut Self::Buffer) -> &str {
(self as $primitive).write(buf)
}
}
};
}
impl_Integer_size!(isize as i16 #[cfg(target_pointer_width = "16")]);
impl_Integer_size!(usize as u16 #[cfg(target_pointer_width = "16")]);
impl_Integer_size!(isize as i32 #[cfg(target_pointer_width = "32")]);
impl_Integer_size!(usize as u32 #[cfg(target_pointer_width = "32")]);
impl_Integer_size!(isize as i64 #[cfg(target_pointer_width = "64")]);
impl_Integer_size!(usize as u64 #[cfg(target_pointer_width = "64")]);
#[repr(C, align(2))]
struct DecimalPairs([u8; 200]);
// The string of all two-digit numbers in range 00..99 is used as a lookup table.
static DECIMAL_PAIRS: DecimalPairs = DecimalPairs(
*b"0001020304050607080910111213141516171819\
2021222324252627282930313233343536373839\
4041424344454647484950515253545556575859\
6061626364656667686970717273747576777879\
8081828384858687888990919293949596979899",
);
// Returns {value / 100, value % 100} correct for values of up to 4 digits.
fn divmod100(value: u32) -> (u32, u32) {
debug_assert!(value < 10_000);
const EXP: u32 = 19; // 19 is faster or equal to 12 even for 3 digits.
const SIG: u32 = (1 << EXP) / 100 + 1;
let div = (value * SIG) >> EXP; // value / 100
(div, value - div * 100)
}
/// This function converts a slice of ascii characters into a `&str` starting
/// from `offset`.
///
/// # Safety
///
/// `buf` content starting from `offset` index MUST BE initialized and MUST BE
/// ascii characters.
#[cfg_attr(feature = "no-panic", no_panic)]
unsafe fn slice_buffer_to_str(buf: &[MaybeUninit<u8>], offset: usize) -> &str {
// SAFETY: `offset` is always included between 0 and `buf`'s length.
let written = unsafe { buf.get_unchecked(offset..) };
// SAFETY: (`assume_init_ref`) All buf content since offset is set.
// SAFETY: (`from_utf8_unchecked`) Writes use ASCII from the lookup table exclusively.
unsafe { str::from_utf8_unchecked(&*(written as *const [MaybeUninit<u8>] as *const [u8])) }
}
trait Unsigned: Integer {
fn fmt(self, buf: &mut Self::Buffer) -> usize;
}
macro_rules! impl_Unsigned {
($Unsigned:ident) => {
impl Unsigned for $Unsigned {
#[cfg_attr(feature = "no-panic", no_panic)]
fn fmt(self, buf: &mut Self::Buffer) -> usize {
// Count the number of bytes in buf that are not initialized.
let mut offset = buf.len();
// Consume the least-significant decimals from a working copy.
let mut remain = self;
// Format per four digits from the lookup table.
// Four digits need a 16-bit $Unsigned or wider.
while mem::size_of::<Self>() > 1
&& remain
> 999
.try_into()
.expect("branch is not hit for types that cannot fit 999 (u8)")
{
offset -= 4;
// pull two pairs
let scale: Self = 1_00_00
.try_into()
.expect("branch is not hit for types that cannot fit 1E4 (u8)");
let quad = remain % scale;
remain /= scale;
let (pair1, pair2) = divmod100(quad as u32);
unsafe {
buf[offset + 0]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 0));
buf[offset + 1]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 1));
buf[offset + 2]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 0));
buf[offset + 3]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 1));
}
}
// Format per two digits from the lookup table.
if remain > 9 {
offset -= 2;
let (last, pair) = divmod100(remain as u32);
remain = last as Self;
unsafe {
buf[offset + 0]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair as usize * 2 + 0));
buf[offset + 1]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair as usize * 2 + 1));
}
}
// Format the last remaining digit, if any.
if remain != 0 || self == 0 {
offset -= 1;
// Either the compiler sees that remain < 10, or it prevents
// a boundary check up next.
let last = remain as u8 & 15;
buf[offset].write(b'0' + last);
// not used: remain = 0;
}
offset
}
}
};
}
impl_Unsigned!(u8);
impl_Unsigned!(u16);
impl_Unsigned!(u32);
impl_Unsigned!(u64);
impl Unsigned for u128 {
#[cfg_attr(feature = "no-panic", no_panic)]
fn fmt(self, buf: &mut Self::Buffer) -> usize {
// Optimize common-case zero, which would also need special treatment due to
// its "leading" zero.
if self == 0 {
let offset = buf.len() - 1;
buf[offset].write(b'0');
return offset;
}
// Take the 16 least-significant decimals.
let (quot_1e16, mod_1e16) = div_rem_1e16(self);
let (mut remain, mut offset) = if quot_1e16 == 0 {
(mod_1e16, u128::MAX_STR_LEN)
} else {
// Write digits at buf[23..39].
enc_16lsd::<{ u128::MAX_STR_LEN - 16 }>(buf, mod_1e16);
// Take another 16 decimals.
let (quot2, mod2) = div_rem_1e16(quot_1e16);
if quot2 == 0 {
(mod2, u128::MAX_STR_LEN - 16)
} else {
// Write digits at buf[7..23].
enc_16lsd::<{ u128::MAX_STR_LEN - 32 }>(buf, mod2);
// Quot2 has at most 7 decimals remaining after two 1e16 divisions.
(quot2 as u64, u128::MAX_STR_LEN - 32)
}
};
// Format per four digits from the lookup table.
while remain > 999 {
offset -= 4;
// pull two pairs
let quad = remain % 1_00_00;
remain /= 1_00_00;
let (pair1, pair2) = divmod100(quad as u32);
unsafe {
buf[offset + 0].write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 0));
buf[offset + 1].write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 1));
buf[offset + 2].write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 0));
buf[offset + 3].write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 1));
}
}
// Format per two digits from the lookup table.
if remain > 9 {
offset -= 2;
let (last, pair) = divmod100(remain as u32);
remain = last as u64;
unsafe {
buf[offset + 0].write(*DECIMAL_PAIRS.0.get_unchecked(pair as usize * 2 + 0));
buf[offset + 1].write(*DECIMAL_PAIRS.0.get_unchecked(pair as usize * 2 + 1));
}
}
// Format the last remaining digit, if any.
if remain != 0 {
offset -= 1;
// Either the compiler sees that remain < 10, or it prevents
// a boundary check up next.
let last = remain as u8 & 15;
buf[offset].write(b'0' + last);
// not used: remain = 0;
}
offset
}
}
// Encodes the 16 least-significant decimals of n into `buf[OFFSET..OFFSET + 16]`.
#[cfg_attr(feature = "no-panic", no_panic)]
fn enc_16lsd<const OFFSET: usize>(buf: &mut [MaybeUninit<u8>], n: u64) {
// Consume the least-significant decimals from a working copy.
let mut remain = n;
// Format per four digits from the lookup table.
for quad_index in (1..4).rev() {
// pull two pairs
let quad = remain % 1_00_00;
remain /= 1_00_00;
let (pair1, pair2) = divmod100(quad as u32);
unsafe {
buf[quad_index * 4 + OFFSET + 0]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 0));
buf[quad_index * 4 + OFFSET + 1]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 1));
buf[quad_index * 4 + OFFSET + 2]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 0));
buf[quad_index * 4 + OFFSET + 3]
.write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 1));
}
}
// final two pairs
let (pair1, pair2) = divmod100(remain as u32);
unsafe {
buf[OFFSET + 0].write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 0));
buf[OFFSET + 1].write(*DECIMAL_PAIRS.0.get_unchecked(pair1 as usize * 2 + 1));
buf[OFFSET + 2].write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 0));
buf[OFFSET + 3].write(*DECIMAL_PAIRS.0.get_unchecked(pair2 as usize * 2 + 1));
}
}
// Euclidean division plus remainder with constant 1E16 basically consumes 16
// decimals from n.
//
// The integer division algorithm is based on the following paper:
//
// T. Granlund and P. Montgomery, “Division by Invariant Integers Using Multiplication”
// in Proc. of the SIGPLAN94 Conference on Programming Language Design and
// Implementation, 1994, pp. 61–72
//
#[cfg_attr(feature = "no-panic", no_panic)]
fn div_rem_1e16(n: u128) -> (u128, u64) {
const D: u128 = 1_0000_0000_0000_0000;
// The check inlines well with the caller flow.
if n < D {
return (0, n as u64);
}
// These constant values are computed with the CHOOSE_MULTIPLIER procedure
// from the Granlund & Montgomery paper, using N=128, prec=128 and d=1E16.
const M_HIGH: u128 = 76624777043294442917917351357515459181;
const SH_POST: u8 = 51;
// n.widening_mul(M_HIGH).1 >> SH_POST
let quot = u128_ext::mulhi(n, M_HIGH) >> SH_POST;
let rem = n - quot * D;
(quot, rem as u64)
}
+22
View File
@@ -0,0 +1,22 @@
#[cfg(feature = "no-panic")]
use no_panic::no_panic;
/// Multiply unsigned 128 bit integers, return upper 128 bits of the result
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub(crate) fn mulhi(x: u128, y: u128) -> u128 {
let x_lo = x as u64;
let x_hi = (x >> 64) as u64;
let y_lo = y as u64;
let y_hi = (y >> 64) as u64;
// handle possibility of overflow
let carry = (u128::from(x_lo) * u128::from(y_lo)) >> 64;
let m = u128::from(x_lo) * u128::from(y_hi) + carry;
let high1 = m >> 64;
let m_lo = m as u64;
let high2 = (u128::from(x_hi) * u128::from(y_lo) + u128::from(m_lo)) >> 64;
u128::from(x_hi) * u128::from(y_hi) + high1 + high2
}
+45
View File
@@ -0,0 +1,45 @@
#![allow(non_snake_case)]
macro_rules! test {
($($name:ident($value:expr, $expected:expr))*) => {
$(
#[test]
fn $name() {
let mut buffer = itoa::Buffer::new();
let s = buffer.format($value);
assert_eq!(s, $expected);
}
)*
}
}
test! {
test_u64_0(0u64, "0")
test_u64_half(u64::from(u32::MAX), "4294967295")
test_u64_max(u64::MAX, "18446744073709551615")
test_i64_min(i64::MIN, "-9223372036854775808")
test_i16_0(0i16, "0")
test_i16_min(i16::MIN, "-32768")
test_u128_0(0u128, "0")
test_u128_max(u128::MAX, "340282366920938463463374607431768211455")
test_i128_min(i128::MIN, "-170141183460469231731687303715884105728")
test_i128_max(i128::MAX, "170141183460469231731687303715884105727")
}
#[test]
fn test_max_str_len() {
use itoa::Integer as _;
assert_eq!(i8::MAX_STR_LEN, 4);
assert_eq!(u8::MAX_STR_LEN, 3);
assert_eq!(i16::MAX_STR_LEN, 6);
assert_eq!(u16::MAX_STR_LEN, 5);
assert_eq!(i32::MAX_STR_LEN, 11);
assert_eq!(u32::MAX_STR_LEN, 10);
assert_eq!(i64::MAX_STR_LEN, 20);
assert_eq!(u64::MAX_STR_LEN, 20);
assert_eq!(i128::MAX_STR_LEN, 40);
assert_eq!(u128::MAX_STR_LEN, 39);
}
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "5fdb40c054e1fff359a2f7bdf7f87a13b34b465d"
},
"path_in_vcs": ""
}
+1
View File
@@ -0,0 +1 @@
!.github
+16
View File
@@ -0,0 +1,16 @@
{
"rust-analyzer.cargo.allFeatures": false,
"rust-analyzer.linkedProjects": [
"benchmarks/engines/libc/Cargo.toml",
"benchmarks/engines/rust-bytecount/Cargo.toml",
"benchmarks/engines/rust-jetscii/Cargo.toml",
"benchmarks/engines/rust-memchr/Cargo.toml",
"benchmarks/engines/rust-memchrold/Cargo.toml",
"benchmarks/engines/rust-sliceslice/Cargo.toml",
"benchmarks/engines/rust-std/Cargo.toml",
"benchmarks/engines/stringzilla/Cargo.toml",
"benchmarks/shared/Cargo.toml",
"fuzz/Cargo.toml",
"Cargo.toml"
]
}
+38
View File
@@ -0,0 +1,38 @@
# AI Policy
Using AI (i.e., LLMs) as tools for coding is welcome. A high bar is held for
all contributions to this project. Moreover, the project maintainers remain
responsible for any code that is published as part of a release. Contributors
are expected to be responsible for any code they publish.
**AI should not be used to generate comments when communicating with
maintainers**. Comments are expected to be written by humans. Comments that are
believed to be written by AI may be hidden without notice.
If you are opening an issue, you should be able to describe the problem in your
own words.
If you are opening a pull request, you are expected to be able to explain the
proposed changes in your own words. This includes the pull request body and
responses to questions. **Do not copy responses from the AI when replying to
questions from maintainers.**
This project requires a human in the loop who understands the work produced
by AI. **Autonomous agents are not allowed to be used for contributing to our
projects**. Pull requests that appear in violation of this will be closed,
perhaps without notice.
If you wish to include context from an interaction with AI in your comments, it
must be in a quote block (e.g., using `>`) and disclosed as such. It must be
accompanied by human commentary explaining the relevance and implications of
the context. Do not share long snippets.
AI is useful when communicating as a non-native English speaker. If you are
using AI to edit your comments for this purpose, please take the time to ensure
it reflects your own voice and ideas. If using AI for translation, we recommend
writing in your native language and including the AI translation in a quote
block.
This policy was adapted from [uv's AI policy].
[uv's AI policy]: https://github.com/astral-sh/.github/blob/c5187e200db51bfe11d56e13053d29bd3793fdd8/AI_POLICY.md
+8
View File
@@ -0,0 +1,8 @@
# Contributing
## Use of AI
All use of AI in contributions must follow the
[AI Policy](https://github.com/BurntSushi/jiff/blob/master/AI_POLICY.md).
Contributions not following the AI Policy will be closed.
+3
View File
@@ -0,0 +1,3 @@
This project is dual-licensed under the Unlicense and MIT licenses.
You may use this code under the terms of either license.
+80
View File
@@ -0,0 +1,80 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "cfg-if"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
[[package]]
name = "getrandom"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "libc"
version = "0.2.176"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
[[package]]
name = "log"
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
[[package]]
name = "memchr"
version = "2.8.3"
dependencies = [
"log",
"quickcheck",
"rustc-std-workspace-core",
]
[[package]]
name = "quickcheck"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6"
dependencies = [
"rand",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "rustc-std-workspace-core"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9c45b374136f52f2d6311062c7146bff20fec063c3f5d46a410bd937746955"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+89
View File
@@ -0,0 +1,89 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.61"
name = "memchr"
version = "2.8.3"
authors = [
"Andrew Gallant <jamslam@gmail.com>",
"bluss",
]
build = false
exclude = [
"/.github",
"/benchmarks",
"/fuzz",
"/scripts",
"/tmp",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for
1, 2 or 3 byte search and single substring search.
"""
homepage = "https://github.com/BurntSushi/memchr"
documentation = "https://docs.rs/memchr/"
readme = "README.md"
keywords = [
"memchr",
"memmem",
"substring",
"find",
"search",
]
license = "Unlicense OR MIT"
repository = "https://github.com/BurntSushi/memchr"
[package.metadata.docs.rs]
rustdoc-args = ["--generate-link-to-definition"]
[features]
alloc = []
default = ["std"]
libc = []
logging = ["dep:log"]
rustc-dep-of-std = ["core"]
std = ["alloc"]
use_std = ["std"]
[lib]
name = "memchr"
path = "src/lib.rs"
bench = false
[dependencies.core]
version = "1.0.0"
optional = true
package = "rustc-std-workspace-core"
[dependencies.log]
version = "0.4.20"
optional = true
[dev-dependencies.quickcheck]
version = "1.0.3"
default-features = false
[profile.bench]
debug = 2
[profile.release]
debug = 2
[profile.test]
opt-level = 3
debug = 2
+78
View File
@@ -0,0 +1,78 @@
[package]
name = "memchr"
version = "2.8.3" #:version
authors = ["Andrew Gallant <jamslam@gmail.com>", "bluss"]
description = """
Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for
1, 2 or 3 byte search and single substring search.
"""
documentation = "https://docs.rs/memchr/"
homepage = "https://github.com/BurntSushi/memchr"
repository = "https://github.com/BurntSushi/memchr"
readme = "README.md"
keywords = ["memchr", "memmem", "substring", "find", "search"]
license = "Unlicense OR MIT"
exclude = ["/.github", "/benchmarks", "/fuzz", "/scripts", "/tmp"]
edition = "2021"
rust-version = "1.61"
[lib]
name = "memchr"
bench = false
[features]
default = ["std"]
# The 'std' feature permits the memchr crate to use the standard library. This
# permits this crate to use runtime CPU feature detection to automatically
# accelerate searching via vector instructions. Without the standard library,
# this automatic detection is not possible.
std = ["alloc"]
# The 'alloc' feature enables some APIs that require allocation, such as
# 'Finder::into_owned'. Note that this feature does not enable runtime CPU
# feature detection. That still requires 'std'.
alloc = []
# When enabled (it's disabled by default), the `log` crate will be used to
# emit a spattering of log messages. For the most part, the log messages are
# meant to indicate what strategies are being employed. For example, whether
# a vector or a scalar algorithm is used for substring search. This can be
# useful when debugging performance problems.
#
# This is disabled by default.
logging = ["dep:log"]
# The 'use_std' feature is DEPRECATED. It will be removed in memchr 3. Until
# then, it is alias for the 'std' feature.
use_std = ["std"]
# The 'libc' feature has been DEPRECATED and no longer has any effect.
libc = []
# Internal feature, only used when building as part of libstd, not part of the
# stable interface of this crate.
rustc-dep-of-std = ['core']
[dependencies]
# Only used when the `logging` feature is enabled (disabled by default).
log = { version = "0.4.20", optional = true }
# Internal feature, only used when building as part of libstd, not part of the
# stable interface of this crate.
core = { version = '1.0.0', optional = true, package = 'rustc-std-workspace-core' }
[dev-dependencies]
quickcheck = { version = "1.0.3", default-features = false }
[profile.release]
debug = true
[profile.bench]
debug = true
[profile.test]
opt-level = 3
debug = true
[package.metadata.docs.rs]
rustdoc-args = ["--generate-link-to-definition"]
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Andrew Gallant
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+196
View File
@@ -0,0 +1,196 @@
memchr
======
This library provides heavily optimized routines for string search primitives.
[![Build status](https://github.com/BurntSushi/memchr/workflows/ci/badge.svg)](https://github.com/BurntSushi/memchr/actions)
[![Crates.io](https://img.shields.io/crates/v/memchr.svg)](https://crates.io/crates/memchr)
Dual-licensed under MIT or the [UNLICENSE](https://unlicense.org/).
### Documentation
[https://docs.rs/memchr](https://docs.rs/memchr)
### Overview
* The top-level module provides routines for searching for 1, 2 or 3 bytes
in the forward or reverse direction. When searching for more than one byte,
positions are considered a match if the byte at that position matches any
of the bytes.
* The `memmem` sub-module provides forward and reverse substring search
routines.
In all such cases, routines operate on `&[u8]` without regard to encoding. This
is exactly what you want when searching either UTF-8 or arbitrary bytes.
### Compiling without the standard library
memchr links to the standard library by default, but you can disable the
`std` feature if you want to use it in a `#![no_std]` crate:
```toml
[dependencies]
memchr = { version = "2", default-features = false }
```
On `x86_64` platforms, when the `std` feature is disabled, the SSE2 accelerated
implementations will be used. When `std` is enabled, AVX2 accelerated
implementations will be used if the CPU is determined to support it at runtime.
SIMD accelerated routines are also available on the `wasm32` and `aarch64`
targets. The `std` feature is not required to use them.
When a SIMD version is not available, then this crate falls back to
[SWAR](https://en.wikipedia.org/wiki/SWAR) techniques.
### Minimum Rust version policy
This crate's minimum supported `rustc` version is `1.61.0`.
The current policy is that the minimum Rust version required to use this crate
can be increased in minor version updates. For example, if `crate 1.0` requires
Rust 1.20.0, then `crate 1.0.z` for all values of `z` will also require Rust
1.20.0 or newer. However, `crate 1.y` for `y > 0` may require a newer minimum
version of Rust.
In general, this crate will be conservative with respect to the minimum
supported version of Rust.
### Testing strategy
Given the complexity of the code in this crate, along with the pervasive use
of `unsafe`, this crate has an extensive testing strategy. It combines multiple
approaches:
* Hand-written tests.
* Exhaustive-style testing meant to exercise all possible branching and offset
calculations.
* Property based testing through [`quickcheck`](https://github.com/BurntSushi/quickcheck).
* Fuzz testing through [`cargo fuzz`](https://github.com/rust-fuzz/cargo-fuzz).
* A huge suite of benchmarks that are also run as tests. Benchmarks always
confirm that the expected result occurs.
Improvements to the testing infrastructure are very welcome.
### Algorithms used
At time of writing, this crate's implementation of substring search actually
has a few different algorithms to choose from depending on the situation.
* For very small haystacks,
[Rabin-Karp](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm)
is used to reduce latency. Rabin-Karp has very small overhead and can often
complete before other searchers have even been constructed.
* For small needles, a variant of the
["Generic SIMD"](http://0x80.pl/articles/simd-strfind.html#algorithm-1-generic-simd)
algorithm is used. Instead of using the first and last bytes, a heuristic is
used to select bytes based on a background distribution of byte frequencies.
* In all other cases,
[Two-Way](https://en.wikipedia.org/wiki/Two-way_string-matching_algorithm)
is used. If possible, a prefilter based on the "Generic SIMD" algorithm
linked above is used to find candidates quickly. A dynamic heuristic is used
to detect if the prefilter is ineffective, and if so, disables it.
### Why is the standard library's substring search so much slower?
We'll start by establishing what the difference in performance actually
is. There are two relevant benchmark classes to consider: `prebuilt` and
`oneshot`. The `prebuilt` benchmarks are designed to measure---to the extent
possible---search time only. That is, the benchmark first starts by building a
searcher and then only tracking the time for _using_ the searcher:
```
$ rebar rank benchmarks/record/x86_64/2023-08-26.csv --intersection -e memchr/memmem/prebuilt -e std/memmem/prebuilt
Engine Version Geometric mean of speed ratios Benchmark count
------ ------- ------------------------------ ---------------
rust/memchr/memmem/prebuilt 2.5.0 1.03 53
rust/std/memmem/prebuilt 1.73.0-nightly 180dffba1 6.50 53
```
Conversely, the `oneshot` benchmark class measures the time it takes to both
build the searcher _and_ use it:
```
$ rebar rank benchmarks/record/x86_64/2023-08-26.csv --intersection -e memchr/memmem/oneshot -e std/memmem/oneshot
Engine Version Geometric mean of speed ratios Benchmark count
------ ------- ------------------------------ ---------------
rust/memchr/memmem/oneshot 2.5.0 1.04 53
rust/std/memmem/oneshot 1.73.0-nightly 180dffba1 5.26 53
```
**NOTE:** Replace `rebar rank` with `rebar cmp` in the above commands to
explore the specific benchmarks and their differences.
So in both cases, this crate is quite a bit faster over a broad sampling of
benchmarks regardless of whether you measure only search time or search time
plus construction time. The difference is a little smaller when you include
construction time in your measurements.
These two different types of benchmark classes make for a nice segue into
one reason why the standard library's substring search can be slower: API
design. In the standard library, the only APIs available to you require
one to re-construct the searcher for every search. While you can benefit
from building a searcher once and iterating over all matches in a single
string, you cannot reuse that searcher to search other strings. This might
come up when, for example, searching a file one line at a time. You'll need
to re-build the searcher for every line searched, and this can [really
matter][burntsushi-bstr-blog].
**NOTE:** The `prebuilt` benchmark for the standard library can't actually
avoid measuring searcher construction at some level, because there is no API
for it. Instead, the benchmark consists of building the searcher once and then
finding all matches in a single string via an iterator. This tends to
approximate a benchmark where searcher construction isn't measured, but it
isn't perfect. While this means the comparison is not strictly
apples-to-apples, it does reflect what is maximally possible with the standard
library, and thus reflects the best that one could do in a real world scenario.
While there is more to the story than just API design here, it's important to
point out that even if the standard library's substring search were a precise
clone of this crate internally, it would still be at a disadvantage in some
workloads because of its API. (The same also applies to C's standard library
`memmem` function. There is no way to amortize construction of the searcher.
You need to pay for it on every call.)
The other reason for the difference in performance is that
the standard library has trouble using SIMD. In particular, substring search
is implemented in the `core` library, where platform specific code generally
can't exist. That's an issue because in order to utilize SIMD beyond SSE2
while maintaining portable binaries, one needs to use [dynamic CPU feature
detection][dynamic-cpu], and that in turn requires platform specific code.
While there is [an RFC for enabling target feature detection in
`core`][core-feature], it doesn't yet exist.
The bottom line here is that `core`'s substring search implementation is
limited to making use of SSE2, but not AVX.
Still though, this crate does accelerate substring search even when only SSE2
is available. The standard library could therefore adopt the techniques in this
crate just for SSE2. The reason why that hasn't happened yet isn't totally
clear to me. It likely needs a champion to push it through. The standard
library tends to be more conservative in these things. With that said, the
standard library does use some [SSE2 acceleration on `x86-64`][std-sse2] added
in [this PR][std-sse2-pr]. However, at the time of writing, it is only used
for short needles and doesn't use the frequency based heuristics found in this
crate.
**NOTE:** Another thing worth mentioning is that the standard library's
substring search routine requires that both the needle and haystack have type
`&str`. Unless you can assume that your data is valid UTF-8, building a `&str`
will come with the overhead of UTF-8 validation. This may in turn result in
overall slower searching depending on your workload. In contrast, the `memchr`
crate permits both the needle and the haystack to have type `&[u8]`, where
`&[u8]` can be created from a `&str` with zero cost. Therefore, the substring
search in this crate is strictly more flexible than what the standard library
provides.
[burntsushi-bstr-blog]: https://blog.burntsushi.net/bstr/#motivation-based-on-performance
[dynamic-cpu]: https://doc.rust-lang.org/std/arch/index.html#dynamic-cpu-feature-detection
[core-feature]: https://github.com/rust-lang/rfcs/pull/3469
[std-sse2]: https://github.com/rust-lang/rust/blob/bf9229a2e366b4c311f059014a4aa08af16de5d8/library/core/src/str/pattern.rs#L1719-L1857
[std-sse2-pr]: https://github.com/rust-lang/rust/pull/103779

Some files were not shown because too many files have changed in this diff Show More