Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7cda3064e | ||
|
|
484f479b90 | ||
|
|
2d3417b7d3 | ||
|
|
cc14543ced | ||
|
|
a34cf20628 | ||
|
|
abb6bfd35d | ||
|
|
dce31c8784 | ||
|
|
32ab0d75ba | ||
|
|
2c5eccae55 | ||
|
|
18b5fac584 | ||
|
|
34bccbd437 | ||
|
|
e036d99f02 | ||
|
|
43a09c158a | ||
|
|
c752fc6d8b | ||
|
|
802f254e9a | ||
|
|
8d48e488bd | ||
|
|
baf19ed6c8 | ||
|
|
6b24c85fce | ||
|
|
95568d7339 | ||
|
|
d612bb6521 | ||
|
|
c1736f65e8 | ||
|
|
553f6a04fb | ||
|
|
997771ab5e | ||
|
|
ad31cfbafa | ||
|
|
67a33b8221 | ||
|
|
13b1787e1a | ||
|
|
5a6b895113 | ||
|
|
93c47d90ef | ||
|
|
f6af71138c | ||
|
|
8564ced65d | ||
|
|
78baeb8c31 | ||
|
|
a16a4385f8 | ||
|
|
79f492e5e8 | ||
|
|
b0d81b5d0e | ||
|
|
dccbefc8b7 | ||
|
|
894b22277f | ||
|
|
64e1a9ae2b | ||
|
|
2b07d27c67 | ||
|
|
42509a6383 | ||
|
|
5048156b74 | ||
|
|
5a1a7948b1 | ||
|
|
2c6535f948 | ||
|
|
e3e0dab0ec | ||
|
|
97ea7a4f65 | ||
|
|
b25d6b2a71 | ||
|
|
914fb8bef7 | ||
|
|
6ab645e731 | ||
|
|
b62d64adfb | ||
|
|
fe0c2d43ce | ||
|
|
96f84dc283 | ||
|
|
5aa6349e27 | ||
|
|
724b3da478 | ||
|
|
ef399d0ca5 | ||
|
|
4139576155 | ||
|
|
c616429669 | ||
|
|
9ed94bd01f | ||
|
|
3028ef29fb | ||
|
|
99fb12d725 | ||
|
|
367f07d956 | ||
|
|
29749fee4a | ||
|
|
1f558ef596 | ||
|
|
576f834169 | ||
|
|
093cb62212 | ||
|
|
e928140351 | ||
|
|
2e42bedb84 | ||
|
|
c424f7e192 | ||
|
|
0b785eebb5 | ||
|
|
885a71b6fe | ||
|
|
8672507fa4 | ||
|
|
37f1f8433b | ||
|
|
b703c757e4 | ||
|
|
98d891fc67 | ||
|
|
d6e043d79f | ||
|
|
ba286758c7 | ||
|
|
b65e6bc9f1 | ||
|
|
f7aeeaa2eb | ||
|
|
1b0607cbd8 | ||
|
|
ae7745772a | ||
|
|
28af64daa5 | ||
|
|
871a2cd3f7 | ||
|
|
322766cf63 | ||
|
|
c13db2a5ba | ||
|
|
777322c66b | ||
|
|
629dff22fe | ||
|
|
1d000e037b | ||
|
|
c0df4371f7 | ||
|
|
e2be7ff6de | ||
|
|
88d9b99165 | ||
|
|
361a6f4587 | ||
|
|
e19cc7a66b | ||
|
|
d496742500 | ||
|
|
9d705ec44f | ||
|
|
17e73f246a | ||
|
|
017a0eb22c | ||
|
|
a4f499ce12 | ||
|
|
7c361aecd9 | ||
|
|
b9686af9c8 | ||
|
|
212c9198eb | ||
|
|
be0a57a1d9 | ||
|
|
e8faf398f5 | ||
|
|
0c9731a8f9 | ||
|
|
8bdcd8fb83 | ||
|
|
148a0ce5e4 | ||
|
|
23a67af7db | ||
|
|
885a4571ff | ||
|
|
e746efcb94 | ||
|
|
709d07775b | ||
|
|
16c9d4962a | ||
|
|
b59791e0c5 | ||
|
|
283287f74f | ||
|
|
5501dfd66d | ||
|
|
98f3eb75c0 | ||
|
|
ffaa51a092 | ||
|
|
853cb845ff | ||
|
|
a226191c1c | ||
|
|
e9a3c3a669 | ||
|
|
9d84b7164e | ||
|
|
895081e509 | ||
|
|
e460bdc139 | ||
|
|
b76b74cb63 | ||
|
|
a951509350 | ||
|
|
46460fcec3 | ||
|
|
289ad40d86 | ||
|
|
f0c9d4d904 | ||
|
|
5f6e7dd40d | ||
|
|
c93de9fe41 | ||
|
|
f6b5df831e | ||
|
|
d1d7c576cf | ||
|
|
4922e49853 | ||
|
|
c82693e9c1 | ||
|
|
8d19cdeae6 | ||
|
|
772c4aad11 | ||
|
|
52e6093011 | ||
|
|
79c6c72fd6 | ||
|
|
7fd9c8eee3 | ||
|
|
f302bbbb24 | ||
|
|
e83ced0e20 | ||
|
|
5faeb77411 | ||
|
|
b22b494ede | ||
|
|
6c23ce847d | ||
|
|
1d0c275a04 | ||
|
|
6a466a611f | ||
|
|
ea8030b707 | ||
|
|
5aab1e0131 | ||
|
|
1300d7e372 | ||
|
|
66e4f3d47a | ||
|
|
f1b4780e2c | ||
|
|
37028cc3eb | ||
|
|
f6889940c3 | ||
|
|
0e6fd9269b | ||
|
|
31caf922b8 | ||
|
|
3d63bbb3eb | ||
|
|
c0f892c539 | ||
|
|
5d8f14c992 | ||
|
|
a5fe65021b | ||
|
|
6f87f48dca | ||
|
|
b1eb641729 | ||
|
|
7d398caa66 | ||
|
|
ebea5f5cfd | ||
|
|
96dd7bf6d2 | ||
|
|
024df31e66 | ||
|
|
59249d44d3 | ||
|
|
11c068e03e | ||
|
|
f011557cd5 | ||
|
|
db198c05f6 | ||
|
|
d52996c02a | ||
|
|
2e6bcd51a1 | ||
|
|
b59aa8d9c1 | ||
|
|
9e01f2d5d3 | ||
|
|
523ec5fd0b | ||
|
|
f1f7662afa | ||
|
|
a1d8e34390 | ||
|
|
b17c9826c7 | ||
|
|
2d6233cdc7 | ||
|
|
086ad87296 | ||
|
|
eb9dcf830b | ||
|
|
58eeaf1dd4 | ||
|
|
af49d4905d | ||
|
|
c7df11210a | ||
|
|
8fa9e5d9e6 | ||
|
|
c48e7b616d | ||
|
|
492fe68c9e | ||
|
|
c9e5f22d03 | ||
|
|
f215cb3196 | ||
|
|
4cea798651 | ||
|
|
6e3b798273 | ||
|
|
11adff8278 | ||
|
|
16b55b58e3 | ||
|
|
ea6dbf3e6c | ||
|
|
90a2fe12d5 | ||
|
|
bb8e6b3872 | ||
|
|
bc38a4a787 | ||
|
|
3d7de8ffb7 | ||
|
|
654b205e00 | ||
|
|
19a3408912 | ||
|
|
ece32ef55f | ||
|
|
970cf5bb9d | ||
|
|
5cd77eb5de | ||
|
|
a2d0365813 | ||
|
|
e7a23faa5a | ||
|
|
e9c3f36970 | ||
|
|
e0f9b1ab50 | ||
|
|
98e3b9d6a5 | ||
|
|
323e45ab0e | ||
|
|
5d352139dd | ||
|
|
6fd329e047 | ||
|
|
d3599245f8 | ||
|
|
7d602d2f03 | ||
|
|
d1495ff2d5 | ||
|
|
78b9416985 | ||
|
|
12c00693f8 | ||
|
|
d2afef19a9 | ||
|
|
2e88fdb937 | ||
|
|
e67ffcd204 | ||
|
|
f49083ee96 | ||
|
|
6cf9ed1620 | ||
|
|
2c58237e78 | ||
|
|
4f21677ae5 | ||
|
|
7a7a5b1612 | ||
|
|
9f7d8ebb51 | ||
|
|
7e687e0d5d | ||
|
|
81d726cca2 | ||
|
|
c5f669b3c0 | ||
|
|
74ba049b5c | ||
|
|
751d8c0bda | ||
|
|
46a4f58019 | ||
|
|
212cb30b97 | ||
|
|
e9d7200a05 | ||
|
|
3efc252059 | ||
|
|
544711885e | ||
|
|
bd52429276 | ||
|
|
7d3cebea79 | ||
|
|
a404927a78 | ||
|
|
1ce22d9d9f | ||
|
|
befa97d82b | ||
|
|
4eef88b5df | ||
|
|
ab264f4923 | ||
|
|
af8a33b1a0 | ||
|
|
3ab9d1a4bf |
@@ -0,0 +1,5 @@
|
||||
[source.crates-io]
|
||||
replace-with = "vendored-sources"
|
||||
|
||||
[source.vendored-sources]
|
||||
directory = "vendor"
|
||||
@@ -0,0 +1,7 @@
|
||||
2026-11-10T21:41:18-06:00 1 17293278c1c7 src/web.rs 320 Medium files/file endpoints not token-gated (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 073768bc5201 src/web.rs 389 Medium settings redirect header-splitting via __section/__tab (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 d45a2e52d1ba src/auth.rs 37 Medium RNG fallback to constant csrf/guessable wsid (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 b6701ede5237 src/dashboard.rs 199 Medium settings write error swallowed, reported success (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 1b4915d2c7a6 src/tuning.rs 180 Low set_target kept PID integral across unit-mismatched modes (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 97ba434fdd3a src/console.rs 234 Medium editable-deck new-block id collision (fixed)
|
||||
2026-11-10T21:41:18-06:00 1 0a2a1950ad0d src/web.rs 81 Medium unbounded thread-per-connection DoS (fixed: conn cap)
|
||||
@@ -0,0 +1,44 @@
|
||||
# Code Review Memory
|
||||
|
||||
This file is maintained by the `code-review-harness` skill. It records
|
||||
findings across review sessions so the skill can spot recurring issues
|
||||
and apply more aggressive remediation when an issue persists.
|
||||
|
||||
The skill **reads this file at the start of every review** and **updates
|
||||
it at the end** with new findings.
|
||||
|
||||
## How to use
|
||||
|
||||
- The "Recurring Issues" section is rebuilt automatically each run. Treat
|
||||
it as the high-signal list of things that keep coming back.
|
||||
- The "Session Log" is append-only. Each row is one finding from one
|
||||
session. The log is the source of truth; the index is derived from it.
|
||||
- If a finding has been fixed and you don't want it to count toward
|
||||
recurrence anymore, add a `RESOLVED:` row referencing the finding
|
||||
fingerprint.
|
||||
|
||||
## Recurring Issues
|
||||
|
||||
_(auto-generated — rebuilt at end of each session)_
|
||||
|
||||
<!-- BEGIN RECURRING -->
|
||||
|
||||
_No recurring issues yet — every finding has been a one-off, or memory was just initialized._
|
||||
|
||||
<!-- END RECURRING -->
|
||||
|
||||
## Session Log
|
||||
|
||||
_(append-only)_
|
||||
|
||||
<!-- BEGIN LOG -->
|
||||
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:320` [Medium] files/file endpoints not token-gated (fixed) (fp:17293278c1c7)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:389` [Medium] settings redirect header-splitting via __section/__tab (fixed) (fp:073768bc5201)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/auth.rs:37` [Medium] RNG fallback to constant csrf/guessable wsid (fixed) (fp:d45a2e52d1ba)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/dashboard.rs:199` [Medium] settings write error swallowed, reported success (fixed) (fp:b6701ede5237)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/tuning.rs:180` [Low] set_target kept PID integral across unit-mismatched modes (fixed) (fp:1b4915d2c7a6)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/console.rs:234` [Medium] editable-deck new-block id collision (fixed) (fp:97ba434fdd3a)
|
||||
- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:81` [Medium] unbounded thread-per-connection DoS (fixed: conn cap) (fp:0a2a1950ad0d)
|
||||
|
||||
<!-- END LOG -->
|
||||
@@ -0,0 +1,39 @@
|
||||
name: public-benchmark-pages
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [main-release-gate]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-public-benchmark-pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install SSH client
|
||||
run: |
|
||||
if ! command -v ssh >/dev/null 2>&1; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
fi
|
||||
- name: Render measured benchmark history
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/bench_history.py render
|
||||
- name: Publish public benchmark page
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
|
||||
run: python3 ci/publish-bench-pages.py os
|
||||
- name: Clean generated page
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -0,0 +1,26 @@
|
||||
name: completed-ci-badge
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [main-release-gate, next-build]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-completed-ci-badge
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Publish last completed attempts
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/last-attempt-badge.py
|
||||
@@ -0,0 +1,76 @@
|
||||
name: source-pr
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, next]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-source-pr-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
source:
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Check runner image pins
|
||||
run: python3 ci/check-runner-image.py
|
||||
- name: Detect README-only change
|
||||
id: surface
|
||||
run: |
|
||||
surface=full
|
||||
if [ "$GITHUB_EVENT_NAME" = pull_request ] &&
|
||||
{ [ "$GITHUB_BASE_REF" = main ] || [ "$GITHUB_BASE_REF" = next ]; } &&
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF" 2>/dev/null)" &&
|
||||
changed="$(git diff --no-renames --name-only "$base" HEAD)" &&
|
||||
[ "$changed" = README.md ]; then
|
||||
surface=documentation
|
||||
fi
|
||||
echo "surface=$surface" >> "$GITHUB_OUTPUT"
|
||||
- name: Check README-only change
|
||||
if: steps.surface.outputs.surface == 'documentation'
|
||||
run: |
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
|
||||
git diff --check "$base" HEAD -- . ':(exclude)vendor' ':(exclude)third-party'
|
||||
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; then
|
||||
echo "private key material found in tracked source" >&2
|
||||
exit 1
|
||||
else
|
||||
status=$?
|
||||
[ "$status" -eq 1 ]
|
||||
fi
|
||||
- name: Check patch whitespace
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
# Vendored crates (vendor/) and the flare-ui source (third-party/) keep
|
||||
# their upstream bytes (cargo vendor checksums, byte-exact fixtures).
|
||||
if [ "$GITHUB_EVENT_NAME" = pull_request ]; then
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
|
||||
git diff --check "$base" HEAD -- . ':(exclude)vendor' ':(exclude)third-party'
|
||||
else
|
||||
git diff --check HEAD^ HEAD -- . ':(exclude)vendor' ':(exclude)third-party'
|
||||
fi
|
||||
- name: Check CI and evidence tools
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
python3 -m compileall -q ci
|
||||
for test in ci/test-*.py; do python3 "$test"; done
|
||||
python3 ci/evidence_status.py
|
||||
python3 ci/experiment_priority.py
|
||||
- name: Check source
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: |
|
||||
rustup component add rustfmt
|
||||
cargo fmt --check
|
||||
cargo test --locked
|
||||
- name: Clean generated source check
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -0,0 +1,140 @@
|
||||
name: main-release-gate
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-main
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
verify-and-release:
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Install Pages SSH client
|
||||
run: |
|
||||
if ! command -v ssh >/dev/null 2>&1; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
fi
|
||||
- name: Install Rust quality tools
|
||||
run: rustup component add rustfmt clippy
|
||||
- name: Image safety gate
|
||||
run: sh ci/check-image-safety.sh
|
||||
- name: .afw format tests
|
||||
run: python3 ci/test-afw.py
|
||||
- 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: Metric badge checks
|
||||
run: python3 ci/test-metrics.py
|
||||
- name: Release evidence gate checks
|
||||
run: python3 ci/test-conformance.py
|
||||
- name: Research and experiment report checks
|
||||
run: |
|
||||
python3 ci/test-evidence-status.py
|
||||
python3 ci/test-experiment-priority.py
|
||||
python3 ci/test-pr-surface.py
|
||||
- name: Release publication checks
|
||||
run: python3 ci/test-release.py
|
||||
- name: Release version checks
|
||||
run: python3 ci/test-version.py
|
||||
- name: CI cleanup containment checks
|
||||
run: python3 ci/test-cleanup-generated.py
|
||||
- name: Quality
|
||||
run: |
|
||||
cargo clippy --all-targets --locked -- -D warnings
|
||||
printf '{"format":true,"clippy_warnings_denied":true}\n' > quality-current.json
|
||||
- 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 --test-threads=1 | tee bench-current.txt
|
||||
- name: Coverage tool
|
||||
run: |
|
||||
rustup component add llvm-tools-preview
|
||||
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
|
||||
- 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 --quality-gate quality-current.json
|
||||
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
|
||||
with:
|
||||
name: alkane-os-metrics
|
||||
path: |
|
||||
badges/metrics.json
|
||||
quality-current.json
|
||||
coverage/tests.json
|
||||
coverage/bench.json
|
||||
bench-current.txt
|
||||
- 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: Separate research from release evidence
|
||||
run: python3 ci/evidence_status.py --output evidence-status-current.json
|
||||
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
|
||||
with:
|
||||
name: alkane-os-evidence-status
|
||||
path: evidence-status-current.json
|
||||
- name: Pairing and simulator conformance
|
||||
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
|
||||
- name: Clean generated build and benchmark work
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -0,0 +1,45 @@
|
||||
name: next-build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [next]
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-next
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Image safety gate
|
||||
run: sh ci/check-image-safety.sh
|
||||
- name: .afw format tests
|
||||
run: python3 ci/test-afw.py
|
||||
- name: Build release candidate
|
||||
run: cargo build --release --offline --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
|
||||
- name: Clean generated candidate build
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -0,0 +1,4 @@
|
||||
/target/
|
||||
/dist/
|
||||
/coverage/
|
||||
__pycache__/
|
||||
@@ -0,0 +1,7 @@
|
||||
# Alkane OS working rules
|
||||
|
||||
- Keep the project MIT-licensed and preserve third-party licenses in vendored dependencies.
|
||||
- Use run-scoped Cargo output for one-off work. In CI, set `CARGO_TARGET_DIR=target` and remove generated target, coverage, benchmark, and release staging after artifact publication, including failed runs.
|
||||
- Keep the main release gate on all seven boards, all 64 same-vendor pairings, unmodified stock firmware evidence, and genuine pool acceptance from real captured silicon nonces. Do not promote host-only probes to board conformance.
|
||||
- Keep mining, tuning, HAL, API, protocol parsing, and on-device runtime logic in Rust. Use Python only for host tests, CI, release work, and disposable diagnostics unless a documented interface requires it.
|
||||
- No emojis in files or persisted text.
|
||||
@@ -0,0 +1,548 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alkane-os"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"flare-ui",
|
||||
"maud",
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[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.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[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.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
|
||||
dependencies = [
|
||||
"anes",
|
||||
"cast",
|
||||
"ciborium",
|
||||
"clap",
|
||||
"criterion-plot",
|
||||
"is-terminal",
|
||||
"itertools",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"oorandom",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"tinytemplate",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion-plot"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
|
||||
dependencies = [
|
||||
"cast",
|
||||
"itertools",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "flare-ui"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"maud",
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[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 = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
|
||||
|
||||
[[package]]
|
||||
name = "is-terminal"
|
||||
version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "maud"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"maud_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maud_macros"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"proc-macro2-diagnostics",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[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 = "proc-macro2-diagnostics"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[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.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[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 3.0.9",
|
||||
]
|
||||
|
||||
[[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 = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[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 = "tinytemplate"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[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-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[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 = "wschema"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,28 @@
|
||||
[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"] }
|
||||
flare-ui = { path = "third-party/flare-ui/crates/flare-ui" }
|
||||
wschema = { path = "third-party/flare-ui/crates/wschema" }
|
||||
maud = "0.27"
|
||||
|
||||
[workspace]
|
||||
members = ["third-party/flare-ui/crates/flare-ui", "third-party/flare-ui/crates/wschema"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.1"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
license = "MIT"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
@@ -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.
|
||||
|
||||
@@ -1,3 +1,76 @@
|
||||
# CI badges
|
||||
# Alkane OS
|
||||
|
||||
Machine-maintained status for the last completed main and next workflow attempts.
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-os/actions)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
Rust mining and tuning core for Alkane control boards. The
|
||||
[SDK](https://gitea.bluefla.re/blueflare/alkane-sdk) builds board images and
|
||||
provides the hardware backend. The on-board web console is the parameterised
|
||||
`flare-ui`: a sidebar shell with live telemetry (readings) and real controls
|
||||
(mode/target, start/stop) that drive the runtime, with `/api/...` as the
|
||||
interface of record behind every page.
|
||||
|
||||
## Status
|
||||
|
||||
The host miner supports BM1362 and BM1366 through the SDK's simulator HAL and
|
||||
Stratum V1. Tests have replayed 33 captured BM1366 shares and one BM1362
|
||||
share to a loopback pool with matching ACCEPT responses. Production board
|
||||
control is still under development.
|
||||
|
||||
The BM1370 module encodes a captured S21 Pro job and parses captured nonce
|
||||
frames. Work-ID mapping, chain control, and pool acceptance remain open.
|
||||
|
||||
The HAL client requests PSU shutdown on sensor faults and reserves work IDs
|
||||
until a confirmed reset or shutdown. A production backend still needs a
|
||||
power lease, watchdog, and validated temperature limits. SHA-256d and
|
||||
Litecoin Scrypt proof verification are implemented; Scrypt chip report
|
||||
handling and mining remain open.
|
||||
|
||||
Run `alkane-os --list-targets` for the target matrix. Set `POOL_PASSWORD` to
|
||||
the pool password, then mine with a simulator HAL socket and Stratum V1 pool:
|
||||
|
||||
```sh
|
||||
ALKANE_POOL_PASSWORD="$POOL_PASSWORD" alkane-os --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1366
|
||||
```
|
||||
|
||||
Use `BM1362` for that chip. Set `ALKANE_API_LISTEN=127.0.0.1:4028` for
|
||||
read-only `summary` and `version` commands; reach it remotely through SSH.
|
||||
|
||||
To bring up the full web console on a workstation with no hashboard, run
|
||||
`alkane-os --serve-sim`: a reference HAL runs in-process, the runtime boots
|
||||
against it, and the printed URL serves the live, controllable console (the
|
||||
frequency moves toward the target; start/stop and mode changes take effect).
|
||||
`alkane-os --serve` serves the same console with no backend, for a board whose
|
||||
HAL backend is not written yet. `ALKANE_WEB_LISTEN=ADDR` overrides the bind
|
||||
(default port 80, or 8080 without privilege).
|
||||
|
||||
## Release gate
|
||||
|
||||
`main` runs tests, benchmarks, and conformance before release; `next` builds
|
||||
release candidates. The release gate is red. It requires all 64 same-vendor
|
||||
pairings (52 Bitmain, 12 WhatsMiner), unmodified stock firmware, captured
|
||||
silicon nonces, difficulty-1 pool acceptance, and bench-validated models.
|
||||
Stock firmware may faithfully reject a pairing; Alkane OS must mine it.
|
||||
See the [evidence contract](ci/CONFORMANCE.md).
|
||||
|
||||
Badges cover host code, not board conformance. See the public
|
||||
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/os/).
|
||||
|
||||
## Local checks
|
||||
|
||||
```sh
|
||||
CARGO_TARGET_DIR=/var/tmp/alkane-os-target cargo test --locked
|
||||
```
|
||||
|
||||
Use an executable target directory if the source mount is `noexec`.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE). Vendored dependencies keep their own licenses.
|
||||
|
||||
@@ -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 @@
|
||||
<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 @@
|
||||
<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 @@
|
||||
<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 @@
|
||||
<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 |
@@ -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 @@
|
||||
<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 |
@@ -0,0 +1,63 @@
|
||||
# Release conformance evidence
|
||||
|
||||
`check-conformance.py` is a release gate for all 64 same-vendor cells. It
|
||||
currently fails because the simulator and bench evidence producer is not yet
|
||||
implemented. A green Rust build, host HAL replay probe, or rootfs archive does
|
||||
not fill any cell.
|
||||
|
||||
`research-evidence.json` records scoped historical observations with source
|
||||
hashes. `evidence_status.py` reports those separately from declarations in
|
||||
`conformance.json`. Neither research claims nor manifest declarations count
|
||||
as verified release cells. The current-run checker below is the only release
|
||||
validator. `experiment-queue.json` ranks the next protocol and controller
|
||||
experiments by the number of affected cells; blocked work stays visible.
|
||||
The status report names catalog, decoded protocol, stock simulator boot,
|
||||
captured-nonce pool acceptance, physical lifecycle, and complete-cell levels.
|
||||
It leaves current-run verified counts unset; the conformance checker certifies
|
||||
the full cells separately.
|
||||
|
||||
Each CI run must put a JSON report at
|
||||
`ci/evidence/<GITHUB_RUN_ID>/<board>/<chip>.json`. The report binds its
|
||||
`run_id`, `source_commit`, `os_binary_sha256`, `board`, and `chip` to the
|
||||
current workflow. It records `stock_firmware_modified: false`,
|
||||
`simulator_booted_stock: true`, and a `stock_result` of `mines` or `rejects`.
|
||||
For a rejection, `stock_first_rejection` names the first genuine firmware
|
||||
gate. Reports for stock mining also reference `stock_pool_accept_capture`.
|
||||
|
||||
The report references files under `ci/evidence/` with objects containing
|
||||
`path` and `sha256`: `sdk_image`, `stock_image`, `simulator_trace`,
|
||||
`simulator_model`, `control_capture`, `chip_capture`,
|
||||
`alkane_share_accept_capture`, and `bench_validation`.
|
||||
The checker opens and hashes each file. It loads the trace and capture JSON,
|
||||
checks the current run/image/cell identities, verifies SHA-256d or Litecoin
|
||||
Scrypt nonces against
|
||||
a pool target at difficulty 1 or higher, and requires a matching
|
||||
`mining.submit` and pool ACCEPT response ID. A SHA-256 capture must include
|
||||
the matching `subscription` (`extranonce1`, `extranonce2_size`), full
|
||||
`notify` message, exact decimal `difficulty`, and a `configure_response`
|
||||
with an accepted BIP310 mask when version bits were submitted. A later
|
||||
`version_mask_event` may supply the effective `mining.set_version_mask`.
|
||||
The checker reconstructs
|
||||
the coinbase, merkle root, and complete submitted header; its 80 bytes and
|
||||
calculated difficulty target must match the capture. The trace binds
|
||||
the capture digests.
|
||||
The Scrypt verifier uses [Litecoin's 80-byte, N=1024, r=1, p=1 proof hash](https://github.com/litecoin-project/litecoin/blob/master/src/crypto/scrypt.cpp).
|
||||
Equihash proof verification remains pending, so its cells fail closed.
|
||||
Scrypt cells also remain pending until real silicon reports, stock behavior,
|
||||
and pool acceptance are captured for those chips.
|
||||
Bench calibration names the physical control-board and chip devices, their
|
||||
capture digests, and the simulator model digest. It can be reused across OS
|
||||
commits until the model or a physical capture changes.
|
||||
The fixed digests and artifact paths also appear in `conformance.json` so
|
||||
source review can track what each cell claims.
|
||||
|
||||
The simulator runner must generate these reports by booting pristine stock
|
||||
firmware and Alkane OS in a machine model, with nonce data replayed from
|
||||
real-silicon captures. A rejected stock pairing must show its first rejection
|
||||
in the simulator trace while Alkane OS reaches pool ACCEPT. Bench devices
|
||||
provide independent observations for model validation, not CI dependencies.
|
||||
The checker verifies its input artifacts and reported nonce. It cannot prove
|
||||
that a self-asserted pool response came from a real pool or turn a report into
|
||||
physical evidence. The capture producer must preserve raw request/response
|
||||
bytes and independent provenance. Capture provenance and faithful machine
|
||||
models remain release blockers until the runner and bench validation are built.
|
||||
@@ -0,0 +1,275 @@
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Board profiles used by the .afw producer and the CI checker.
|
||||
|
||||
An .afw is valid for exactly one board family. The arch and bootloader policy
|
||||
come from this table, never from the caller alone, so a bundle cannot claim a
|
||||
board it was not built for. cv1835 and am335x have complete, buildable profiles in this release; the
|
||||
other Antminer families are listed so a wrong-board bundle is rejected by name
|
||||
instead of being accepted as "unknown".
|
||||
"""
|
||||
|
||||
AM335X_PARTITIONS = [
|
||||
{"name": "mtd0", "device": "/dev/mtd0", "offset": 0x0000000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd1", "device": "/dev/mtd1", "offset": 0x0020000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd2", "device": "/dev/mtd2", "offset": 0x0040000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd3", "device": "/dev/mtd3", "offset": 0x0060000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd4", "device": "/dev/mtd4", "offset": 0x0080000, "size": 0x1C0000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd5", "device": "/dev/mtd5", "offset": 0x0240000, "size": 0x20000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd6", "device": "/dev/mtd6", "offset": 0x0260000, "size": 0x20000,
|
||||
"secure": False, "boot_critical": True, "write_order": 2, "image": "dtb"},
|
||||
{"name": "mtd7", "device": "/dev/mtd7", "offset": 0x0280000, "size": 0x500000,
|
||||
"secure": False, "boot_critical": True, "write_order": 3, "image": "kernel"},
|
||||
{"name": "mtd8", "device": "/dev/mtd8", "offset": 0x0800000, "size": 0x1400000,
|
||||
"secure": False, "boot_critical": True, "write_order": 1, "image": "rootfs"},
|
||||
{"name": "mtd9", "device": "/dev/mtd9", "offset": 0x1C00000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": False, "write_order": 0, "image": None},
|
||||
{"name": "mtd10", "device": "/dev/mtd10", "offset": 0x1E00000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": False, "write_order": 0, "image": None},
|
||||
{"name": "mtd11", "device": "/dev/mtd11", "offset": 0x2000000, "size": 0x6000000,
|
||||
"secure": True, "boot_critical": False, "write_order": 0, "image": None},
|
||||
]
|
||||
|
||||
AM335X_IMAGES = [
|
||||
{"name": "kernel", "source": "alkane-am335x.uImage", "role": "kernel",
|
||||
"format": "uimage", "partition": "mtd7", "install": True, "exact_bytes": None},
|
||||
{"name": "dtb", "source": "am335x-alkane.dtb", "role": "dtb",
|
||||
"format": "fdt", "partition": "mtd6", "install": True, "exact_bytes": None},
|
||||
{"name": "rootfs", "source": "alkane-am335x-ramdisk.uImage", "role": "rootfs",
|
||||
"format": "uimage", "partition": "mtd8", "install": True, "exact_bytes": None},
|
||||
]
|
||||
|
||||
# Tier-3 from-stock variant: same 12-partition NAND map, but mtd4 is written
|
||||
# with our non-RSA U-Boot (a legacy uImage the preserved SPL chainloads), so its
|
||||
# secure flag is False and it carries the u-boot image at write_order 3; the
|
||||
# kernel moves to write_order 4 (U-Boot lands before the kernel). The SPL copies
|
||||
# (mtd0-3) and bootenv (mtd5) stay preserved and are never write targets.
|
||||
AM335X_STOCK_PARTITIONS = []
|
||||
for _p in AM335X_PARTITIONS:
|
||||
_q = dict(_p)
|
||||
if _q["name"] == "mtd4":
|
||||
_q.update(secure=False, write_order=3, image="u-boot")
|
||||
elif _q["name"] == "mtd7":
|
||||
_q.update(write_order=4)
|
||||
AM335X_STOCK_PARTITIONS.append(_q)
|
||||
|
||||
AM335X_STOCK_IMAGES = [
|
||||
{"name": "u-boot", "source": "alkane-am335x-uboot-mtd4.uImage", "role": "bootloader",
|
||||
"format": "uimage", "partition": "mtd4", "install": True, "exact_bytes": None},
|
||||
] + [dict(_img) for _img in AM335X_IMAGES]
|
||||
|
||||
BOARDS = {
|
||||
"am335x": {
|
||||
"arch": "arm",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
"format_checks": ["uimage", "fdt", "uimage"],
|
||||
"partitions": AM335X_PARTITIONS,
|
||||
"images": AM335X_IMAGES,
|
||||
},
|
||||
"am335x-stock": {
|
||||
"arch": "arm",
|
||||
"bootloader_policy": "include",
|
||||
"buildable": True,
|
||||
"format_checks": ["uimage", "uimage", "fdt", "uimage"],
|
||||
"partitions": AM335X_STOCK_PARTITIONS,
|
||||
"images": AM335X_STOCK_IMAGES,
|
||||
},
|
||||
"cv1835": {
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
"format_checks": ["fit", "arm64-image", "fdt", "cpio-gzip"],
|
||||
"partitions": [
|
||||
{
|
||||
"name": "p1",
|
||||
"device": "/dev/mmcblk0p1",
|
||||
"offset": 0,
|
||||
"size": 16 * 1024 * 1024,
|
||||
"secure": False,
|
||||
"boot_critical": True,
|
||||
"write_order": 1,
|
||||
"image": "p1",
|
||||
},
|
||||
{
|
||||
"name": "p3",
|
||||
"device": "/dev/mmcblk0p3",
|
||||
"offset": 0,
|
||||
"size": 32 * 1024 * 1024,
|
||||
"secure": True,
|
||||
"boot_critical": False,
|
||||
"write_order": 0,
|
||||
"image": None,
|
||||
},
|
||||
{
|
||||
"name": "boot0",
|
||||
"device": "/dev/mmcblk0boot0",
|
||||
"offset": 0,
|
||||
"size": 4 * 1024 * 1024,
|
||||
"secure": True,
|
||||
"boot_critical": True,
|
||||
"write_order": 0,
|
||||
"image": None,
|
||||
},
|
||||
{
|
||||
"name": "boot1",
|
||||
"device": "/dev/mmcblk0boot1",
|
||||
"offset": 0,
|
||||
"size": 4 * 1024 * 1024,
|
||||
"secure": True,
|
||||
"boot_critical": True,
|
||||
"write_order": 0,
|
||||
"image": None,
|
||||
},
|
||||
],
|
||||
"images": [
|
||||
{
|
||||
"name": "kernel",
|
||||
"source": "Image",
|
||||
"role": "kernel",
|
||||
"format": "arm64-image",
|
||||
"partition": None,
|
||||
"install": False,
|
||||
"exact_bytes": None,
|
||||
},
|
||||
{
|
||||
"name": "dtb",
|
||||
"source": "cv-alkane.dtb",
|
||||
"role": "dtb",
|
||||
"format": "fdt",
|
||||
"partition": None,
|
||||
"install": False,
|
||||
"exact_bytes": None,
|
||||
},
|
||||
{
|
||||
"name": "rootfs",
|
||||
"source": "rootfs.cpio.gz",
|
||||
"role": "rootfs",
|
||||
"format": "cpio-gzip",
|
||||
"partition": None,
|
||||
"install": False,
|
||||
"exact_bytes": None,
|
||||
},
|
||||
{
|
||||
"name": "p1",
|
||||
"source": "alkane-cv1835-p1.fit",
|
||||
"role": "boot",
|
||||
"format": "fit",
|
||||
"partition": "p1",
|
||||
"install": True,
|
||||
"exact_bytes": 16 * 1024 * 1024,
|
||||
},
|
||||
],
|
||||
},
|
||||
# Antminer families that the seven-board release gate still lists. They are
|
||||
# known, so a wrong-board bundle is refused by identity, but they do not
|
||||
# have a buildable .afw profile in this release.
|
||||
"zynq-7010": {
|
||||
"arch": "armv7",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
# kernel (zImage), dtb (FDT), rootfs (gzip cpio ramdisk)
|
||||
"format_checks": ["zimage", "fdt", "cpio-gzip"],
|
||||
# Both bench Zynq-7010 units (S19, S17) share mtd0 (40 MiB: BOOT.bin +
|
||||
# the kernel slot) and mtd1 (32 MiB: ramfs). BOOT.bin (FSBL + FPGA
|
||||
# bitstream + stock U-Boot) is PRESERVED - the bundle carries no
|
||||
# bootloader member; only the kernel slot in mtd0 and the ramfs in mtd1
|
||||
# are our OS. The exact kernel-slot sub-offset is placed by the install
|
||||
# method (it differs by unit), so this profile gates image formats and
|
||||
# size ceilings, not a fixed offset map.
|
||||
"partitions": [
|
||||
{"name": "mtd0", "device": "/dev/mtd0", "offset": 0, "size": 0x2800000,
|
||||
"secure": False, "boot_critical": True, "write_order": 1, "image": "kernel"},
|
||||
{"name": "mtd1", "device": "/dev/mtd1", "offset": 0x2800000, "size": 0x2000000,
|
||||
"secure": False, "boot_critical": True, "write_order": 2, "image": "rootfs"},
|
||||
],
|
||||
"images": [
|
||||
{"name": "kernel", "source": "zImage", "role": "kernel",
|
||||
"format": "zimage", "partition": "mtd0", "install": True, "exact_bytes": None},
|
||||
{"name": "dtb", "source": "zynq-alkane.dtb", "role": "dtb",
|
||||
"format": "fdt", "partition": "mtd0", "install": True, "exact_bytes": None},
|
||||
{"name": "rootfs", "source": "rootfs.cpio.gz", "role": "rootfs",
|
||||
"format": "cpio-gzip", "partition": "mtd1", "install": True, "exact_bytes": None},
|
||||
],
|
||||
},
|
||||
"zynq-s17": {"arch": "armv7", "bootloader_policy": "include", "buildable": False},
|
||||
# Amlogic A113D / AXG (S21 Pro-class) control board. arm64. Our OS is staged
|
||||
# as FILES in the nvdata UBI volume (mtd6): kernel (arm64 Image), dtb, and a
|
||||
# uImage ramdisk. The signed FIP bootloader and the stock boot partition
|
||||
# (mtd0-5) are PRESERVED - zero raw writes outside nvdata, so the stock OS in
|
||||
# mtd4 stays as a one-setenv fallback. Hence bootloader_policy preserve and no
|
||||
# bootloader member.
|
||||
"a113d": {
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"buildable": True,
|
||||
"format_checks": ["arm64-image", "fdt", "uimage"],
|
||||
"partitions": [
|
||||
{"name": "mtd0", "device": "/dev/mtd0", "offset": 0x0000000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd1", "device": "/dev/mtd1", "offset": 0x0800000, "size": 0x800000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd2", "device": "/dev/mtd2", "offset": 0x1000000, "size": 0x200000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd3", "device": "/dev/mtd3", "offset": 0x1200000, "size": 0x1000000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd4", "device": "/dev/mtd4", "offset": 0x2200000, "size": 0x2000000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "mtd5", "device": "/dev/mtd5", "offset": 0x4200000, "size": 0x500000,
|
||||
"secure": True, "boot_critical": True, "write_order": 0, "image": None},
|
||||
{"name": "nvdata", "device": "/dev/mtd6", "offset": 0x4700000, "size": 0xB900000,
|
||||
"secure": False, "boot_critical": True, "write_order": 1, "image": "kernel"},
|
||||
],
|
||||
"images": [
|
||||
{"name": "kernel", "source": "vmlinux.bin", "role": "kernel",
|
||||
"format": "arm64-image", "partition": "nvdata", "install": True, "exact_bytes": None},
|
||||
{"name": "dtb", "source": "devicetree.dtb", "role": "dtb",
|
||||
"format": "fdt", "partition": "nvdata", "install": True, "exact_bytes": None},
|
||||
{"name": "rootfs", "source": "uramdisk.image.gz", "role": "rootfs",
|
||||
"format": "uimage", "partition": "nvdata", "install": True, "exact_bytes": None},
|
||||
],
|
||||
},
|
||||
"a113d-s21pro": {"arch": "arm64", "bootloader_policy": "preserve", "buildable": False},
|
||||
"am335x-bb": {"arch": "armv7", "bootloader_policy": "preserve", "buildable": False},
|
||||
}
|
||||
|
||||
SAFE_IMAGE_FORMATS = {
|
||||
"fit",
|
||||
"arm64-image",
|
||||
"zimage",
|
||||
"fdt",
|
||||
"cpio-gzip",
|
||||
"uimage",
|
||||
"raw",
|
||||
}
|
||||
|
||||
SAFE_IMAGE_ROLES = {
|
||||
"kernel",
|
||||
"dtb",
|
||||
"rootfs",
|
||||
"bootloader",
|
||||
"boot",
|
||||
"component",
|
||||
}
|
||||
|
||||
|
||||
def board(name):
|
||||
"""Return the profile for a board family, or raise KeyError."""
|
||||
return BOARDS[name]
|
||||
|
||||
|
||||
def known_board(name):
|
||||
return name in BOARDS
|
||||
|
||||
|
||||
def expect_arch(name):
|
||||
return BOARDS[name]["arch"]
|
||||
|
||||
|
||||
def expect_policy(name):
|
||||
return BOARDS[name]["bootloader_policy"]
|
||||
@@ -0,0 +1,656 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Generate an .afw manifest and stage its payload members.
|
||||
|
||||
The output is a full OS install bundle for exactly one board family: the
|
||||
manifest names every image, its size and SHA-256, the partition plan, the
|
||||
bootloader policy, the network recovery path and a liveness marker. Payload
|
||||
members are staged under <staging>/payload/ in manifest order.
|
||||
|
||||
This script does not create the tar. ci/make-afw.sh packs the staged members
|
||||
in the fixed order manifest.json, optional manifest.json.sig, then payload.
|
||||
ci/check-afw.py verifies the finished bundle before it is published.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import afw_boards
|
||||
|
||||
SCHEMA = 2
|
||||
P1_LOAD = 0x100200000
|
||||
GOLDEN_LBA_BYTES = 0x300000 * 512
|
||||
REVISION = 40
|
||||
|
||||
AM335X_MAP = {
|
||||
"mtd0": (0x0000000, 0x20000, True, True, 0, None),
|
||||
"mtd1": (0x0020000, 0x20000, True, True, 0, None),
|
||||
"mtd2": (0x0040000, 0x20000, True, True, 0, None),
|
||||
"mtd3": (0x0060000, 0x20000, True, True, 0, None),
|
||||
"mtd4": (0x0080000, 0x1C0000, True, True, 0, None),
|
||||
"mtd5": (0x0240000, 0x20000, True, True, 0, None),
|
||||
"mtd6": (0x0260000, 0x20000, False, True, 2, "dtb"),
|
||||
"mtd7": (0x0280000, 0x500000, False, True, 3, "kernel"),
|
||||
"mtd8": (0x0800000, 0x1400000, False, True, 1, "rootfs"),
|
||||
"mtd9": (0x1C00000, 0x200000, True, False, 0, None),
|
||||
"mtd10": (0x1E00000, 0x200000, True, False, 0, None),
|
||||
"mtd11": (0x2000000, 0x6000000, True, False, 0, None),
|
||||
}
|
||||
AM335X_HOLE = (0x780000, 0x80000)
|
||||
AM335X_CHIP = 0x8000000
|
||||
AM335X_TARGETS = {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_FORMATS = {"kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
# Tier-3 from-stock: same map except mtd4 is a write target (our U-Boot).
|
||||
AM335X_STOCK_MAP = dict(AM335X_MAP)
|
||||
AM335X_STOCK_MAP["mtd4"] = (0x0080000, 0x1C0000, False, True, 3, "u-boot")
|
||||
AM335X_STOCK_MAP["mtd7"] = (0x0280000, 0x500000, False, True, 4, "kernel")
|
||||
AM335X_STOCK_TARGETS = {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_STOCK_FORMATS = {"u-boot": "uimage", "kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_STOCK_CEILINGS = {"u-boot": 0x1C0000, "kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
# SPL copies (mtd0-3) and bootenv (mtd5) must never be written on either tier.
|
||||
AM335X_NEVER_WRITE = {"mtd0", "mtd1", "mtd2", "mtd3", "mtd5"}
|
||||
|
||||
# Zynq-7010 (tier 2, preserve): kernel into the mtd0 kernel slot, dtb, rootfs
|
||||
# into mtd1; BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) preserved.
|
||||
ZYNQ_FORMATS = {"kernel": "zimage", "dtb": "fdt", "rootfs": "cpio-gzip"}
|
||||
ZYNQ_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x2000000}
|
||||
|
||||
# Amlogic A113D/AXG (tier 2, preserve): kernel (arm64 Image), dtb and a uImage
|
||||
# ramdisk are staged as FILES in the nvdata UBI (mtd6); the FIP bootloader and
|
||||
# the stock boot partition (mtd0-5) are preserved. Ceilings keep the three well
|
||||
# within the ~185 MiB usable nvdata UBI.
|
||||
A113D_FORMATS = {"kernel": "arm64-image", "dtb": "fdt", "rootfs": "uimage"}
|
||||
A113D_CEILINGS = {"kernel": 0x4000000, "dtb": 0x100000, "rootfs": 0x6000000}
|
||||
A113D_NVDATA_USABLE = 0xB900000 # mtd6 nvdata size; the three images must fit
|
||||
|
||||
|
||||
def die(message):
|
||||
print(f"afw_manifest: error: {message}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def sha256_bytes(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def git_revision(path):
|
||||
try:
|
||||
return subprocess.check_output(
|
||||
["git", "-C", str(path), "rev-parse", "HEAD"],
|
||||
text=True,
|
||||
stderr=subprocess.DEVNULL,
|
||||
).strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return None
|
||||
|
||||
|
||||
def check_revision(name, value):
|
||||
if value is None or len(value) != REVISION:
|
||||
die(f"{name} must be a 40-character git revision, got {value!r}")
|
||||
if any(character not in "0123456789abcdef" for character in value):
|
||||
die(f"{name} must be lowercase hexadecimal")
|
||||
return value
|
||||
|
||||
|
||||
def build_date(value):
|
||||
if value is None:
|
||||
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
try:
|
||||
moment = datetime.datetime.fromtimestamp(int(value), datetime.timezone.utc)
|
||||
except (ValueError, OSError):
|
||||
die("SOURCE_DATE_EPOCH must be an integer Unix timestamp")
|
||||
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def magic_ok(fmt, path):
|
||||
with path.open("rb") as source:
|
||||
data = source.read() if fmt == "fit" else source.read(4096)
|
||||
if fmt == "fit":
|
||||
if not data.startswith(b"\xd0\x0d\xfe\xed"):
|
||||
return "does not start with the FIT/FDT magic d00dfeed"
|
||||
if b"config@cv1835_miner_emmc" not in data:
|
||||
return "FIT is missing config@cv1835_miner_emmc"
|
||||
if b"signature@" in data:
|
||||
return "FIT carries signature@ nodes, which this board cannot boot"
|
||||
elif fmt == "fdt":
|
||||
if not data.startswith(b"\xd0\x0d\xfe\xed"):
|
||||
return "does not start with the FDT magic d00dfeed"
|
||||
elif fmt == "arm64-image":
|
||||
if len(data) < 64 or data[0x38:0x3C] != b"ARMd":
|
||||
return "does not carry the arm64 Image ARMd header magic"
|
||||
elif fmt == "cpio-gzip":
|
||||
if not data.startswith(b"\x1f\x8b"):
|
||||
return "is not gzip-compressed"
|
||||
elif fmt == "uimage":
|
||||
if not data.startswith(b"\x27\x05\x19\x56"):
|
||||
return "is not a legacy uImage"
|
||||
return None
|
||||
|
||||
|
||||
def pad_to(source, destination, exact_bytes):
|
||||
size = source.stat().st_size
|
||||
if size > exact_bytes:
|
||||
die(f"{source.name} is {size} bytes, larger than its {exact_bytes}-byte partition")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with source.open("rb") as reader, destination.open("wb") as writer:
|
||||
shutil.copyfileobj(reader, writer)
|
||||
if size < exact_bytes:
|
||||
writer.write(b"\0" * (exact_bytes - size))
|
||||
if destination.stat().st_size != exact_bytes:
|
||||
die(f"{destination.name} did not reach the exact {exact_bytes}-byte size")
|
||||
|
||||
|
||||
def load_plan(path, profile, board):
|
||||
plan = json.loads(Path(path).read_text())
|
||||
if plan.get("board") != board:
|
||||
die(f"plan board {plan.get('board')!r} does not match --board {board!r}")
|
||||
if plan.get("arch") != profile["arch"]:
|
||||
die(f"plan arch {plan.get('arch')!r} does not match {profile['arch']!r}")
|
||||
policy = plan.get("bootloader_policy", profile["bootloader_policy"])
|
||||
if policy != profile["bootloader_policy"]:
|
||||
die(f"plan bootloader_policy {policy!r} does not match {profile['bootloader_policy']!r}")
|
||||
partitions = plan.get("partitions")
|
||||
images = plan.get("images")
|
||||
if not isinstance(partitions, list) or not isinstance(images, list):
|
||||
die("plan must contain partitions and images lists")
|
||||
return partitions, images
|
||||
|
||||
|
||||
def signing_key(path):
|
||||
raw = Path(path).read_bytes()
|
||||
if len(raw) == 64:
|
||||
try:
|
||||
raw = bytes.fromhex(raw.decode("ascii").strip())
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
die("signing key file must be 32 raw bytes or 64 hexadecimal characters")
|
||||
if len(raw) != 32:
|
||||
die("signing key file must be 32 raw bytes or 64 hexadecimal characters")
|
||||
try:
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
except ImportError:
|
||||
die("Ed25519 signing needs the Python cryptography package")
|
||||
private = Ed25519PrivateKey.from_private_bytes(raw)
|
||||
public = private.public_key().public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
||||
)
|
||||
return private, public.hex()
|
||||
|
||||
|
||||
def validate_am335x(partitions, images):
|
||||
"""Reject the AM335x brick paths before a bundle is packed."""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 3:
|
||||
die("am335x must install exactly kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(AM335X_TARGETS):
|
||||
die("am335x install images must be named kernel, dtb and rootfs")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
if "spl" in lowered or "u-boot" in lowered or "uboot" in lowered:
|
||||
die(f"am335x bundle carries an spl/u-boot member: {image['file']!r}")
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != AM335X_FORMATS[name]:
|
||||
die(f"am335x {name} format must be {AM335X_FORMATS[name]}")
|
||||
if image["partition"] != AM335X_TARGETS[name]:
|
||||
die(f"am335x {name} must target {AM335X_TARGETS[name]}")
|
||||
if image["size"] > AM335X_CEILINGS[name]:
|
||||
die(
|
||||
f"am335x {name} is {image['size']} bytes, over the "
|
||||
f"0x{AM335X_CEILINGS[name]:x}-byte ceiling"
|
||||
)
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
if name not in AM335X_MAP:
|
||||
die(f"unknown am335x partition {name!r}")
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_MAP[name]
|
||||
if int(partition["offset"]) != offset:
|
||||
die(f"am335x {name} offset must be 0x{offset:x}")
|
||||
if int(partition["size"]) != size:
|
||||
die(f"am335x {name} size must be 0x{size:x}")
|
||||
if bool(partition["secure"]) is not secure:
|
||||
die(f"am335x {name} secure flag is wrong")
|
||||
if bool(partition["boot_critical"]) is not boot_critical:
|
||||
die(f"am335x {name} boot_critical flag is wrong")
|
||||
if int(partition.get("write_order", 0)) != write_order:
|
||||
die(f"am335x {name} write_order must be {write_order}")
|
||||
if partition.get("image") != image_name:
|
||||
die(f"am335x {name} image must be {image_name!r}")
|
||||
start = int(partition["offset"])
|
||||
end = start + int(partition["size"])
|
||||
hole_start, hole_size = AM335X_HOLE
|
||||
if start < hole_start + hole_size and end > hole_start:
|
||||
die(f"am335x {name} overlaps the 0x780000-0x800000 hole")
|
||||
if name in {f"mtd{index}" for index in range(0, 6)} and write_order != 0:
|
||||
die(f"am335x {name} is preserved and must not be written")
|
||||
if set(seen) != set(AM335X_MAP):
|
||||
die("am335x manifest partition map is incomplete")
|
||||
if int(seen["mtd7"]["offset"]) + int(seen["mtd7"]["size"]) != AM335X_HOLE[0]:
|
||||
die("am335x mtd7 must end at the 0x780000 hole")
|
||||
if int(seen["mtd8"]["offset"]) != AM335X_HOLE[0] + AM335X_HOLE[1]:
|
||||
die("am335x mtd8 must start at 0x800000 after the hole")
|
||||
total = sum(int(part["size"]) for part in partitions)
|
||||
if total != AM335X_CHIP - AM335X_HOLE[1]:
|
||||
die("am335x partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate_am335x_stock(partitions, images):
|
||||
"""Reject the AM335x tier-3 (from-stock) brick paths before packing.
|
||||
|
||||
This bundle DOES write mtd4 (our non-RSA U-Boot), so unlike the tier-2
|
||||
validator it permits a u-boot member - but it still guards every brick
|
||||
path: the four install images are exactly u-boot/kernel/dtb/rootfs, mtd4
|
||||
carries the u-boot and no SPL copy is ever a write target, the 0x780000
|
||||
hole and the 12-partition geometry are exact, and no mtd0-3/mtd5 may hold
|
||||
an image.
|
||||
"""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 4:
|
||||
die("am335x-stock must install exactly u-boot, kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(AM335X_STOCK_TARGETS):
|
||||
die("am335x-stock install images must be named u-boot, kernel, dtb and rootfs")
|
||||
# The U-Boot member is expected here; a loose 'spl' member never is.
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
if "spl" in lowered:
|
||||
die(f"am335x-stock bundle carries an spl member: {image['file']!r}")
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != AM335X_STOCK_FORMATS[name]:
|
||||
die(f"am335x-stock {name} format must be {AM335X_STOCK_FORMATS[name]}")
|
||||
if image["partition"] != AM335X_STOCK_TARGETS[name]:
|
||||
die(f"am335x-stock {name} must target {AM335X_STOCK_TARGETS[name]}")
|
||||
if image["size"] > AM335X_STOCK_CEILINGS[name]:
|
||||
die(
|
||||
f"am335x-stock {name} is {image['size']} bytes, over the "
|
||||
f"0x{AM335X_STOCK_CEILINGS[name]:x}-byte ceiling"
|
||||
)
|
||||
if installs[[img["name"] for img in installs].index("u-boot")]["role"] != "bootloader":
|
||||
die("am335x-stock u-boot image must have role bootloader")
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
if name not in AM335X_STOCK_MAP:
|
||||
die(f"unknown am335x-stock partition {name!r}")
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_STOCK_MAP[name]
|
||||
if int(partition["offset"]) != offset:
|
||||
die(f"am335x-stock {name} offset must be 0x{offset:x}")
|
||||
if int(partition["size"]) != size:
|
||||
die(f"am335x-stock {name} size must be 0x{size:x}")
|
||||
if bool(partition["secure"]) is not secure:
|
||||
die(f"am335x-stock {name} secure flag is wrong")
|
||||
if bool(partition["boot_critical"]) is not boot_critical:
|
||||
die(f"am335x-stock {name} boot_critical flag is wrong")
|
||||
if int(partition.get("write_order", 0)) != write_order:
|
||||
die(f"am335x-stock {name} write_order must be {write_order}")
|
||||
if partition.get("image") != image_name:
|
||||
die(f"am335x-stock {name} image must be {image_name!r}")
|
||||
start = int(partition["offset"])
|
||||
end = start + int(partition["size"])
|
||||
hole_start, hole_size = AM335X_HOLE
|
||||
if start < hole_start + hole_size and end > hole_start:
|
||||
die(f"am335x-stock {name} overlaps the 0x780000-0x800000 hole")
|
||||
if name in AM335X_NEVER_WRITE and (write_order != 0 or partition.get("image") is not None):
|
||||
die(f"am335x-stock {name} is preserved and must not be written")
|
||||
if set(seen) != set(AM335X_STOCK_MAP):
|
||||
die("am335x-stock manifest partition map is incomplete")
|
||||
if int(seen["mtd7"]["offset"]) + int(seen["mtd7"]["size"]) != AM335X_HOLE[0]:
|
||||
die("am335x-stock mtd7 must end at the 0x780000 hole")
|
||||
if int(seen["mtd8"]["offset"]) != AM335X_HOLE[0] + AM335X_HOLE[1]:
|
||||
die("am335x-stock mtd8 must start at 0x800000 after the hole")
|
||||
total = sum(int(part["size"]) for part in partitions)
|
||||
if total != AM335X_CHIP - AM335X_HOLE[1]:
|
||||
die("am335x-stock partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate_zynq(partitions, images):
|
||||
"""Reject the Zynq-7010 brick paths before packing (tier 2, preserve).
|
||||
|
||||
The board reuses the stock BOOT.bin (FSBL + FPGA bitstream + stock U-Boot),
|
||||
so the bundle must carry NO bootloader/spl/BOOT.bin member; it installs our
|
||||
kernel (zImage) into the mtd0 kernel slot, the dtb, and the rootfs
|
||||
(gzip cpio) into mtd1. The exact kernel-slot offset is placed per-unit by the
|
||||
install method, so this gate enforces the image set, formats and the
|
||||
size ceilings (so an oversize image cannot overrun the slot) - not a fixed
|
||||
offset map.
|
||||
"""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 3:
|
||||
die("zynq-7010 must install exactly kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(ZYNQ_FORMATS):
|
||||
die("zynq-7010 install images must be named kernel, dtb and rootfs")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image.get('role','')}".lower()
|
||||
if "spl" in lowered or "u-boot" in lowered or "uboot" in lowered \
|
||||
or "boot.bin" in lowered or image.get("role") == "bootloader":
|
||||
die(f"zynq-7010 bundle carries a bootloader/spl member: {image['file']!r}")
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != ZYNQ_FORMATS[name]:
|
||||
die(f"zynq-7010 {name} format must be {ZYNQ_FORMATS[name]}")
|
||||
if image["size"] > ZYNQ_CEILINGS[name]:
|
||||
die(
|
||||
f"zynq-7010 {name} is {image['size']} bytes, over the "
|
||||
f"0x{ZYNQ_CEILINGS[name]:x}-byte ceiling"
|
||||
)
|
||||
# BOOT.bin lives at the front of mtd0 and is never a write target here.
|
||||
for partition in partitions:
|
||||
if partition.get("image") in (None, "kernel", "rootfs"):
|
||||
continue
|
||||
die(f"zynq-7010 partition {partition['name']!r} has an unexpected image target")
|
||||
|
||||
|
||||
def validate_a113d(partitions, images):
|
||||
"""Reject the Amlogic A113D/AXG brick paths before packing (tier 2, preserve).
|
||||
|
||||
Our OS is staged as files in the nvdata UBI; the signed FIP bootloader and the
|
||||
stock boot partition (mtd0-5) are preserved, so the bundle must carry NO
|
||||
bootloader/spl/tpl/fip member. The kernel (arm64 Image), dtb and uImage
|
||||
ramdisk must fit the nvdata UBI both individually (ceilings) and together.
|
||||
"""
|
||||
installs = [image for image in images if image["install"]]
|
||||
if len(installs) != 3:
|
||||
die("a113d must install exactly kernel, dtb and rootfs")
|
||||
if {image["name"] for image in installs} != set(A113D_FORMATS):
|
||||
die("a113d install images must be named kernel, dtb and rootfs")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image.get('role','')}".lower()
|
||||
if "spl" in lowered or "u-boot" in lowered or "uboot" in lowered \
|
||||
or "fip" in lowered or "tpl" in lowered or image.get("role") == "bootloader":
|
||||
die(f"a113d bundle carries a bootloader/spl/fip member: {image['file']!r}")
|
||||
total = 0
|
||||
for image in installs:
|
||||
name = image["name"]
|
||||
if image["format"] != A113D_FORMATS[name]:
|
||||
die(f"a113d {name} format must be {A113D_FORMATS[name]}")
|
||||
if image["size"] > A113D_CEILINGS[name]:
|
||||
die(f"a113d {name} is {image['size']} bytes, over the 0x{A113D_CEILINGS[name]:x}-byte ceiling")
|
||||
total += image["size"]
|
||||
if total > A113D_NVDATA_USABLE:
|
||||
die(f"a113d images total {total} bytes, over the 0x{A113D_NVDATA_USABLE:x}-byte nvdata UBI")
|
||||
# mtd0-5 (FIP + stock boot) are never a write target.
|
||||
for partition in partitions:
|
||||
if partition["name"] != "nvdata" and partition.get("image") is not None:
|
||||
die(f"a113d partition {partition['name']!r} is preserved and must not carry an image")
|
||||
|
||||
|
||||
def build(args):
|
||||
board = args.board
|
||||
if not afw_boards.known_board(board):
|
||||
die(f"unknown board family {board!r}")
|
||||
profile = afw_boards.board(board)
|
||||
if not profile["buildable"]:
|
||||
die(f"board {board!r} has no buildable .afw profile in this release")
|
||||
|
||||
input_dir = Path(args.input)
|
||||
if not input_dir.is_dir():
|
||||
die(f"input directory does not exist: {input_dir}")
|
||||
|
||||
plan_document = None
|
||||
if args.plan:
|
||||
plan_document = json.loads(Path(args.plan).read_text())
|
||||
partitions, image_specs = load_plan(args.plan, profile, board)
|
||||
else:
|
||||
partitions = profile["partitions"]
|
||||
image_specs = profile["images"]
|
||||
|
||||
staging = Path(args.staging) if args.staging else Path(tempfile.mkdtemp(prefix="afw-manifest."))
|
||||
payload_dir = staging / "payload"
|
||||
payload_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
images = []
|
||||
for spec in image_specs:
|
||||
source_name = spec.get("source", spec.get("file"))
|
||||
if not source_name:
|
||||
die(f"image {spec.get('name')!r} has no source file")
|
||||
source = input_dir / source_name
|
||||
if not source.is_file():
|
||||
die(f"required image is missing: {source}")
|
||||
name = spec["name"]
|
||||
fmt = spec.get("format", "raw")
|
||||
if fmt not in afw_boards.SAFE_IMAGE_FORMATS:
|
||||
die(f"image {name!r} has unsupported format {fmt!r}")
|
||||
role = spec.get("role", "component")
|
||||
if role not in afw_boards.SAFE_IMAGE_ROLES:
|
||||
die(f"image {name!r} has unsupported role {role!r}")
|
||||
target = payload_dir / source.name
|
||||
exact = spec.get("exact_bytes")
|
||||
if exact is not None:
|
||||
pad_to(source, target, int(exact))
|
||||
else:
|
||||
shutil.copyfile(source, target)
|
||||
problem = magic_ok(fmt, target)
|
||||
if problem:
|
||||
die(f"image {name!r} ({target.name}) {problem}")
|
||||
size = target.stat().st_size
|
||||
images.append(
|
||||
{
|
||||
"name": name,
|
||||
"file": f"payload/{target.name}",
|
||||
"role": role,
|
||||
"format": fmt,
|
||||
"size": size,
|
||||
"sha256": sha256_file(target),
|
||||
"partition": spec.get("partition"),
|
||||
"install": bool(spec.get("install", False)),
|
||||
}
|
||||
)
|
||||
|
||||
names = {image["name"] for image in images}
|
||||
for partition in partitions:
|
||||
image_name = partition.get("image")
|
||||
if image_name is not None and image_name not in names:
|
||||
die(f"partition {partition.get('name')!r} references missing image {image_name!r}")
|
||||
if not partition.get("secure", False):
|
||||
size = int(partition.get("size", 0))
|
||||
if size <= 0:
|
||||
die(f"partition {partition.get('name')!r} has no positive size")
|
||||
if partition.get("write_order", 0) > 0 and image_name is None:
|
||||
die(f"installable partition {partition.get('name')!r} has no image")
|
||||
device = partition.get("device", "")
|
||||
if not device.startswith("/dev/"):
|
||||
die(f"partition {partition.get('name')!r} has an invalid device path")
|
||||
if "boot0" in device and not partition.get("secure", False):
|
||||
die("boot0 must be declared secure and must never be a write target")
|
||||
if "boot0" in device and partition.get("write_order", 0) > 0:
|
||||
die("boot0 must not be in the write order")
|
||||
|
||||
for image in images:
|
||||
partition_name = image.get("partition")
|
||||
if partition_name is None:
|
||||
continue
|
||||
matches = [item for item in partitions if item.get("name") == partition_name]
|
||||
if len(matches) != 1:
|
||||
die(f"image {image['name']!r} targets unknown partition {partition_name!r}")
|
||||
partition = matches[0]
|
||||
if partition.get("secure", False):
|
||||
die(f"image {image['name']!r} targets secure partition {partition_name!r}")
|
||||
if image["size"] > int(partition["size"]):
|
||||
die(
|
||||
f"image {image['name']!r} is {image['size']} bytes, larger than "
|
||||
f"partition {partition_name!r} ({partition['size']} bytes)"
|
||||
)
|
||||
exact = image.get("exact_bytes", partition.get("exact_bytes"))
|
||||
if exact is not None and image["size"] != int(exact):
|
||||
die(f"image {image['name']!r} must be exactly {exact} bytes")
|
||||
|
||||
installs = [image for image in images if image["install"]]
|
||||
if not installs:
|
||||
die("bundle has no installable image")
|
||||
if board == "cv1835":
|
||||
if len(installs) != 1 or installs[0]["name"] != "p1":
|
||||
die("cv1835 must install exactly one image, p1")
|
||||
if installs[0]["size"] != 16 * 1024 * 1024:
|
||||
die("cv1835 p1 must be the 16 MiB padded FIT")
|
||||
elif board == "am335x":
|
||||
validate_am335x(partitions, images)
|
||||
elif board == "am335x-stock":
|
||||
validate_am335x_stock(partitions, images)
|
||||
elif board == "zynq-7010":
|
||||
validate_zynq(partitions, images)
|
||||
elif board == "a113d":
|
||||
validate_a113d(partitions, images)
|
||||
|
||||
policy = profile["bootloader_policy"]
|
||||
if policy == "preserve" and any(image["role"] == "bootloader" for image in images):
|
||||
die("bootloader_policy is preserve but the bundle carries a bootloader image")
|
||||
if policy == "include" and not any(image["role"] == "bootloader" for image in images):
|
||||
die("bootloader_policy is include but the bundle has no bootloader image")
|
||||
|
||||
sdk_revision = check_revision(
|
||||
"sdk_revision", args.sdk_revision or (git_revision(args.sdk_dir) if args.sdk_dir else None)
|
||||
)
|
||||
os_revision = check_revision(
|
||||
"os_revision", args.os_revision or (git_revision(args.os_dir) if args.os_dir else None)
|
||||
)
|
||||
|
||||
signature = {
|
||||
"type": "unsigned",
|
||||
"member": None,
|
||||
"public_key_hex": None,
|
||||
}
|
||||
signer = None
|
||||
if args.signing_key:
|
||||
signer, public_hex = signing_key(args.signing_key)
|
||||
signature = {
|
||||
"type": "ed25519",
|
||||
"member": "manifest.json.sig",
|
||||
"public_key_hex": public_hex,
|
||||
}
|
||||
|
||||
if board == "am335x":
|
||||
boot_switch = {
|
||||
"method": "preserved-u-boot-go",
|
||||
"detail": "mtd0-5 (SPL and our non-RSA U-Boot) are preserved and never "
|
||||
"written. The update writes mtd8 root, mtd6 dtb and mtd7 kernel as "
|
||||
"legacy ARM uImages, and the existing boot command loads them.",
|
||||
}
|
||||
preflight = {
|
||||
"required_commands": ["flash_erase", "nandwrite", "nanddump", "md5sum", "sync"],
|
||||
"forbidden_devices": [f"/dev/mtd{index}" for index in range(0, 6)],
|
||||
"min_free_bytes": 32 * 1024 * 1024,
|
||||
"source_os": ["alkane", "ouros", "braiins"],
|
||||
"held_partitions": ["mtd8", "mtd6", "mtd7"],
|
||||
"preserve_partitions": [f"mtd{index}" for index in range(0, 6)],
|
||||
}
|
||||
recovery = {
|
||||
"network": "afw restore --host <ip> --held-backup <mtd8.img> --confirm FLASH",
|
||||
"held_partition": "mtd8",
|
||||
"held_partitions": ["mtd8", "mtd6", "mtd7"],
|
||||
}
|
||||
else:
|
||||
boot_switch = {
|
||||
"method": "partition-overwrite",
|
||||
"detail": "Writing /dev/mmcblk0p1 replaces the FIT. The vendor boot0, "
|
||||
"BL2, BL31 and U-Boot chain is preserved and never written.",
|
||||
}
|
||||
preflight = {
|
||||
"required_commands": ["dd", "md5sum", "sync"],
|
||||
"forbidden_devices": ["/dev/mmcblk0", "/dev/mmcblk0boot0", "/dev/mmcblk0boot1"],
|
||||
"min_free_bytes": 32 * 1024 * 1024,
|
||||
"source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"],
|
||||
}
|
||||
recovery = {
|
||||
"network": "afw restore --host <ip> --held-backup <file>",
|
||||
"held_partition": "p1",
|
||||
"golden_lba_bytes": GOLDEN_LBA_BYTES,
|
||||
}
|
||||
|
||||
manifest = {
|
||||
"schema": SCHEMA,
|
||||
"format": "afw",
|
||||
"board": board,
|
||||
"arch": profile["arch"],
|
||||
"version": args.version,
|
||||
"build_date": build_date(os.environ.get("SOURCE_DATE_EPOCH")),
|
||||
"sdk_revision": sdk_revision,
|
||||
"os_revision": os_revision,
|
||||
"payload_type": "os",
|
||||
"bootloader_policy": policy,
|
||||
"signature": signature,
|
||||
"partitions": [
|
||||
{
|
||||
"name": item["name"],
|
||||
"device": item["device"],
|
||||
"offset": int(item.get("offset", 0)),
|
||||
"size": int(item["size"]),
|
||||
"secure": bool(item.get("secure", False)),
|
||||
"boot_critical": bool(item.get("boot_critical", False)),
|
||||
"write_order": int(item.get("write_order", 0)),
|
||||
"image": item.get("image"),
|
||||
}
|
||||
for item in partitions
|
||||
],
|
||||
"images": images,
|
||||
"boot_switch": boot_switch,
|
||||
"preflight": preflight,
|
||||
"recovery": recovery,
|
||||
"marker": (plan_document or {}).get("marker")
|
||||
or args.marker
|
||||
or ("Alkane" if board == "am335x" else "ALKANE"),
|
||||
"kernel_version": (plan_document or {}).get("kernel_version")
|
||||
or args.kernel_version
|
||||
or "6.18.48",
|
||||
}
|
||||
if args.notes:
|
||||
manifest["notes"] = args.notes
|
||||
|
||||
manifest_path = staging / "manifest.json"
|
||||
manifest_bytes = (json.dumps(manifest, indent=2) + "\n").encode()
|
||||
manifest_path.write_bytes(manifest_bytes)
|
||||
|
||||
if signer is not None:
|
||||
signature_bytes = signer.sign(manifest_bytes)
|
||||
(staging / "manifest.json.sig").write_bytes(signature_bytes)
|
||||
(staging / "manifest.pub").write_text(signature["public_key_hex"] + "\n")
|
||||
|
||||
print(str(manifest_path))
|
||||
return staging, manifest_path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--board", required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--input", required=True, help="SDK board output directory")
|
||||
parser.add_argument("--staging", help="staging directory for manifest.json and payload/")
|
||||
parser.add_argument("--plan", help="plan JSON emitted by alkane-sdk ci/check-plans.py")
|
||||
parser.add_argument("--sdk-revision")
|
||||
parser.add_argument("--os-revision")
|
||||
parser.add_argument("--sdk-dir")
|
||||
parser.add_argument("--os-dir", default=".")
|
||||
parser.add_argument("--signing-key", help="raw 32-byte or 64-hex Ed25519 seed file")
|
||||
parser.add_argument("--kernel-version")
|
||||
parser.add_argument("--marker")
|
||||
parser.add_argument("--notes")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
build(args)
|
||||
except SystemExit:
|
||||
raise
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
die(str(error))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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")
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/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
|
||||
from bench_host import identity as benchmark_host
|
||||
|
||||
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, host=None) -> dict:
|
||||
distance = distance or git_distance
|
||||
choices = []
|
||||
for entry in index.get("entries", []):
|
||||
ancestor = entry.get("sha")
|
||||
if ancestor == sha or not isinstance(ancestor, str):
|
||||
continue
|
||||
if host is not None and entry.get("metrics", {}).get("bench_host") != host:
|
||||
continue
|
||||
gap = distance(ancestor, sha)
|
||||
if gap is not None and gap > 0:
|
||||
choices.append((gap, entry))
|
||||
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"])
|
||||
host = entry["metrics"].get("bench_host", {})
|
||||
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
|
||||
cells.append(f'<td>{html.escape(str(host_label))}</td>')
|
||||
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
|
||||
for name in names]
|
||||
rows.append("<tr>" + "".join(cells) + "</tr>")
|
||||
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><th scope=\"col\">CPU</th>{headings}</tr></thead><tbody>{''.join(rows)}"
|
||||
"</tbody></table></div></body></html>\n")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("prepare", "publish", "render"))
|
||||
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, host=benchmark_host())
|
||||
Path("badges").mkdir(exist_ok=True)
|
||||
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
|
||||
print(f"Loaded {len(baseline)} prior benchmark measurements")
|
||||
return
|
||||
if args.action == "render":
|
||||
if not index["entries"]:
|
||||
raise ValueError("no measured benchmark history to publish")
|
||||
Path("bench-site").mkdir(exist_ok=True)
|
||||
Path("bench-site/index.html").write_text(render_html(index))
|
||||
print(f"Rendered {len(index['entries'])} measured benchmark commits")
|
||||
return
|
||||
metrics = json.loads(Path("badges/metrics.json").read_text())
|
||||
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
index = updated_index(index, sha, metrics, timestamp)
|
||||
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()
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Identify the CPU class used for comparable CI microbenchmark baselines."""
|
||||
|
||||
import os
|
||||
import platform
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def identity() -> dict[str, object]:
|
||||
model = "unknown"
|
||||
cpuinfo = Path("/proc/cpuinfo")
|
||||
if cpuinfo.is_file():
|
||||
for line in cpuinfo.read_text(errors="replace").splitlines():
|
||||
if line.startswith(("model name\t", "Hardware\t", "Processor\t")):
|
||||
model = line.partition(":")[2].strip()[:160]
|
||||
break
|
||||
return {"architecture": platform.machine(), "cpu_model": model,
|
||||
"logical_cpus": os.cpu_count() or 1}
|
||||
@@ -0,0 +1,709 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Verify an .afw OS install bundle before it can be published or installed.
|
||||
|
||||
The gate is deliberately strict and offline. It reads the tar itself instead of
|
||||
trusting GNU tar, checks the fixed member order, rejects path traversal and
|
||||
non-regular members, verifies every payload size and SHA-256 against the
|
||||
manifest, checks the board/arch and bootloader policy, checks each image against
|
||||
its partition ceiling, and refuses a signed bundle it cannot verify.
|
||||
|
||||
Exit codes: 0 pass, 1 failure, 2 usage error.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import afw_boards
|
||||
|
||||
BLOCK = 512
|
||||
MAX_MANIFEST = 64 * 1024
|
||||
MAX_ARCHIVE = 512 * 1024 * 1024
|
||||
|
||||
AM335X_MAP = {
|
||||
"mtd0": (0x0000000, 0x20000, True, True, 0, None),
|
||||
"mtd1": (0x0020000, 0x20000, True, True, 0, None),
|
||||
"mtd2": (0x0040000, 0x20000, True, True, 0, None),
|
||||
"mtd3": (0x0060000, 0x20000, True, True, 0, None),
|
||||
"mtd4": (0x0080000, 0x1C0000, True, True, 0, None),
|
||||
"mtd5": (0x0240000, 0x20000, True, True, 0, None),
|
||||
"mtd6": (0x0260000, 0x20000, False, True, 2, "dtb"),
|
||||
"mtd7": (0x0280000, 0x500000, False, True, 3, "kernel"),
|
||||
"mtd8": (0x0800000, 0x1400000, False, True, 1, "rootfs"),
|
||||
"mtd9": (0x1C00000, 0x200000, True, False, 0, None),
|
||||
"mtd10": (0x1E00000, 0x200000, True, False, 0, None),
|
||||
"mtd11": (0x2000000, 0x6000000, True, False, 0, None),
|
||||
}
|
||||
AM335X_HOLE = (0x780000, 0x80000)
|
||||
AM335X_CHIP = 0x8000000
|
||||
AM335X_TARGETS = {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_FORMATS = {"kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
# Tier-3 from-stock: same map, mtd4 written with our U-Boot; kernel at order 4.
|
||||
AM335X_STOCK_MAP = dict(AM335X_MAP)
|
||||
AM335X_STOCK_MAP["mtd4"] = (0x0080000, 0x1C0000, False, True, 3, "u-boot")
|
||||
AM335X_STOCK_MAP["mtd7"] = (0x0280000, 0x500000, False, True, 4, "kernel")
|
||||
AM335X_STOCK_TARGETS = {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
AM335X_STOCK_FORMATS = {"u-boot": "uimage", "kernel": "uimage", "dtb": "fdt", "rootfs": "uimage"}
|
||||
AM335X_STOCK_CEILINGS = {"u-boot": 0x1C0000, "kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x1400000}
|
||||
AM335X_NEVER_WRITE = {"mtd0", "mtd1", "mtd2", "mtd3", "mtd5"}
|
||||
ZYNQ_FORMATS = {"kernel": "zimage", "dtb": "fdt", "rootfs": "cpio-gzip"}
|
||||
ZYNQ_CEILINGS = {"kernel": 0x500000, "dtb": 0x20000, "rootfs": 0x2000000}
|
||||
A113D_FORMATS = {"kernel": "arm64-image", "dtb": "fdt", "rootfs": "uimage"}
|
||||
A113D_CEILINGS = {"kernel": 0x4000000, "dtb": 0x100000, "rootfs": 0x6000000}
|
||||
A113D_NVDATA_USABLE = 0xB900000
|
||||
|
||||
|
||||
class AfwError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise AfwError(message)
|
||||
|
||||
|
||||
def parse_octal(field, name):
|
||||
text = field.split(b"\0", 1)[0].strip()
|
||||
if not text:
|
||||
return 0
|
||||
if any(byte >= 0x80 for byte in text):
|
||||
fail(f"{name}: base-256 tar numbers are not part of this format")
|
||||
try:
|
||||
return int(text, 8)
|
||||
except ValueError:
|
||||
fail(f"{name}: invalid octal field")
|
||||
|
||||
|
||||
def safe_member_name(name):
|
||||
if not name or len(name) > 255:
|
||||
fail(f"unsafe member name length: {name!r}")
|
||||
if name.startswith("/") or name.startswith("./"):
|
||||
fail(f"absolute or ./-prefixed member is not allowed: {name!r}")
|
||||
if "\\" in name or "\0" in name:
|
||||
fail(f"member name contains a forbidden character: {name!r}")
|
||||
parts = name.split("/")
|
||||
if any(part in ("", ".", "..") for part in parts):
|
||||
fail(f"path traversal or empty component in member name: {name!r}")
|
||||
if any(ord(character) < 0x20 for character in name):
|
||||
fail(f"control character in member name: {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
def read_tar(path):
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
except OSError as error:
|
||||
fail(f"cannot read {path}: {error}")
|
||||
if size == 0 or size > MAX_ARCHIVE:
|
||||
fail(f"archive size {size} is outside the accepted range")
|
||||
if size % BLOCK:
|
||||
fail(f"archive length {size} is not a multiple of {BLOCK} (truncated tar)")
|
||||
data = path.read_bytes()
|
||||
members = []
|
||||
offset = 0
|
||||
zero_blocks = 0
|
||||
while offset < len(data):
|
||||
block = data[offset : offset + BLOCK]
|
||||
offset += BLOCK
|
||||
if block == b"\0" * BLOCK:
|
||||
zero_blocks += 1
|
||||
if zero_blocks == 2:
|
||||
break
|
||||
continue
|
||||
if zero_blocks:
|
||||
fail("non-zero data appears between end-of-archive blocks")
|
||||
if block[257:262] != b"ustar":
|
||||
fail("member header is not POSIX ustar")
|
||||
stored = parse_octal(block[148:156], "tar checksum")
|
||||
header = bytearray(block)
|
||||
header[148:156] = b" " * 8
|
||||
if sum(header) != stored:
|
||||
fail("tar header checksum mismatch")
|
||||
name = block[0:100].split(b"\0", 1)[0].decode("utf-8", "strict")
|
||||
prefix = block[345:500].split(b"\0", 1)[0].decode("utf-8", "strict")
|
||||
if prefix:
|
||||
name = f"{prefix}/{name}"
|
||||
safe_member_name(name)
|
||||
typeflag = block[156:157]
|
||||
if typeflag not in (b"\0", b"0"):
|
||||
fail(f"member {name!r} is not a regular file (typeflag {typeflag!r})")
|
||||
length = parse_octal(block[124:136], f"size of {name}")
|
||||
if length > MAX_ARCHIVE:
|
||||
fail(f"member {name!r} is too large")
|
||||
padded = (length + BLOCK - 1) // BLOCK * BLOCK
|
||||
if offset + padded > len(data):
|
||||
fail(f"member {name!r} runs past the end of the archive (truncated tar)")
|
||||
payload = data[offset : offset + length]
|
||||
offset += padded
|
||||
members.append((name, payload))
|
||||
if zero_blocks < 2:
|
||||
fail("archive has no two-block end marker (truncated tar)")
|
||||
if any(data[offset:]):
|
||||
fail("non-zero trailing bytes after the end-of-archive marker")
|
||||
if not members:
|
||||
fail("archive has no members")
|
||||
names = [name for name, _ in members]
|
||||
if len(names) != len(set(names)):
|
||||
fail("archive has duplicate member names")
|
||||
return members
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
fail(message)
|
||||
|
||||
|
||||
def is_hex(value, length=64):
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and len(value) == length
|
||||
and all(character in "0123456789abcdef" for character in value)
|
||||
)
|
||||
|
||||
|
||||
def check_format(manifest, image, payload, name):
|
||||
fmt = image["format"]
|
||||
if fmt == "fit":
|
||||
require(payload.startswith(b"\xd0\x0d\xfe\xed"), f"{name} is not a FIT")
|
||||
require(b"config@cv1835_miner_emmc" in payload, f"{name} has no default CV config")
|
||||
require(b"signature@" not in payload, f"{name} carries signature@ nodes")
|
||||
elif fmt == "fdt":
|
||||
require(payload.startswith(b"\xd0\x0d\xfe\xed"), f"{name} is not an FDT")
|
||||
elif fmt == "arm64-image":
|
||||
require(len(payload) >= 64 and payload[0x38:0x3C] == b"ARMd", f"{name} is not an arm64 Image")
|
||||
elif fmt == "zimage":
|
||||
# ARM zImage: magic 0x016f2818 (little-endian) at offset 0x24.
|
||||
require(len(payload) >= 0x28 and payload[0x24:0x28] == b"\x18\x28\x6f\x01",
|
||||
f"{name} is not an ARM zImage")
|
||||
elif fmt == "cpio-gzip":
|
||||
require(payload.startswith(b"\x1f\x8b"), f"{name} is not gzip-compressed")
|
||||
elif fmt == "uimage":
|
||||
require(payload.startswith(b"\x27\x05\x19\x56"), f"{name} is not a legacy uImage")
|
||||
if manifest["board"] in ("am335x", "am335x-stock"):
|
||||
require(len(payload) >= 64, f"{name} has no complete uImage header")
|
||||
# ih_arch (byte 29) ARM = 2; ih_type (byte 30): kernel 2, ramdisk 3,
|
||||
# firmware (our U-Boot in mtd4) 5.
|
||||
require(payload[29] == 2, f"{name} is not an ARM uImage")
|
||||
if image["name"] == "rootfs" or image["role"] == "rootfs":
|
||||
require(payload[30] == 3, f"{name} must be a type-3 ramdisk uImage")
|
||||
elif image["name"] == "u-boot" or image["role"] == "bootloader":
|
||||
require(payload[30] == 5, f"{name} must be a type-5 firmware (U-Boot) uImage")
|
||||
else:
|
||||
require(payload[30] == 2, f"{name} must be a type-2 kernel uImage")
|
||||
|
||||
|
||||
def verify_signature(manifest_bytes, manifest, signature_member, public_key):
|
||||
signature = manifest.get("signature")
|
||||
require(isinstance(signature, dict), "manifest signature is not an object")
|
||||
kind = signature.get("type")
|
||||
if kind == "unsigned":
|
||||
require(signature_member is None, "unsigned manifest carries a signature member")
|
||||
require(signature.get("member") is None, "unsigned manifest names a signature member")
|
||||
return "unsigned"
|
||||
require(kind == "ed25519", f"unsupported signature type {kind!r}")
|
||||
require(signature.get("member") == "manifest.json.sig", "signature member name is wrong")
|
||||
require(signature_member is not None, "ed25519 manifest has no signature member")
|
||||
require(len(signature_member) == 64, "manifest.json.sig must be exactly 64 bytes")
|
||||
key_hex = public_key or signature.get("public_key_hex")
|
||||
require(is_hex(key_hex), "ed25519 manifest needs a 32-byte public key")
|
||||
if public_key and signature.get("public_key_hex") not in (None, public_key):
|
||||
fail("--public-key differs from the manifest public_key_hex")
|
||||
try:
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
except ImportError:
|
||||
fail("Ed25519 verification needs the Python cryptography package")
|
||||
try:
|
||||
Ed25519PublicKey.from_public_bytes(bytes.fromhex(key_hex)).verify(
|
||||
signature_member, manifest_bytes
|
||||
)
|
||||
except InvalidSignature:
|
||||
fail("manifest.json.sig does not verify against the public key")
|
||||
return "ed25519"
|
||||
|
||||
|
||||
def validate_am335x(manifest, images, partitions, install_images):
|
||||
require(manifest["arch"] == "arm", "am335x must be arm")
|
||||
require(
|
||||
manifest["bootloader_policy"] == "preserve",
|
||||
"am335x must preserve mtd0-5",
|
||||
)
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
require(
|
||||
"spl" not in lowered and "u-boot" not in lowered and "uboot" not in lowered,
|
||||
f"am335x bundle carries an spl/u-boot member: {image['file']!r}",
|
||||
)
|
||||
require(len(install_images) == 3, "am335x installs exactly kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(AM335X_TARGETS),
|
||||
"am335x install images must be named kernel, dtb and rootfs",
|
||||
)
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(
|
||||
image["format"] == AM335X_FORMATS[name],
|
||||
f"am335x {name} format must be {AM335X_FORMATS[name]}",
|
||||
)
|
||||
require(
|
||||
image["partition"] == AM335X_TARGETS[name],
|
||||
f"am335x {name} must target {AM335X_TARGETS[name]}",
|
||||
)
|
||||
require(
|
||||
image["size"] <= AM335X_CEILINGS[name],
|
||||
f"am335x {name} ({image['size']} B) exceeds the "
|
||||
f"0x{AM335X_CEILINGS[name]:x}-byte mtd ceiling",
|
||||
)
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
require(name in AM335X_MAP, f"unknown am335x partition {name!r}")
|
||||
if name not in AM335X_MAP:
|
||||
continue
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_MAP[name]
|
||||
require(partition["offset"] == offset, f"am335x {name} offset must be 0x{offset:x}")
|
||||
require(partition["size"] == size, f"am335x {name} size must be 0x{size:x}")
|
||||
require(partition["secure"] is secure, f"am335x {name} secure flag is wrong")
|
||||
require(
|
||||
partition["boot_critical"] is boot_critical,
|
||||
f"am335x {name} boot_critical flag is wrong",
|
||||
)
|
||||
require(
|
||||
partition["write_order"] == write_order,
|
||||
f"am335x {name} write_order must be {write_order}",
|
||||
)
|
||||
require(
|
||||
partition.get("image") == image_name,
|
||||
f"am335x {name} image must be {image_name!r}",
|
||||
)
|
||||
start = partition["offset"]
|
||||
end = start + partition["size"]
|
||||
hole_start, hole_size = AM335X_HOLE
|
||||
require(
|
||||
not (start < hole_start + hole_size and end > hole_start),
|
||||
f"am335x {name} overlaps the 0x780000-0x800000 hole",
|
||||
)
|
||||
if name in {f"mtd{index}" for index in range(0, 6)}:
|
||||
require(
|
||||
partition["write_order"] == 0 and partition.get("image") is None,
|
||||
f"am335x {name} is preserved and must not be written",
|
||||
)
|
||||
require(set(seen) == set(AM335X_MAP), "am335x manifest partition map is incomplete")
|
||||
require(
|
||||
seen["mtd7"]["offset"] + seen["mtd7"]["size"] == AM335X_HOLE[0],
|
||||
"am335x mtd7 must end at the 0x780000 hole",
|
||||
)
|
||||
require(
|
||||
seen["mtd8"]["offset"] == AM335X_HOLE[0] + AM335X_HOLE[1],
|
||||
"am335x mtd8 must start at 0x800000 after the hole",
|
||||
)
|
||||
total = sum(part["size"] for part in partitions)
|
||||
require(total == AM335X_CHIP - AM335X_HOLE[1], "am335x partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate_am335x_stock(manifest, images, partitions, install_images):
|
||||
"""Tier-3 from-stock gate: the bundle writes mtd4 (our U-Boot) but must
|
||||
still never touch an SPL copy, and the geometry/ceilings/hole stay exact."""
|
||||
require(manifest["arch"] == "arm", "am335x-stock must be arm")
|
||||
require(
|
||||
manifest["bootloader_policy"] == "include",
|
||||
"am335x-stock must declare bootloader_policy include",
|
||||
)
|
||||
# A u-boot member is expected; a loose spl member never is.
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']}".lower()
|
||||
require("spl" not in lowered, f"am335x-stock bundle carries an spl member: {image['file']!r}")
|
||||
require(len(install_images) == 4, "am335x-stock installs exactly u-boot, kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(AM335X_STOCK_TARGETS),
|
||||
"am335x-stock install images must be named u-boot, kernel, dtb and rootfs",
|
||||
)
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(
|
||||
image["format"] == AM335X_STOCK_FORMATS[name],
|
||||
f"am335x-stock {name} format must be {AM335X_STOCK_FORMATS[name]}",
|
||||
)
|
||||
require(
|
||||
image["partition"] == AM335X_STOCK_TARGETS[name],
|
||||
f"am335x-stock {name} must target {AM335X_STOCK_TARGETS[name]}",
|
||||
)
|
||||
require(
|
||||
image["size"] <= AM335X_STOCK_CEILINGS[name],
|
||||
f"am335x-stock {name} ({image['size']} B) exceeds the "
|
||||
f"0x{AM335X_STOCK_CEILINGS[name]:x}-byte ceiling",
|
||||
)
|
||||
uboot = [image for image in install_images if image["name"] == "u-boot"][0]
|
||||
require(uboot["role"] == "bootloader", "am335x-stock u-boot image must have role bootloader")
|
||||
seen = {}
|
||||
for partition in partitions:
|
||||
name = partition["name"]
|
||||
require(name in AM335X_STOCK_MAP, f"unknown am335x-stock partition {name!r}")
|
||||
seen[name] = partition
|
||||
offset, size, secure, boot_critical, write_order, image_name = AM335X_STOCK_MAP[name]
|
||||
require(partition["offset"] == offset, f"am335x-stock {name} offset must be 0x{offset:x}")
|
||||
require(partition["size"] == size, f"am335x-stock {name} size must be 0x{size:x}")
|
||||
require(partition["secure"] is secure, f"am335x-stock {name} secure flag is wrong")
|
||||
require(
|
||||
partition["boot_critical"] is boot_critical,
|
||||
f"am335x-stock {name} boot_critical flag is wrong",
|
||||
)
|
||||
require(
|
||||
partition["write_order"] == write_order,
|
||||
f"am335x-stock {name} write_order must be {write_order}",
|
||||
)
|
||||
require(partition.get("image") == image_name, f"am335x-stock {name} image must be {image_name!r}")
|
||||
start = partition["offset"]
|
||||
end = start + partition["size"]
|
||||
if start < AM335X_HOLE[0] + AM335X_HOLE[1] and end > AM335X_HOLE[0]:
|
||||
fail(f"am335x-stock {name} overlaps the 0x780000-0x800000 hole")
|
||||
if name in AM335X_NEVER_WRITE and (write_order != 0 or partition.get("image") is not None):
|
||||
fail(f"am335x-stock {name} is preserved and must not be written")
|
||||
require(set(seen) == set(AM335X_STOCK_MAP), "am335x-stock manifest partition map is incomplete")
|
||||
require(
|
||||
seen["mtd7"]["offset"] + seen["mtd7"]["size"] == AM335X_HOLE[0],
|
||||
"am335x-stock mtd7 must end at the 0x780000 hole",
|
||||
)
|
||||
require(
|
||||
seen["mtd8"]["offset"] == AM335X_HOLE[0] + AM335X_HOLE[1],
|
||||
"am335x-stock mtd8 must start at 0x800000 after the hole",
|
||||
)
|
||||
total = sum(part["size"] for part in partitions)
|
||||
require(total == AM335X_CHIP - AM335X_HOLE[1], "am335x-stock partition sizes must sum to 0x7F80000")
|
||||
|
||||
|
||||
def validate(path, allow_unsigned=False, public_key=None, expect_board=None, plan_path=None):
|
||||
members = read_tar(Path(path))
|
||||
if members[0][0] != "manifest.json":
|
||||
fail("first member must be manifest.json")
|
||||
manifest_bytes = members[0][1]
|
||||
if len(manifest_bytes) > MAX_MANIFEST:
|
||||
fail(f"manifest.json is {len(manifest_bytes)} bytes, over the 64 KiB cap")
|
||||
try:
|
||||
manifest = json.loads(manifest_bytes)
|
||||
except (ValueError, UnicodeDecodeError) as error:
|
||||
fail(f"manifest.json is not valid JSON: {error}")
|
||||
require(isinstance(manifest, dict), "manifest.json must be an object")
|
||||
|
||||
required = (
|
||||
"schema",
|
||||
"format",
|
||||
"board",
|
||||
"arch",
|
||||
"version",
|
||||
"build_date",
|
||||
"sdk_revision",
|
||||
"os_revision",
|
||||
"payload_type",
|
||||
"bootloader_policy",
|
||||
"signature",
|
||||
"partitions",
|
||||
"images",
|
||||
"boot_switch",
|
||||
"preflight",
|
||||
"recovery",
|
||||
"marker",
|
||||
"kernel_version",
|
||||
)
|
||||
for key in required:
|
||||
require(key in manifest, f"manifest is missing {key!r}")
|
||||
|
||||
require(manifest["schema"] == 2, "only .afw schema 2 is accepted")
|
||||
require(manifest["format"] == "afw", "manifest format is not afw")
|
||||
require(manifest["payload_type"] == "os", "payload_type must be os")
|
||||
board = manifest["board"]
|
||||
require(afw_boards.known_board(board), f"unknown board family {board!r}")
|
||||
profile = afw_boards.board(board)
|
||||
require(manifest["arch"] == profile["arch"], f"board {board} must use {profile['arch']}")
|
||||
require(
|
||||
manifest["bootloader_policy"] == profile["bootloader_policy"],
|
||||
f"board {board} requires bootloader_policy {profile['bootloader_policy']}",
|
||||
)
|
||||
require(
|
||||
manifest["bootloader_policy"] in ("include", "preserve"),
|
||||
"bootloader_policy must be include or preserve",
|
||||
)
|
||||
if expect_board is not None:
|
||||
require(board == expect_board, f"bundle is for {board}, expected {expect_board}")
|
||||
for field in ("sdk_revision", "os_revision"):
|
||||
require(is_hex(manifest[field], 40), f"{field} must be a 40-character revision")
|
||||
require(isinstance(manifest["version"], str) and manifest["version"], "version is empty")
|
||||
require(isinstance(manifest["build_date"], str) and manifest["build_date"], "build_date is empty")
|
||||
require(isinstance(manifest["marker"], str) and manifest["marker"], "marker is empty")
|
||||
require(
|
||||
isinstance(manifest["kernel_version"], str) and manifest["kernel_version"],
|
||||
"kernel_version is empty",
|
||||
)
|
||||
for field in ("boot_switch", "preflight", "recovery"):
|
||||
require(isinstance(manifest[field], dict), f"{field} must be an object")
|
||||
|
||||
images = manifest["images"]
|
||||
partitions = manifest["partitions"]
|
||||
require(isinstance(images, list) and images, "images must be a non-empty list")
|
||||
require(isinstance(partitions, list) and partitions, "partitions must be a non-empty list")
|
||||
|
||||
image_names = set()
|
||||
install_images = []
|
||||
for image in images:
|
||||
require(isinstance(image, dict), "image entry is not an object")
|
||||
for key in ("name", "file", "role", "format", "size", "sha256", "install"):
|
||||
require(key in image, f"image entry is missing {key!r}")
|
||||
name = image["name"]
|
||||
require(isinstance(name, str) and name and name not in image_names, f"duplicate image {name!r}")
|
||||
image_names.add(name)
|
||||
require(image["role"] in afw_boards.SAFE_IMAGE_ROLES, f"image {name} has an unknown role")
|
||||
require(image["format"] in afw_boards.SAFE_IMAGE_FORMATS, f"image {name} has an unknown format")
|
||||
require(isinstance(image["size"], int) and image["size"] > 0, f"image {name} has no size")
|
||||
require(is_hex(image["sha256"]), f"image {name} has no sha256")
|
||||
require(isinstance(image["install"], bool), f"image {name} install flag is not a bool")
|
||||
safe_member_name(image["file"])
|
||||
require(image["file"].startswith("payload/"), f"image {name} is outside payload/")
|
||||
require(image["file"] not in ("payload/manifest.json",), f"image {name} reuses a reserved name")
|
||||
if image["install"]:
|
||||
require(image.get("partition"), f"installable image {name} has no partition")
|
||||
install_images.append(image)
|
||||
|
||||
require(install_images, "bundle has no installable image")
|
||||
partition_names = set()
|
||||
for partition in partitions:
|
||||
require(isinstance(partition, dict), "partition entry is not an object")
|
||||
for key in ("name", "device", "offset", "size", "secure", "boot_critical", "write_order"):
|
||||
require(key in partition, f"partition entry is missing {key!r}")
|
||||
name = partition["name"]
|
||||
require(isinstance(name, str) and name and name not in partition_names, f"duplicate partition {name!r}")
|
||||
partition_names.add(name)
|
||||
device = partition["device"]
|
||||
require(isinstance(device, str) and device.startswith("/dev/"), f"partition {name} has a bad device")
|
||||
require(isinstance(partition["size"], int) and partition["size"] > 0, f"partition {name} has no size")
|
||||
require(partition["offset"] >= 0, f"partition {name} has a negative offset")
|
||||
require(isinstance(partition["secure"], bool), f"partition {name} secure is not a bool")
|
||||
require(isinstance(partition["boot_critical"], bool), f"partition {name} boot_critical is not a bool")
|
||||
require(isinstance(partition["write_order"], int) and partition["write_order"] >= 0, f"partition {name} write_order")
|
||||
if "boot0" in device:
|
||||
require(partition["secure"], "boot0 must be declared secure")
|
||||
require(partition["write_order"] == 0, "boot0 must not be in the write order")
|
||||
require(partition.get("image") is None, "boot0 must not carry an install image")
|
||||
image_name = partition.get("image")
|
||||
if image_name is not None:
|
||||
require(image_name in image_names, f"partition {name} names missing image {image_name!r}")
|
||||
|
||||
for image in images:
|
||||
if image.get("partition") is None:
|
||||
continue
|
||||
matches = [item for item in partitions if item["name"] == image["partition"]]
|
||||
require(len(matches) == 1, f"image {image['name']} names an unknown partition")
|
||||
partition = matches[0]
|
||||
require(not partition["secure"], f"image {image['name']} targets a secure partition")
|
||||
require(
|
||||
image["size"] <= partition["size"],
|
||||
f"image {image['name']} ({image['size']} B) exceeds partition "
|
||||
f"{partition['name']} ({partition['size']} B)",
|
||||
)
|
||||
|
||||
if board == "am335x":
|
||||
validate_am335x(manifest, images, partitions, install_images)
|
||||
|
||||
if board == "am335x-stock":
|
||||
validate_am335x_stock(manifest, images, partitions, install_images)
|
||||
|
||||
if board == "a113d":
|
||||
require(manifest["arch"] == "arm64", "a113d must be arm64")
|
||||
require(manifest["bootloader_policy"] == "preserve", "a113d must preserve the FIP bootloader")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image['role']}".lower()
|
||||
require(
|
||||
"spl" not in lowered and "u-boot" not in lowered and "uboot" not in lowered
|
||||
and "fip" not in lowered and "tpl" not in lowered and image["role"] != "bootloader",
|
||||
f"a113d bundle carries a bootloader/spl/fip member: {image['file']!r}",
|
||||
)
|
||||
require(len(install_images) == 3, "a113d installs exactly kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(A113D_FORMATS),
|
||||
"a113d install images must be named kernel, dtb and rootfs",
|
||||
)
|
||||
total = 0
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(image["format"] == A113D_FORMATS[name], f"a113d {name} format must be {A113D_FORMATS[name]}")
|
||||
require(
|
||||
image["size"] <= A113D_CEILINGS[name],
|
||||
f"a113d {name} ({image['size']} B) exceeds the 0x{A113D_CEILINGS[name]:x}-byte ceiling",
|
||||
)
|
||||
total += image["size"]
|
||||
require(total <= A113D_NVDATA_USABLE, f"a113d images total {total} B exceed the nvdata UBI (0x{A113D_NVDATA_USABLE:x})")
|
||||
# Only nvdata (mtd6) may carry an image; mtd0-5 (FIP + stock boot) are preserved.
|
||||
for partition in partitions:
|
||||
if partition["name"] != "nvdata":
|
||||
require(partition.get("image") is None, f"a113d {partition['name']!r} is preserved and must not carry an image")
|
||||
|
||||
if board == "zynq-7010":
|
||||
require(manifest["arch"] == "armv7", "zynq-7010 must be armv7")
|
||||
require(manifest["bootloader_policy"] == "preserve", "zynq-7010 must preserve BOOT.bin")
|
||||
for image in images:
|
||||
lowered = f"{image['name']} {image['file']} {image['role']}".lower()
|
||||
require(
|
||||
"spl" not in lowered and "u-boot" not in lowered and "uboot" not in lowered
|
||||
and "boot.bin" not in lowered and image["role"] != "bootloader",
|
||||
f"zynq-7010 bundle carries a bootloader/spl member: {image['file']!r}",
|
||||
)
|
||||
require(len(install_images) == 3, "zynq-7010 installs exactly kernel, dtb and rootfs")
|
||||
require(
|
||||
{image["name"] for image in install_images} == set(ZYNQ_FORMATS),
|
||||
"zynq-7010 install images must be named kernel, dtb and rootfs",
|
||||
)
|
||||
for image in install_images:
|
||||
name = image["name"]
|
||||
require(
|
||||
image["format"] == ZYNQ_FORMATS[name],
|
||||
f"zynq-7010 {name} format must be {ZYNQ_FORMATS[name]}",
|
||||
)
|
||||
require(
|
||||
image["size"] <= ZYNQ_CEILINGS[name],
|
||||
f"zynq-7010 {name} ({image['size']} B) exceeds the "
|
||||
f"0x{ZYNQ_CEILINGS[name]:x}-byte ceiling",
|
||||
)
|
||||
|
||||
if board == "cv1835":
|
||||
require(len(install_images) == 1 and install_images[0]["name"] == "p1", "cv1835 installs only p1")
|
||||
p1 = install_images[0]
|
||||
require(p1["format"] == "fit", "cv1835 p1 must be a FIT")
|
||||
require(p1["size"] == 16 * 1024 * 1024, "cv1835 p1 must be the 16 MiB padded FIT")
|
||||
p1_parts = [item for item in partitions if item["name"] == "p1"]
|
||||
require(len(p1_parts) == 1, "cv1835 manifest must plan p1")
|
||||
require(p1_parts[0]["size"] == 16 * 1024 * 1024, "cv1835 p1 partition must be 16 MiB")
|
||||
require(p1_parts[0]["device"] == "/dev/mmcblk0p1", "cv1835 p1 device is wrong")
|
||||
require(not p1_parts[0]["secure"], "cv1835 p1 must not be secure")
|
||||
require(p1_parts[0]["write_order"] == 1, "cv1835 p1 must be written once")
|
||||
|
||||
if manifest["bootloader_policy"] == "preserve":
|
||||
require(
|
||||
not any(image["role"] == "bootloader" for image in images),
|
||||
"bootloader_policy is preserve but the bundle carries a bootloader image",
|
||||
)
|
||||
else:
|
||||
require(
|
||||
any(image["role"] == "bootloader" for image in images),
|
||||
"bootloader_policy is include but the bundle has no bootloader image",
|
||||
)
|
||||
|
||||
signature = manifest["signature"]
|
||||
require(isinstance(signature, dict), "signature must be an object")
|
||||
kind = signature.get("type")
|
||||
if kind == "unsigned":
|
||||
if not allow_unsigned:
|
||||
fail("bundle is unsigned; pass --allow-unsigned for bench-only use")
|
||||
elif kind != "ed25519":
|
||||
fail(f"unsupported signature type {kind!r}")
|
||||
|
||||
expected = [image["file"] for image in images]
|
||||
signature_member = None
|
||||
body = members[1:]
|
||||
if signature.get("member") is not None:
|
||||
require(len(body) >= 1 and body[0][0] == "manifest.json.sig", "signature member must be second")
|
||||
signature_member = body[0][1]
|
||||
body = body[1:]
|
||||
verify_signature(manifest_bytes, manifest, signature_member, public_key)
|
||||
actual = [name for name, _ in body]
|
||||
require(actual == expected, "payload members are missing, extra, or out of manifest order")
|
||||
|
||||
for (name, payload), image in zip(body, images):
|
||||
require(len(payload) == image["size"], f"size mismatch for {name}")
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
require(digest == image["sha256"], f"sha256 mismatch for {name}")
|
||||
check_format(manifest, image, payload, name)
|
||||
|
||||
summary = {
|
||||
"file": str(path),
|
||||
"board": board,
|
||||
"arch": manifest["arch"],
|
||||
"version": manifest["version"],
|
||||
"bootloader_policy": manifest["bootloader_policy"],
|
||||
"signature": kind,
|
||||
"marker": manifest["marker"],
|
||||
"kernel_version": manifest["kernel_version"],
|
||||
"members": [name for name, _ in members],
|
||||
"payloads": [
|
||||
{"name": image["name"], "file": image["file"], "size": image["size"], "sha256": image["sha256"]}
|
||||
for image in images
|
||||
],
|
||||
"install": [
|
||||
{
|
||||
"image": image["name"],
|
||||
"partition": image["partition"],
|
||||
"size": image["size"],
|
||||
}
|
||||
for image in install_images
|
||||
],
|
||||
}
|
||||
|
||||
if plan_path:
|
||||
plan = json.loads(Path(plan_path).read_text())
|
||||
require(plan.get("board") == board, "plan board differs from manifest board")
|
||||
require(plan.get("arch") == manifest["arch"], "plan arch differs from manifest arch")
|
||||
require(
|
||||
plan.get("bootloader_policy") == manifest["bootloader_policy"],
|
||||
"plan bootloader policy differs from manifest",
|
||||
)
|
||||
plan_parts = {item["name"]: item for item in plan.get("partitions", [])}
|
||||
for partition in partitions:
|
||||
if partition["name"] not in plan_parts:
|
||||
continue
|
||||
require(
|
||||
int(plan_parts[partition["name"]]["size"]) == partition["size"],
|
||||
f"plan size for {partition['name']} differs from the manifest",
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("afw")
|
||||
parser.add_argument("--allow-unsigned", action="store_true")
|
||||
parser.add_argument("--public-key", help="Ed25519 public key hex, or a file containing it")
|
||||
parser.add_argument("--expect-board")
|
||||
parser.add_argument("--plan", help="plan JSON to cross-check")
|
||||
parser.add_argument("--json", action="store_true")
|
||||
parser.add_argument("--quiet", action="store_true")
|
||||
args = parser.parse_args()
|
||||
public_key = args.public_key
|
||||
if public_key and len(public_key) != 64:
|
||||
try:
|
||||
public_key = Path(public_key).read_text().strip()
|
||||
except OSError as error:
|
||||
parser.error(f"cannot read public key: {error}")
|
||||
try:
|
||||
summary = validate(
|
||||
Path(args.afw),
|
||||
allow_unsigned=args.allow_unsigned,
|
||||
public_key=public_key,
|
||||
expect_board=args.expect_board,
|
||||
plan_path=args.plan,
|
||||
)
|
||||
except AfwError as error:
|
||||
print(f"afw: FAIL {args.afw}: {error}", file=sys.stderr)
|
||||
return 1
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"afw: FAIL {args.afw}: {error}", file=sys.stderr)
|
||||
return 1
|
||||
if args.json:
|
||||
print(json.dumps(summary, indent=2))
|
||||
elif not args.quiet:
|
||||
print(f"afw: OK {args.afw}")
|
||||
print(
|
||||
f" board {summary['board']} arch {summary['arch']} version {summary['version']} "
|
||||
f"bootloader {summary['bootloader_policy']} signature {summary['signature']}"
|
||||
)
|
||||
print(f" marker {summary['marker']} kernel {summary['kernel_version']}")
|
||||
for item in summary["payloads"]:
|
||||
print(f" payload {item['name']}: {item['size']} B sha256 {item['sha256']}")
|
||||
for item in summary["install"]:
|
||||
print(f" install {item['image']} -> {item['partition']} ({item['size']} B)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,401 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Require the binary target matrix and traceable per-cell release evidence."""
|
||||
|
||||
import argparse
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
REQUIRED_BOARDS = {
|
||||
"am335x-bb": "bitmain",
|
||||
"zynq-7010": "bitmain",
|
||||
"cv1835": "bitmain",
|
||||
"a113d": "bitmain",
|
||||
"allwinner-h3": "whatsminer",
|
||||
"allwinner-h6": "whatsminer",
|
||||
"allwinner-h616": "whatsminer",
|
||||
}
|
||||
REQUIRED_CHIPS = {
|
||||
**{chip: "bitmain" for chip in (
|
||||
"BM1384", "BM1387", "BM1360", "BM1362", "BM1366", "BM1368",
|
||||
"BM1370", "BM1396", "BM1397", "BM1398", "BM1489", "BM1491", "BM1746",
|
||||
)},
|
||||
**{chip: "whatsminer" for chip in (
|
||||
"KF1950", "ID-1968", "ID-1980", "ID-1990",
|
||||
)},
|
||||
}
|
||||
REQUIRED_ALGORITHMS = {
|
||||
**{chip: "Sha256" for chip in REQUIRED_CHIPS if chip not in
|
||||
("BM1489", "BM1491", "BM1746")},
|
||||
"BM1489": "Scrypt", "BM1491": "Scrypt", "BM1746": "Equihash",
|
||||
}
|
||||
DIGEST = re.compile(r"[0-9a-f]{64}\Z")
|
||||
COMMIT = re.compile(r"[0-9a-f]{40}\Z")
|
||||
DIFF_ONE_TARGET = 0xffff << (8 * (0x1d - 3))
|
||||
MAX_REPORT_BYTES = 1_048_576
|
||||
|
||||
|
||||
def sha256_file(path: pathlib.Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1_048_576), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def load_report(path: pathlib.Path) -> dict:
|
||||
if path.stat().st_size > MAX_REPORT_BYTES:
|
||||
raise ValueError("evidence report exceeds 1 MiB")
|
||||
value = json.loads(path.read_text())
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("evidence report is not an object")
|
||||
return value
|
||||
|
||||
|
||||
def artifact(root: pathlib.Path, value: object) -> pathlib.Path:
|
||||
if not isinstance(value, dict) or not isinstance(value.get("path"), str):
|
||||
raise ValueError("artifact reference is missing")
|
||||
digest = value.get("sha256")
|
||||
if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
|
||||
raise ValueError("artifact digest is invalid")
|
||||
path = (root / value["path"]).resolve()
|
||||
if not path.is_relative_to(root.resolve()) or not path.is_file():
|
||||
raise ValueError("artifact is missing or outside evidence directory")
|
||||
if sha256_file(path) != digest:
|
||||
raise ValueError("artifact digest mismatch")
|
||||
return path
|
||||
|
||||
|
||||
def hex_field(value: object, size: int | None = None) -> bytes:
|
||||
if (not isinstance(value, str) or len(value) & 1
|
||||
or len(value) > 131_072 or not re.fullmatch(r"[0-9a-fA-F]*", value)
|
||||
or (size is not None and len(value) != size * 2)):
|
||||
raise ValueError("invalid Stratum hex field")
|
||||
return bytes.fromhex(value)
|
||||
|
||||
|
||||
def u32_hex(value: object) -> int:
|
||||
return int.from_bytes(hex_field(value, 4), "big")
|
||||
|
||||
|
||||
def reconstructed_header(capture: dict, params: list[str]) -> tuple[bytes, int]:
|
||||
subscription = capture.get("subscription")
|
||||
notify = capture.get("notify")
|
||||
if not isinstance(subscription, dict) or not isinstance(notify, dict):
|
||||
raise ValueError("subscription and notify are required to bind the share")
|
||||
extra1 = hex_field(subscription.get("extranonce1"))
|
||||
extra_size = subscription.get("extranonce2_size")
|
||||
if (len(extra1) > 32 or type(extra_size) is not int
|
||||
or not 0 <= extra_size <= 32):
|
||||
raise ValueError("invalid subscription extranonce")
|
||||
extra2 = hex_field(params[2], extra_size)
|
||||
job = notify.get("params")
|
||||
if (notify.get("method") != "mining.notify" or not isinstance(job, list)
|
||||
or len(job) != 9 or job[0] != params[1]
|
||||
or not isinstance(job[4], list) or len(job[4]) > 64
|
||||
or type(job[8]) is not bool):
|
||||
raise ValueError("submission is not bound to a matching notify")
|
||||
prevhash = hex_field(job[1], 32)
|
||||
coinbase = hex_field(job[2]) + extra1 + extra2 + hex_field(job[3])
|
||||
if len(coinbase) > 65_536:
|
||||
raise ValueError("coinbase exceeds supported size")
|
||||
root = hashlib.sha256(hashlib.sha256(coinbase).digest()).digest()
|
||||
for branch in job[4]:
|
||||
pair = root + hex_field(branch, 32)
|
||||
root = hashlib.sha256(hashlib.sha256(pair).digest()).digest()
|
||||
base_version = u32_hex(job[5])
|
||||
nbits = u32_hex(job[6])
|
||||
u32_hex(job[7])
|
||||
submitted_ntime = u32_hex(params[3])
|
||||
submitted_nonce = u32_hex(params[4])
|
||||
if len(params) == 6:
|
||||
configure = capture.get("configure_response")
|
||||
result = configure.get("result") if isinstance(configure, dict) else None
|
||||
if not isinstance(result, dict) or result.get("version-rolling") is not True:
|
||||
raise ValueError("version rolling was not negotiated")
|
||||
mask_text = result.get("version-rolling.mask")
|
||||
mask_event = capture.get("version_mask_event")
|
||||
if mask_event is not None:
|
||||
fields = mask_event.get("params") if isinstance(mask_event, dict) else None
|
||||
if (not isinstance(mask_event, dict)
|
||||
or mask_event.get("method") != "mining.set_version_mask"
|
||||
or not isinstance(fields, list) or len(fields) != 1):
|
||||
raise ValueError("invalid effective version mask event")
|
||||
mask_text = fields[0]
|
||||
mask = u32_hex(mask_text)
|
||||
bits = u32_hex(params[5])
|
||||
if bits & ~mask:
|
||||
raise ValueError("submitted version bits exceed negotiated mask")
|
||||
version = (base_version & ~mask) | bits
|
||||
else:
|
||||
if capture.get("configure_response") is not None or capture.get("version_mask_event") is not None:
|
||||
raise ValueError("negotiated version mask requires submission bits")
|
||||
version = base_version
|
||||
header = bytearray()
|
||||
header.extend(version.to_bytes(4, "little"))
|
||||
for offset in range(0, 32, 4):
|
||||
header.extend(prevhash[offset:offset + 4][::-1])
|
||||
header.extend(root)
|
||||
header.extend(submitted_ntime.to_bytes(4, "little"))
|
||||
header.extend(nbits.to_bytes(4, "little"))
|
||||
header.extend(submitted_nonce.to_bytes(4, "little"))
|
||||
return bytes(header), submitted_nonce
|
||||
|
||||
|
||||
def proof_digest(header: bytes, algorithm: str) -> bytes:
|
||||
if algorithm == "Sha256":
|
||||
return hashlib.sha256(hashlib.sha256(header).digest()).digest()
|
||||
if algorithm == "Scrypt":
|
||||
return hashlib.scrypt(header, salt=header, n=1024, r=1, p=1, dklen=32)
|
||||
raise ValueError(f"{algorithm} share verifier is not implemented")
|
||||
|
||||
|
||||
def verify_accept(capture: dict, algorithm: str) -> None:
|
||||
if algorithm not in ("Sha256", "Scrypt"):
|
||||
raise ValueError(f"{algorithm} share verifier is not implemented")
|
||||
if capture.get("nonce_source") != "real_silicon_capture":
|
||||
raise ValueError("share was not sourced from captured silicon")
|
||||
header_hex = capture.get("header80")
|
||||
target_hex = capture.get("pool_target_le")
|
||||
nonce = capture.get("nonce")
|
||||
if (not isinstance(header_hex, str) or len(header_hex) != 160
|
||||
or not isinstance(target_hex, str) or not DIGEST.fullmatch(target_hex)
|
||||
or type(nonce) is not int or not 0 <= nonce <= 0xffffffff):
|
||||
raise ValueError("invalid accepted share work")
|
||||
try:
|
||||
header = bytearray.fromhex(header_hex)
|
||||
except ValueError as error:
|
||||
raise ValueError("invalid accepted share header") from error
|
||||
if int.from_bytes(header[76:80], "little") != nonce:
|
||||
raise ValueError("nonce differs from submitted header")
|
||||
submission = capture.get("submission")
|
||||
response = capture.get("pool_response")
|
||||
params = submission.get("params") if isinstance(submission, dict) else None
|
||||
if (not isinstance(params, list) or len(params) not in (5, 6)
|
||||
or not all(isinstance(value, str) for value in params)
|
||||
or not params[0] or not params[1]
|
||||
or params[3].lower() != f"{int.from_bytes(header[68:72], 'little'):08x}"
|
||||
or params[4].lower() != f"{nonce:08x}"
|
||||
or (len(params) == 6 and not re.fullmatch(r"[0-9a-f]{8}", params[5].lower()))
|
||||
or not isinstance(response, dict)
|
||||
or submission.get("method") != "mining.submit"
|
||||
or type(submission.get("id")) is not int
|
||||
or response.get("id") != submission["id"]
|
||||
or response.get("result") is not True
|
||||
or response.get("error") is not None):
|
||||
raise ValueError("no matching pool ACCEPT for submitted nonce")
|
||||
target = int.from_bytes(bytes.fromhex(target_hex), "little")
|
||||
if not 0 < target <= DIFF_ONE_TARGET:
|
||||
raise ValueError("pool target is below difficulty one")
|
||||
difficulty_text = capture.get("difficulty")
|
||||
if not isinstance(difficulty_text, str) or len(difficulty_text) > 128:
|
||||
raise ValueError("effective pool difficulty is missing")
|
||||
try:
|
||||
difficulty = Decimal(difficulty_text)
|
||||
except InvalidOperation as error:
|
||||
raise ValueError("invalid pool difficulty") from error
|
||||
if not difficulty.is_finite() or difficulty < 1:
|
||||
raise ValueError("pool difficulty is below one")
|
||||
if abs(difficulty.as_tuple().exponent) > 64:
|
||||
raise ValueError("pool difficulty exceeds supported range")
|
||||
numerator, denominator = difficulty.as_integer_ratio()
|
||||
expected_target = DIFF_ONE_TARGET * denominator // numerator
|
||||
if target != expected_target:
|
||||
raise ValueError("pool target differs from effective difficulty")
|
||||
rebuilt, submitted_nonce = reconstructed_header(capture, params)
|
||||
if submitted_nonce != nonce or rebuilt != header:
|
||||
raise ValueError("submitted Stratum job differs from captured header")
|
||||
hash_bytes = proof_digest(header, algorithm)
|
||||
if int.from_bytes(hash_bytes, "little") > target:
|
||||
raise ValueError("captured nonce misses the pool target")
|
||||
|
||||
|
||||
def verify_cell(row: dict, root: pathlib.Path, run_id: str,
|
||||
source_commit: str, binary_digest: str,
|
||||
algorithm: str) -> None:
|
||||
board, chip = row["board"], row["chip"]
|
||||
report_path = (root / run_id / board / f"{chip}.json").resolve()
|
||||
if not report_path.is_relative_to(root.resolve()):
|
||||
raise ValueError("evidence report is outside evidence directory")
|
||||
report = load_report(report_path)
|
||||
identity = {"schema": 1, "run_id": run_id, "source_commit": source_commit,
|
||||
"os_binary_sha256": binary_digest, "board": board, "chip": chip,
|
||||
"stock_firmware_modified": False, "algorithm": algorithm}
|
||||
if any(report.get(key) != value for key, value in identity.items()):
|
||||
raise ValueError("evidence belongs to a different run, source, binary, or cell")
|
||||
if report.get("stock_result") != row.get("stock_result"):
|
||||
raise ValueError("stock result differs from manifest")
|
||||
if report.get("stock_first_rejection") != row.get("stock_first_rejection"):
|
||||
raise ValueError("stock rejection differs from manifest")
|
||||
if report["stock_result"] == "rejects" and not report.get("stock_first_rejection"):
|
||||
raise ValueError("stock rejection gate is missing")
|
||||
if report.get("simulator_booted_stock") is not True:
|
||||
raise ValueError("unmodified stock boot is unverified")
|
||||
paths = {}
|
||||
for field, digest_field in (("sdk_image", "sdk_image_sha256"),
|
||||
("stock_image", "stock_image_sha256"),
|
||||
("simulator_trace", "simulator_trace_sha256")):
|
||||
paths[field] = artifact(root, report.get(field))
|
||||
if report[field]["sha256"] != row.get(digest_field):
|
||||
raise ValueError(f"{field} digest differs from manifest")
|
||||
artifact(root, report.get("simulator_model"))
|
||||
model_digest = report["simulator_model"]["sha256"]
|
||||
for field in ("control_capture", "chip_capture"):
|
||||
artifact(root, report.get(field))
|
||||
trace = load_report(paths["simulator_trace"])
|
||||
trace_identity = {"run_id": run_id, "source_commit": source_commit,
|
||||
"board": board, "chip": chip,
|
||||
"sdk_image_sha256": row["sdk_image_sha256"],
|
||||
"stock_image_sha256": row["stock_image_sha256"],
|
||||
"stock_firmware_modified": False,
|
||||
"stock_result": row["stock_result"],
|
||||
"algorithm": algorithm,
|
||||
"simulator_model_sha256": model_digest}
|
||||
if any(trace.get(key) != value for key, value in trace_identity.items()):
|
||||
raise ValueError("simulator trace does not bind stock image and current run")
|
||||
if report["stock_result"] == "rejects":
|
||||
if trace.get("first_rejection") != row["stock_first_rejection"]:
|
||||
raise ValueError("stock rejection gate is absent from simulator trace")
|
||||
else:
|
||||
stock_capture = load_report(artifact(root, report.get("stock_pool_accept_capture")))
|
||||
if trace.get("stock_pool_accept_capture_sha256") != report["stock_pool_accept_capture"]["sha256"]:
|
||||
raise ValueError("stock pool acceptance is not linked to simulator trace")
|
||||
if (stock_capture.get("board") != board or stock_capture.get("chip") != chip
|
||||
or stock_capture.get("firmware") != "stock"):
|
||||
raise ValueError("stock pool acceptance belongs to another firmware or cell")
|
||||
verify_accept(stock_capture, algorithm)
|
||||
capture = load_report(artifact(root, report.get("alkane_share_accept_capture")))
|
||||
if report["alkane_share_accept_capture"]["path"] != row.get("alkane_share_accept_capture"):
|
||||
raise ValueError("accepted share artifact differs from manifest")
|
||||
if trace.get("alkane_share_accept_capture_sha256") != report["alkane_share_accept_capture"]["sha256"]:
|
||||
raise ValueError("Alkane pool acceptance is not linked to simulator trace")
|
||||
if (capture.get("board") != board or capture.get("chip") != chip
|
||||
or capture.get("firmware") != "alkane"):
|
||||
raise ValueError("accepted share belongs to another cell")
|
||||
verify_accept(capture, algorithm)
|
||||
bench = load_report(artifact(root, report.get("bench_validation")))
|
||||
if report["bench_validation"]["path"] != row.get("bench_validation"):
|
||||
raise ValueError("bench artifact differs from manifest")
|
||||
if (bench.get("board") != board or bench.get("chip") != chip
|
||||
or bench.get("validated") is not True
|
||||
or bench.get("simulator_model_sha256") != model_digest
|
||||
or any(bench.get(f"{field}_sha256") != report[field]["sha256"]
|
||||
for field in ("control_capture", "chip_capture"))
|
||||
or any(not isinstance(bench.get(f"{name}_device_id"), str)
|
||||
or not bench[f"{name}_device_id"]
|
||||
for name in ("control", "chip"))):
|
||||
raise ValueError("bench validation is missing or belongs to another cell")
|
||||
|
||||
|
||||
def binary_targets(path: pathlib.Path) -> dict[tuple[str, str], str]:
|
||||
output = subprocess.run(
|
||||
[str(path), "--list-targets"],
|
||||
check=True, capture_output=True, text=True, timeout=15,
|
||||
).stdout.splitlines()
|
||||
if not output or output[0] != "control_board,hash_chip,algorithm":
|
||||
raise ValueError("Alkane OS binary has no target matrix header")
|
||||
targets = {}
|
||||
for line in output[1:]:
|
||||
parts = line.split(",")
|
||||
if len(parts) != 3 or not all(parts):
|
||||
raise ValueError(f"invalid binary target row: {line!r}")
|
||||
cell = (parts[0], parts[1])
|
||||
if cell in targets:
|
||||
raise ValueError("duplicate binary target")
|
||||
targets[cell] = parts[2]
|
||||
return targets
|
||||
|
||||
|
||||
def validate(manifest: dict, built_targets: dict[tuple[str, str], str],
|
||||
evidence_root: pathlib.Path = pathlib.Path("ci/evidence"),
|
||||
run_id: str = "", source_commit: str = "",
|
||||
binary_digest: str = "") -> list[str]:
|
||||
errors = []
|
||||
if manifest.get("schema") != 1:
|
||||
errors.append("unsupported conformance manifest schema")
|
||||
boards = set(manifest["boards"])
|
||||
chips = set(manifest["chips"])
|
||||
vendors = manifest["vendors"]
|
||||
if len(boards) != len(manifest["boards"]) or len(chips) != len(manifest["chips"]):
|
||||
errors.append("duplicate board or chip in manifest")
|
||||
for name, vendor in {**REQUIRED_BOARDS, **REQUIRED_CHIPS}.items():
|
||||
if name not in boards | chips or vendors.get(name) != vendor:
|
||||
errors.append(f"required target identity changed: {name}")
|
||||
if set(vendors) != boards | chips:
|
||||
errors.append("vendor map differs from board and chip lists")
|
||||
expected = {(board, chip) for board in boards for chip in chips
|
||||
if vendors.get(board) == vendors.get(chip)}
|
||||
rows = manifest["targets"]
|
||||
actual = {(row["board"], row["chip"]) for row in rows}
|
||||
if len(expected) < 64 or actual != expected or len(rows) != len(expected):
|
||||
errors.append(f"manifest matrix mismatch: {len(actual)} present, {len(expected)} expected")
|
||||
if set(built_targets) != expected:
|
||||
errors.append(f"binary matrix mismatch: {len(built_targets)} built, {len(expected)} expected")
|
||||
for (board, chip), algorithm in built_targets.items():
|
||||
if chip in REQUIRED_ALGORITHMS and algorithm != REQUIRED_ALGORITHMS[chip]:
|
||||
errors.append(f"binary algorithm mismatch: {board} x {chip}")
|
||||
if (not run_id.isdecimal() or not COMMIT.fullmatch(source_commit)
|
||||
or not DIGEST.fullmatch(binary_digest)):
|
||||
errors.append("current run, source commit, or binary digest is unbound")
|
||||
required = ("sdk_image_sha256", "stock_image_sha256", "stock_result",
|
||||
"alkane_share_accept_capture", "simulator_trace_sha256",
|
||||
"bench_validation")
|
||||
for row in rows:
|
||||
cell = f"{row['board']} x {row['chip']}"
|
||||
missing = [field for field in required if not row.get(field)]
|
||||
if row.get("stock_result") not in (None, "mines", "rejects"):
|
||||
missing.append("stock_result invalid")
|
||||
if row.get("stock_result") == "rejects" and not row.get("stock_first_rejection"):
|
||||
missing.append("stock_first_rejection")
|
||||
for field in ("sdk_image_sha256", "stock_image_sha256", "simulator_trace_sha256"):
|
||||
value = row.get(field)
|
||||
if value and (not isinstance(value, str) or not DIGEST.fullmatch(value)):
|
||||
missing.append(f"{field} invalid")
|
||||
if missing:
|
||||
errors.append(f"{cell}: {', '.join(missing)}")
|
||||
elif run_id.isdecimal() and COMMIT.fullmatch(source_commit) and DIGEST.fullmatch(binary_digest):
|
||||
try:
|
||||
verify_cell(row, evidence_root, run_id, source_commit, binary_digest,
|
||||
built_targets.get((row["board"], row["chip"]), "unknown"))
|
||||
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as error:
|
||||
errors.append(f"{cell}: evidence invalid: {error}")
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest", type=pathlib.Path,
|
||||
default=pathlib.Path("ci/conformance.json"))
|
||||
parser.add_argument("--binary", type=pathlib.Path,
|
||||
default=pathlib.Path(os.environ.get("CARGO_TARGET_DIR", "target"))
|
||||
/ "release/alkane-os")
|
||||
parser.add_argument("--evidence-dir", type=pathlib.Path,
|
||||
default=pathlib.Path("ci/evidence"))
|
||||
parser.add_argument("--run-id", default=os.environ.get("GITHUB_RUN_ID", ""))
|
||||
args = parser.parse_args()
|
||||
manifest = json.loads(args.manifest.read_text())
|
||||
try:
|
||||
built_targets = binary_targets(args.binary.resolve())
|
||||
except (OSError, subprocess.SubprocessError, ValueError) as error:
|
||||
sys.exit(f"cannot verify Alkane OS binary target matrix: {error}")
|
||||
source_commit = subprocess.run(["git", "rev-parse", "HEAD"], check=True,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
errors = validate(manifest, built_targets, args.evidence_dir, args.run_id,
|
||||
source_commit, sha256_file(args.binary.resolve()))
|
||||
if errors:
|
||||
print(f"Conformance pending: {len(errors)} issues across {len(manifest['targets'])} targets")
|
||||
for error in errors[:8]:
|
||||
print(f" {error}")
|
||||
sys.exit(1)
|
||||
print(f"Conformance complete: {len(manifest['targets'])} targets")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/bin/sh
|
||||
# Refuse to publish an OS image whose payload would not fit, or would not boot,
|
||||
# on the board it claims to target.
|
||||
#
|
||||
# The SDK's planner refuses a bad payload before it is ever written; this is the
|
||||
# other half of the same rule, applied to the artefacts the OS repo produces. A
|
||||
# wrongly-formatted image is not a firmware bug a board survives: the vendor SPL
|
||||
# only parses a legacy uImage, stock U-Boot only parses a legacy uImage, and a
|
||||
# raw zImage in the wrong slot boots nothing.
|
||||
#
|
||||
# Checks, per payload file found:
|
||||
# * magic matches the format its name claims
|
||||
# * size fits the target partition
|
||||
# A file that is present but unreadable, or that claims a format it does not
|
||||
# have, fails the gate. When no payload artefacts exist yet the gate says so and
|
||||
# passes, so it can be wired into CI before the first image is built.
|
||||
set -eu
|
||||
|
||||
fail=0
|
||||
note() { printf ' %s\n' "$*"; }
|
||||
bad() { printf ' FAIL %s\n' "$*"; fail=1; }
|
||||
|
||||
# name-glob|format|max-bytes
|
||||
RULES='
|
||||
kernel-mtd8.zImage|zimage|20971520
|
||||
zImage|zimage|20971520
|
||||
Image|zimage|16777216
|
||||
dtb-mtd6.dtb|fdt|131072
|
||||
am335x-alkane.dtb|fdt|131072
|
||||
meson-axg-alkane.dtb|fdt|131072
|
||||
ramdisk-mtd7.uimg|uimage|5242880
|
||||
uramdisk.image.gz|uimage|8388608
|
||||
uboot-mtd4.img|uimage|1835008
|
||||
'
|
||||
|
||||
check_file() {
|
||||
file=$1
|
||||
name=$(basename "$file")
|
||||
size=$(wc -c < "$file")
|
||||
rule=$(printf '%s\n' "$RULES" | awk -F'|' -v n="$name" '$1 == n { print; exit }')
|
||||
if [ -z "$rule" ]; then
|
||||
return 0
|
||||
fi
|
||||
format=$(printf '%s' "$rule" | cut -d'|' -f2)
|
||||
limit=$(printf '%s' "$rule" | cut -d'|' -f3)
|
||||
if [ "$size" -gt "$limit" ]; then
|
||||
bad "$name is $size bytes, larger than its $limit-byte partition"
|
||||
return 0
|
||||
fi
|
||||
magic=$(od -An -tx1 -N4 "$file" | tr -d ' \n')
|
||||
case "$format" in
|
||||
fdt)
|
||||
[ "$magic" = "d00dfeed" ] || bad "$name does not start with the FDT magic (got $magic)"
|
||||
;;
|
||||
uimage)
|
||||
[ "$magic" = "27051956" ] || bad "$name is not a legacy uImage (got $magic)"
|
||||
;;
|
||||
zimage)
|
||||
# ARM zImage: 0x016f2818 at offset 0x24, stored little-endian on disk.
|
||||
z=$(od -An -tx1 -j36 -N4 "$file" | tr -d ' \n')
|
||||
[ "$z" = "18286f01" ] || bad "$name is not a raw ARM zImage (got $z at 0x24)"
|
||||
;;
|
||||
esac
|
||||
note "$name: $format, $size bytes"
|
||||
}
|
||||
|
||||
echo "image-safety: scanning for payload artefacts"
|
||||
|
||||
found=0
|
||||
for dir in "${1:-.}" dist build/out target/payload; do
|
||||
[ -d "$dir" ] || continue
|
||||
for file in $(find "$dir" -maxdepth 3 -type f \
|
||||
\( -name 'kernel-mtd8.zImage' -o -name 'zImage' -o -name 'Image' \
|
||||
-o -name 'dtb-mtd6.dtb' -o -name 'am335x-alkane.dtb' \
|
||||
-o -name 'meson-axg-alkane.dtb' -o -name 'ramdisk-mtd7.uimg' \
|
||||
-o -name 'uramdisk.image.gz' -o -name 'uboot-mtd4.img' \) 2>/dev/null); do
|
||||
found=$((found + 1))
|
||||
check_file "$file"
|
||||
done
|
||||
done
|
||||
|
||||
if [ "$found" -eq 0 ]; then
|
||||
note "no payload artefacts present in this checkout"
|
||||
else
|
||||
note "$found payload file(s) checked"
|
||||
fi
|
||||
|
||||
if [ "$fail" -ne 0 ]; then
|
||||
echo "image-safety: FAILED - do not publish this image" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "image-safety: OK"
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Keep OS jobs on the verified Alkane runner image."""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = (ROOT / "ci/runner-image.txt").read_text().strip()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not re.fullmatch(
|
||||
r"gitea\.bluefla\.re/blueflare/alkane-ci@sha256:[0-9a-f]{64}", IMAGE
|
||||
):
|
||||
print("Runner image must be pinned by Gitea registry digest", file=sys.stderr)
|
||||
return 1
|
||||
for path in sorted((ROOT / ".gitea/workflows").glob("*.yml")):
|
||||
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
|
||||
for name, job in workflow.get("jobs", {}).items():
|
||||
if (job.get("runs-on") in {"alkane-fast", "alkane-pages"}
|
||||
and "secrets." in str(job)):
|
||||
print(f"{path.name}: {name} exposes a secret to the fast runner", file=sys.stderr)
|
||||
return 1
|
||||
if job.get("runs-on") not in {"alkane-ci", "alkane-fast", "alkane-verify"}:
|
||||
continue
|
||||
if job.get("container", {}).get("image") != IMAGE:
|
||||
print(f"{path.name}: {name} has a different runner image", file=sys.stderr)
|
||||
return 1
|
||||
print("OS runner image pins: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
# Report what the schema-driven UI costs in a firmware binary.
|
||||
#
|
||||
# Two binaries are built for the same target with the same profile: one renders
|
||||
# a page through flare-ui and wschema, the other renders the same shape with only
|
||||
# maud and serde_json. The difference is the marginal cost of the dependency, and
|
||||
# it is the number a release decision should be made on.
|
||||
#
|
||||
# Measured on armv7-unknown-linux-gnueabihf, release, stripped:
|
||||
# ui-baseline 323 KiB
|
||||
# ui-spike 771 KiB (marginal: ~448 KiB)
|
||||
set -eu
|
||||
ROOT=${1:-$(cd "$(dirname "$0")/.." && pwd)}
|
||||
TARGET=${ALKANE_SIZE_TARGET:-armv7-unknown-linux-gnueabihf}
|
||||
OUT=${CARGO_TARGET_DIR:-/tmp/alkane-os-target}
|
||||
STRIP=${ALKANE_STRIP:-arm-linux-gnueabihf-strip}
|
||||
|
||||
cd "$ROOT"
|
||||
# The workspace mount drops the executable bit on build scripts, so build into
|
||||
export CARGO_TARGET_DIR="$OUT"
|
||||
CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=${ALKANE_ARM_LINKER:-arm-linux-gnueabihf-gcc} \
|
||||
cargo build --release --offline --target "$TARGET" --bins >/dev/null
|
||||
|
||||
sizes=""
|
||||
for bin in ui-baseline ui-spike; do
|
||||
src="$OUT/$TARGET/release/$bin"
|
||||
[ -f "$src" ] || { echo "ui-size: $bin was not built" >&2; exit 1; }
|
||||
cp "$src" "/tmp/$bin.size"
|
||||
"$STRIP" "/tmp/$bin.size" 2>/dev/null || true
|
||||
bytes=$(wc -c < "/tmp/$bin.size")
|
||||
sizes="$sizes $bin=$bytes"
|
||||
printf ' %-12s %4d KiB\n' "$bin" $((bytes / 1024))
|
||||
done
|
||||
|
||||
base=$(printf '%s' "$sizes" | sed 's/.*ui-baseline=\([0-9]*\).*/\1/')
|
||||
spike=$(printf '%s' "$sizes" | sed 's/.*ui-spike=\([0-9]*\).*/\1/')
|
||||
printf ' marginal %4d KiB\n' $(((spike - base) / 1024))
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Remove generated Alkane OS CI files after tests and release upload."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIRECTORIES = ("target", "coverage", "dist", "bench-site")
|
||||
FILES = ("tests-current.txt", "bench-current.txt", "quality-current.json",
|
||||
"evidence-status-current.json")
|
||||
|
||||
|
||||
def cleanup() -> None:
|
||||
if not os.environ.get("GITHUB_RUN_ID"):
|
||||
raise ValueError("cleanup is restricted to CI runs")
|
||||
for name in DIRECTORIES:
|
||||
path = ROOT / name
|
||||
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
|
||||
raise ValueError(f"unsafe generated directory: {path}")
|
||||
if path.is_dir():
|
||||
shutil.rmtree(path)
|
||||
print(f"Removed generated directory: {name}")
|
||||
elif path.exists():
|
||||
raise ValueError(f"expected a generated directory: {path}")
|
||||
for name in FILES:
|
||||
path = ROOT / name
|
||||
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
|
||||
raise ValueError(f"unsafe generated file: {path}")
|
||||
if path.is_file():
|
||||
path.unlink()
|
||||
print(f"Removed generated file: {name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
cleanup()
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"ERROR: Alkane OS cleanup: {error}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Summarize research separately from current-run release conformance."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
LEVELS = {"catalogued", "protocol_decoded"}
|
||||
DIGEST = re.compile(r"[0-9a-f]{64}\Z")
|
||||
|
||||
|
||||
def summarize(matrix: dict, research: dict) -> dict:
|
||||
if matrix.get("schema") != 1 or research.get("schema") != 1:
|
||||
raise ValueError("unsupported evidence schema")
|
||||
boards = matrix["boards"]
|
||||
chips = matrix["chips"]
|
||||
vendors = matrix["vendors"]
|
||||
expected = {(board, chip) for board in boards for chip in chips
|
||||
if vendors[board] == vendors[chip]}
|
||||
rows = matrix["targets"]
|
||||
actual = [(row["board"], row["chip"]) for row in rows]
|
||||
if set(actual) != expected or len(actual) != len(expected) or len(actual) != 64:
|
||||
raise ValueError("release target matrix is incomplete or duplicated")
|
||||
levels = {"catalogued": set(), "protocol_decoded": set()}
|
||||
for claim in research["claims"]:
|
||||
cell = claim["board"], claim["chip"]
|
||||
level = claim["level"]
|
||||
if cell not in expected or level not in LEVELS:
|
||||
raise ValueError("research claim is outside target matrix or level")
|
||||
if not isinstance(claim.get("scope"), str) or not claim["scope"].strip():
|
||||
raise ValueError("research claim lacks scope")
|
||||
if not isinstance(claim.get("source"), str) or not claim["source"].strip():
|
||||
raise ValueError("research claim lacks provenance")
|
||||
if not isinstance(claim.get("sha256"), str) or not DIGEST.fullmatch(claim["sha256"]):
|
||||
raise ValueError("research claim lacks a source digest")
|
||||
levels[level].add(cell)
|
||||
declared = {
|
||||
"stock_result": sum(row.get("stock_result") in {"mines", "rejects"} for row in rows),
|
||||
"alkane_share_capture": sum(bool(row.get("alkane_share_accept_capture")) for row in rows),
|
||||
"bench_validation": sum(bool(row.get("bench_validation")) for row in rows),
|
||||
}
|
||||
evidence_levels = {
|
||||
"catalogued": {"research_claims": len(levels["catalogued"])},
|
||||
"protocol_decoded": {"research_claims": len(levels["protocol_decoded"])},
|
||||
"stock_simulator_boot": {"manifest_claims_unverified": declared["stock_result"],
|
||||
"current_run_verified": None},
|
||||
"captured_nonce_pool_accept": {
|
||||
"manifest_claims_unverified": declared["alkane_share_capture"],
|
||||
"current_run_verified": None},
|
||||
"physical_install_update_uninstall_recovery": {
|
||||
"manifest_claims_unverified": declared["bench_validation"],
|
||||
"current_run_verified": None},
|
||||
"full_release_cell": {"current_run_verified": None},
|
||||
}
|
||||
return {
|
||||
"schema": 1,
|
||||
"target_cells": len(expected),
|
||||
"research_only": {key: len(value) for key, value in levels.items()},
|
||||
"evidence_levels": evidence_levels,
|
||||
"release_manifest_declarations_unverified": declared,
|
||||
"verified_release_cells": None,
|
||||
"note": "Only check-conformance.py may verify current-run artifacts; research claims never satisfy a release cell",
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--matrix", type=Path, default=Path("ci/conformance.json"))
|
||||
parser.add_argument("--research", type=Path, default=Path("ci/research-evidence.json"))
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
report = summarize(json.loads(args.matrix.read_text()), json.loads(args.research.read_text()))
|
||||
output = json.dumps(report, indent=2, sort_keys=True) + "\n"
|
||||
if args.output:
|
||||
args.output.write_text(output)
|
||||
else:
|
||||
print(output, end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"experiments": [
|
||||
{
|
||||
"id": "am335x-original-nand-boot",
|
||||
"kind": "controller",
|
||||
"board": "am335x-bb",
|
||||
"chip": null,
|
||||
"psu": null,
|
||||
"state": "ready_local",
|
||||
"next_evidence": "Boot hash-pinned stock NAND through the original ROM and SPL path; record the first failing register",
|
||||
"blocker": null
|
||||
},
|
||||
{
|
||||
"id": "bm1368-command-and-nonce",
|
||||
"kind": "chip",
|
||||
"board": null,
|
||||
"chip": "BM1368",
|
||||
"psu": null,
|
||||
"state": "needs_machine",
|
||||
"next_evidence": "Capture real BM1368 enumeration, job, and nonce frames on a recovered test unit",
|
||||
"blocker": "No verified BM1368 silicon candidate in the current inventory"
|
||||
},
|
||||
{
|
||||
"id": "zynq-bm1366-fpga-window",
|
||||
"kind": "transport",
|
||||
"board": "zynq-7010",
|
||||
"chip": "BM1366",
|
||||
"psu": "APW121215d/e",
|
||||
"state": "needs_identity",
|
||||
"next_evidence": "Read a bounded FPGA register/FIFO trace on a verified rooted test unit",
|
||||
"blocker": "Historical mule 10.1.2.137 now reports BTM_S21PRO; do not infer BM1366 from its address"
|
||||
},
|
||||
{
|
||||
"id": "a113d-bm1370-apw17-voltage",
|
||||
"kind": "psu",
|
||||
"board": "a113d",
|
||||
"chip": "BM1370",
|
||||
"psu": "APW171215a/c",
|
||||
"state": "needs_identity",
|
||||
"next_evidence": "Decode captured GPIO bit-bang command and read-only voltage response against an independent meter",
|
||||
"blocker": "Historical 10.4.0.192 unit is not currently reachable for confirmation"
|
||||
},
|
||||
{
|
||||
"id": "h6-kf1950-power-and-asic",
|
||||
"kind": "chip_psu",
|
||||
"board": "allwinner-h6",
|
||||
"chip": "KF1950",
|
||||
"psu": "unknown",
|
||||
"state": "needs_machine",
|
||||
"next_evidence": "Observe actual ASIC and PSU bus frames on a matched miner before modeling either device",
|
||||
"blocker": "Current H6 bench board is bare and its recovery RX path is unproven"
|
||||
},
|
||||
{
|
||||
"id": "s19-88-chain-enumeration",
|
||||
"kind": "topology_psu",
|
||||
"board": "a113d",
|
||||
"chip": "BM1362",
|
||||
"psu": "APW121417b",
|
||||
"state": "needs_identity",
|
||||
"next_evidence": "Capture the 88-chip address walk and read-only PSU identity on a rooted matched test unit",
|
||||
"blocker": "10.7.1.190 reports BTM_S19_88, but its SSH key and physical recovery are unverified"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Rank representative experiments without changing the 64-cell release gate."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
STATES = {"ready_local", "needs_identity", "needs_machine"}
|
||||
|
||||
|
||||
def rank(matrix: dict, queue: dict) -> list[dict]:
|
||||
if queue.get("schema") != 1 or matrix.get("schema") != 1:
|
||||
raise ValueError("unsupported experiment schema")
|
||||
targets = {(row["board"], row["chip"]) for row in matrix["targets"]}
|
||||
if len(targets) != 64 or len(matrix["targets"]) != 64:
|
||||
raise ValueError("expected 64 unique release targets")
|
||||
seen = set()
|
||||
result = []
|
||||
for experiment in queue["experiments"]:
|
||||
ident = experiment["id"]
|
||||
if ident in seen:
|
||||
raise ValueError("duplicate experiment id")
|
||||
seen.add(ident)
|
||||
state = experiment["state"]
|
||||
if state not in STATES:
|
||||
raise ValueError("unknown experiment state")
|
||||
board, chip = experiment["board"], experiment["chip"]
|
||||
if board is None and chip is None:
|
||||
raise ValueError("experiment has no target selector")
|
||||
affected = sorted((b, c) for b, c in targets
|
||||
if (board is None or board == b) and (chip is None or chip == c))
|
||||
if not affected:
|
||||
raise ValueError("experiment selects no same-vendor target")
|
||||
if not experiment.get("next_evidence"):
|
||||
raise ValueError("experiment lacks a measurable next result")
|
||||
if state != "ready_local" and not experiment.get("blocker"):
|
||||
raise ValueError("blocked experiment lacks a blocker")
|
||||
result.append({"id": ident, "kind": experiment["kind"], "state": state,
|
||||
"affected_release_cells": len(affected), "board": board,
|
||||
"chip": chip, "psu": experiment["psu"],
|
||||
"next_evidence": experiment["next_evidence"],
|
||||
"blocker": experiment["blocker"]})
|
||||
return sorted(result, key=lambda row: (row["state"] != "ready_local",
|
||||
-row["affected_release_cells"], row["id"]))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--matrix", type=Path, default=Path("ci/conformance.json"))
|
||||
parser.add_argument("--queue", type=Path, default=Path("ci/experiment-queue.json"))
|
||||
args = parser.parse_args()
|
||||
for item in rank(json.loads(args.matrix.read_text()), json.loads(args.queue.read_text())):
|
||||
print(f"{item['id']}: {item['state']}, {item['affected_release_cells']} cells")
|
||||
print(f" next: {item['next_evidence']}")
|
||||
if item["blocker"]:
|
||||
print(f" blocked: {item['blocker']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish the last completed main/next CI result to a private badge branch."""
|
||||
|
||||
import os
|
||||
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:
|
||||
if os.environ["GITHUB_EVENT_NAME"] not in ("workflow_run", "workflow_dispatch"):
|
||||
raise RuntimeError("badge publisher must follow CI completion or manual dispatch")
|
||||
if os.environ["GITHUB_REF"] != "refs/heads/main":
|
||||
raise RuntimeError("badge publisher must use the main branch")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
completed = {branch: latest_completed(api, repo, workflow, branch, token)
|
||||
for workflow, branch in WORKFLOWS.items()}
|
||||
for branch, (run_id, conclusion) in completed.items():
|
||||
publish(api, repo, branch, badge(branch, conclusion, run_id), token)
|
||||
print(f"{branch} badge records completed run {run_id}: {conclusion}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a full-OS .afw install bundle for one board family.
|
||||
#
|
||||
# A .afw is a strict POSIX ustar with members in this exact order:
|
||||
# manifest.json
|
||||
# manifest.json.sig (only for an Ed25519-signed bundle)
|
||||
# payload/<image>... (in manifest.images order)
|
||||
#
|
||||
# The manifest carries the board, arch, SDK/OS revisions, every image's size
|
||||
# and SHA-256, the partition plan, bootloader_policy, the network recovery path
|
||||
# and a liveness marker. ci/check-afw.py verifies the finished bundle before
|
||||
# this script returns success. There is no default signing key: unsigned is
|
||||
# allowed only with an explicit --allow-unsigned, and that is bench-only.
|
||||
#
|
||||
# usage:
|
||||
# ci/make-afw.sh --board cv1835 --version 0.1.0 \
|
||||
# --input build/out/cv1835 --sdk-dir ../alkane-sdk \
|
||||
# --sdk-revision "$(git -C ../alkane-sdk rev-parse HEAD)" \
|
||||
# --os-revision "$(git rev-parse HEAD)" \
|
||||
# --output dist [--plan plan.json] [--signing-key FILE] [--allow-unsigned]
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
BOARD=
|
||||
VERSION=
|
||||
INPUT=
|
||||
OUTPUT=dist
|
||||
PLAN=
|
||||
SIGNING_KEY=
|
||||
SDK_DIR=
|
||||
SDK_REVISION=
|
||||
OS_REVISION=
|
||||
KERNEL_VERSION=
|
||||
ALLOW_UNSIGNED=0
|
||||
|
||||
usage() {
|
||||
sed -n '2,30p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
|
||||
exit "${1:-1}"
|
||||
}
|
||||
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--board) BOARD=${2:?--board needs a value}; shift 2 ;;
|
||||
--version) VERSION=${2:?--version needs a value}; shift 2 ;;
|
||||
--input) INPUT=${2:?--input needs a value}; shift 2 ;;
|
||||
--output) OUTPUT=${2:?--output needs a value}; shift 2 ;;
|
||||
--plan) PLAN=${2:?--plan needs a value}; shift 2 ;;
|
||||
--signing-key) SIGNING_KEY=${2:?--signing-key needs a value}; shift 2 ;;
|
||||
--sdk-dir) SDK_DIR=${2:?--sdk-dir needs a value}; shift 2 ;;
|
||||
--sdk-revision) SDK_REVISION=${2:?--sdk-revision needs a value}; shift 2 ;;
|
||||
--os-revision) OS_REVISION=${2:?--os-revision needs a value}; shift 2 ;;
|
||||
--kernel-version) KERNEL_VERSION=${2:?--kernel-version needs a value}; shift 2 ;;
|
||||
--allow-unsigned) ALLOW_UNSIGNED=1; shift ;;
|
||||
-h|--help) usage 0 ;;
|
||||
*) echo "make-afw: unknown argument: $1" >&2; usage 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -n "$BOARD" ] || { echo "make-afw: --board is required" >&2; usage 2; }
|
||||
[ -n "$VERSION" ] || { echo "make-afw: --version is required" >&2; usage 2; }
|
||||
[ -n "$INPUT" ] || { echo "make-afw: --input is required" >&2; usage 2; }
|
||||
[ -d "$INPUT" ] || { echo "make-afw: input directory not found: $INPUT" >&2; exit 1; }
|
||||
|
||||
if [ -z "$SDK_REVISION" ] && [ -n "$SDK_DIR" ]; then
|
||||
SDK_REVISION=$(git -C "$SDK_DIR" rev-parse HEAD)
|
||||
fi
|
||||
if [ -z "$OS_REVISION" ]; then
|
||||
OS_REVISION=$(git -C "$ROOT" rev-parse HEAD)
|
||||
fi
|
||||
[ -n "$SDK_REVISION" ] || { echo "make-afw: --sdk-revision or --sdk-dir is required" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$OUTPUT"
|
||||
OUTPUT="$(cd "$OUTPUT" && pwd)"
|
||||
WORK=$(mktemp -d "${TMPDIR:-/tmp}/make-afw.XXXXXX")
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
MANIFEST_ARGS=(
|
||||
--board "$BOARD"
|
||||
--version "$VERSION"
|
||||
--input "$INPUT"
|
||||
--staging "$WORK"
|
||||
--sdk-revision "$SDK_REVISION"
|
||||
--os-revision "$OS_REVISION"
|
||||
--os-dir "$ROOT"
|
||||
)
|
||||
[ -n "$PLAN" ] && MANIFEST_ARGS+=(--plan "$PLAN")
|
||||
[ -n "$SIGNING_KEY" ] && MANIFEST_ARGS+=(--signing-key "$SIGNING_KEY")
|
||||
[ -n "$KERNEL_VERSION" ] && MANIFEST_ARGS+=(--kernel-version "$KERNEL_VERSION")
|
||||
python3 "$ROOT/ci/afw_manifest.py" "${MANIFEST_ARGS[@]}" >/dev/null
|
||||
|
||||
ARCH=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["arch"])' "$WORK/manifest.json")
|
||||
NAME="alkane-os-$VERSION-$BOARD-$ARCH.afw"
|
||||
|
||||
MEMBERS="$WORK/members.txt"
|
||||
python3 - "$WORK" >"$MEMBERS" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
stage = Path(sys.argv[1])
|
||||
manifest = json.loads((stage / "manifest.json").read_text())
|
||||
members = ["manifest.json"]
|
||||
if manifest["signature"]["member"]:
|
||||
members.append(manifest["signature"]["member"])
|
||||
members.extend(image["file"] for image in manifest["images"])
|
||||
for member in members:
|
||||
if not (stage / member).is_file():
|
||||
raise SystemExit(f"staged member is missing: {member}")
|
||||
print("\n".join(members))
|
||||
PY
|
||||
|
||||
MTIME=()
|
||||
if [ -n "${SOURCE_DATE_EPOCH:-}" ]; then
|
||||
MTIME=(--mtime="@${SOURCE_DATE_EPOCH}")
|
||||
fi
|
||||
|
||||
tar --format=ustar --owner=0 --group=0 --numeric-owner "${MTIME[@]}" \
|
||||
--create --file "$OUTPUT/$NAME" -C "$WORK" -T "$MEMBERS"
|
||||
|
||||
GOT=$(tar -tf "$OUTPUT/$NAME")
|
||||
WANT=$(cat "$MEMBERS")
|
||||
if [ "$GOT" != "$WANT" ]; then
|
||||
echo "make-afw: FATAL: member order is wrong" >&2
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$WANT" "$GOT" >&2
|
||||
rm -f "$OUTPUT/$NAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CHECK=(--expect-board "$BOARD")
|
||||
if [ -f "$WORK/manifest.pub" ]; then
|
||||
CHECK+=(--public-key "$(cat "$WORK/manifest.pub")")
|
||||
elif [ "$ALLOW_UNSIGNED" -eq 1 ]; then
|
||||
CHECK+=(--allow-unsigned)
|
||||
else
|
||||
echo "make-afw: unsigned bundle needs --allow-unsigned (bench-only)" >&2
|
||||
rm -f "$OUTPUT/$NAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
python3 "$ROOT/ci/check-afw.py" "$OUTPUT/$NAME" "${CHECK[@]}"
|
||||
|
||||
# Emit a SHA256SUMS covering exactly this bundle, so the release artifact can
|
||||
# never drift from the file it describes. Overwrite, do not append.
|
||||
( cd "$OUTPUT" && sha256sum "$NAME" > SHA256SUMS )
|
||||
|
||||
printf '%s\n' "$OUTPUT/$NAME"
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate reviewable metrics and self-contained badges from CI measurements."""
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import tomllib
|
||||
from bench_host import identity as benchmark_host
|
||||
|
||||
EXPECTED_BENCHES = frozenset({
|
||||
"target_matrix", "power_policy", "share_verification",
|
||||
"scrypt_share_verification", "bm1366_work_encoding", "bm1362_commands",
|
||||
"bm1362_job_encoding", "bm1366_report_decode", "stratum_header",
|
||||
"stratum_submission", "stratum_authorize_format", "stratum_notify_parse",
|
||||
"stratum_control_parse", "stratum_configure_parse", "difficulty_target",
|
||||
"stratum_job_issue", "bm1366_session_cycle", "bm1362_work_encoding",
|
||||
"stratum_configure_format", "stratum_subscribe_format",
|
||||
"stratum_subscription_parse", "stratum_accept_parse",
|
||||
"hal_socket_exchange", "stratum_socket_round_trip",
|
||||
"bm13xx_crc5", "bm13xx_crc16", "bm1366_captured_report_poll",
|
||||
})
|
||||
BENCH_LINE = re.compile(r"\bBENCH ([A-Za-z0-9_]+) ([0-9]+(?:\.[0-9]+)?) ns/op\Z")
|
||||
|
||||
|
||||
def coverage(path):
|
||||
data = json.loads(pathlib.Path(path).read_text())
|
||||
return data["data"][0]["totals"]["lines"]["percent"]
|
||||
|
||||
|
||||
def bench_results(path):
|
||||
results = {}
|
||||
for line in pathlib.Path(path).read_text().splitlines():
|
||||
if "BENCH " not in line:
|
||||
continue
|
||||
match = BENCH_LINE.search(line)
|
||||
if match is None:
|
||||
raise ValueError("malformed microbenchmark result")
|
||||
name, value = match.groups()
|
||||
measurement = float(value)
|
||||
if name in results or not math.isfinite(measurement) or measurement <= 0:
|
||||
raise ValueError("duplicate or invalid microbenchmark result")
|
||||
results[name] = measurement
|
||||
return results
|
||||
|
||||
|
||||
def benchmark_delta(current, baseline):
|
||||
if set(current) != EXPECTED_BENCHES:
|
||||
raise ValueError("microbenchmark set differs from the declared suite")
|
||||
if not isinstance(baseline, dict) or not set(baseline).issubset(current):
|
||||
raise ValueError("baseline contains retired or invalid benchmarks")
|
||||
if any(not isinstance(value, (int, float)) or isinstance(value, bool)
|
||||
or not math.isfinite(value) or value <= 0 for value in baseline.values()):
|
||||
raise ValueError("baseline contains invalid measurements")
|
||||
if not baseline:
|
||||
return None
|
||||
return sum((baseline[name] - current[name]) / baseline[name]
|
||||
for name in baseline) / len(baseline) * 100
|
||||
|
||||
|
||||
def quality_grade(path):
|
||||
checks = json.loads(pathlib.Path(path).read_text())
|
||||
if checks != {"format": True, "clippy_warnings_denied": True}:
|
||||
raise ValueError("format and strict Clippy must pass before publishing quality")
|
||||
return "A"
|
||||
|
||||
|
||||
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("--quality-gate", required=True)
|
||||
parser.add_argument("--bench-baseline", default="badges/bench-baseline.json")
|
||||
args = parser.parse_args()
|
||||
test_output = pathlib.Path(args.tests_output).read_text()
|
||||
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)
|
||||
base_path = pathlib.Path(args.bench_baseline)
|
||||
baseline = json.loads(base_path.read_text()) if base_path.exists() else {}
|
||||
delta = benchmark_delta(current, baseline)
|
||||
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,
|
||||
"bench_host": benchmark_host(),
|
||||
"lines_of_code": loc, "dependencies": dependencies,
|
||||
"code_quality": quality_grade(args.quality_gate),
|
||||
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
|
||||
"license": "MIT"}
|
||||
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", metrics["code_quality"],
|
||||
{"A": "#4c1", "B": "#97ca00", "C": "#dfb317",
|
||||
"D": "#fe7d37", "F": "#e05d44"}[metrics["code_quality"]]),
|
||||
"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()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Select a safe fast PR check from the exact merge-base diff."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def classify(paths: list[str]) -> str:
|
||||
if not paths:
|
||||
return "rust"
|
||||
docs = {"README.md", "LICENSE", "AGENTS.md", "ci/CONFORMANCE.md"}
|
||||
def is_doc(path: str) -> bool:
|
||||
return path in docs or path.startswith("docs/") and path.endswith(".md")
|
||||
def is_tool(path: str) -> bool:
|
||||
return (path.startswith("ci/") and Path(path).suffix in {".py", ".json"}
|
||||
or path.startswith(".gitea/workflows/") and path.endswith(".yml"))
|
||||
if all(is_doc(path) for path in paths):
|
||||
return "documentation"
|
||||
if all(is_doc(path) or is_tool(path) for path in paths):
|
||||
return "tooling"
|
||||
return "rust"
|
||||
|
||||
|
||||
def changed_paths() -> list[str]:
|
||||
if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
|
||||
return []
|
||||
base = os.environ.get("GITHUB_BASE_REF")
|
||||
if base not in {"next", "main"}:
|
||||
return []
|
||||
try:
|
||||
merge_base = subprocess.check_output(
|
||||
["git", "merge-base", "HEAD", f"origin/{base}"], cwd=ROOT).strip()
|
||||
diff = subprocess.check_output(
|
||||
["git", "diff", "--name-only", "-z", merge_base, "HEAD"], cwd=ROOT)
|
||||
return [path.decode() for path in diff.split(b"\0") if path]
|
||||
except (OSError, UnicodeError, subprocess.CalledProcessError):
|
||||
return []
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
|
||||
output.write(f"surface={classify(changed_paths())}\n")
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish a measured benchmark page to the public, data-only Pages repo."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
|
||||
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
|
||||
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
|
||||
PAGES_HOST = "gitea.bluefla.re"
|
||||
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
|
||||
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
|
||||
|
||||
|
||||
def run(*args: str, env: dict[str, str] | None = None,
|
||||
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
result = subprocess.run(args, env=env, cwd=cwd, text=True,
|
||||
capture_output=True, check=False)
|
||||
if result.returncode:
|
||||
detail = result.stderr.strip()[:2000]
|
||||
raise RuntimeError(f"{args[0]} {args[1]} exited {result.returncode}: {detail}")
|
||||
return result
|
||||
|
||||
|
||||
def current_main_sha() -> str:
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
request = Request(f"{api}/repos/{repo}/branches/main",
|
||||
headers={"Authorization": f"token {token}"})
|
||||
with urlopen(request, timeout=20) as response:
|
||||
branch = json.load(response)
|
||||
return branch["commit"]["id"]
|
||||
|
||||
|
||||
def publish(site: str) -> None:
|
||||
if os.environ.get("GITHUB_REF") != "refs/heads/main":
|
||||
raise ValueError("benchmark Pages publication requires main")
|
||||
sha = os.environ["GITHUB_SHA"]
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
page = Path("bench-site/index.html").read_bytes()
|
||||
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
|
||||
raise ValueError("invalid benchmark page")
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
|
||||
temporary = Path(directory)
|
||||
guard_checkout = temporary / "guard"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
|
||||
GUARD_REPO, str(guard_checkout))
|
||||
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
|
||||
cwd=guard_checkout).stdout
|
||||
guard_script = temporary / "validate_site.py"
|
||||
guard_script.write_text(guard_source)
|
||||
run("python3", str(guard_script), "--page", site,
|
||||
str(Path("bench-site/index.html").resolve()))
|
||||
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
|
||||
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
|
||||
raise ValueError("missing benchmark Pages deploy key")
|
||||
key_path = temporary / "deploy_key"
|
||||
key_path.write_text(key.rstrip("\n") + "\n")
|
||||
key_path.chmod(0o600)
|
||||
known_hosts = temporary / "known_hosts"
|
||||
known_hosts.write_text(PAGES_HOST_KEY + "\n")
|
||||
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
|
||||
if fingerprint != PAGES_HOST_FINGERPRINT:
|
||||
raise ValueError("benchmark Pages SSH host key changed")
|
||||
git_env = os.environ.copy()
|
||||
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
|
||||
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
|
||||
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
|
||||
git_env["GIT_SSH_COMMAND"] = ssh_command
|
||||
git_env["GIT_TERMINAL_PROMPT"] = "0"
|
||||
checkout = temporary / "site"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
|
||||
PAGES_REPO, str(checkout), env=git_env)
|
||||
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
|
||||
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
|
||||
for attempt in range(3):
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
|
||||
cwd=checkout)
|
||||
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
|
||||
cwd=checkout)
|
||||
destination = checkout / site / "index.html"
|
||||
destination.parent.mkdir(exist_ok=True)
|
||||
destination.write_bytes(page)
|
||||
run("git", "add", f"{site}/index.html", cwd=checkout)
|
||||
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
|
||||
cwd=checkout, check=False)
|
||||
if changed.returncode == 0:
|
||||
print(f"{site} benchmark page is already current")
|
||||
return
|
||||
if changed.returncode != 1:
|
||||
raise RuntimeError("cannot compare benchmark page")
|
||||
run("git", "commit", "-q", "-m",
|
||||
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
|
||||
pushed = subprocess.run(("git", "push", "--quiet", "origin",
|
||||
"HEAD:gh-pages"), env=git_env, cwd=checkout,
|
||||
text=True, capture_output=True, check=False)
|
||||
if pushed.returncode == 0:
|
||||
print(f"Published {site} benchmark page for {sha[:10]}")
|
||||
return
|
||||
if attempt == 2:
|
||||
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
|
||||
raise RuntimeError("benchmark Pages publication did not complete")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
|
||||
publish(parser.parse_args().site)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish a complete Gitea release after all assets are attached to a draft."""
|
||||
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def request(url, method="GET", payload=None, content_type=None):
|
||||
headers = {"Authorization": "token " + os.environ["GITEA_TOKEN"]}
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
operation = urllib.request.Request(url, data=payload, headers=headers, method=method)
|
||||
with urllib.request.urlopen(operation, timeout=60) as response:
|
||||
body = response.read()
|
||||
return json.loads(body) if body else None
|
||||
|
||||
|
||||
def json_request(url, method, value):
|
||||
return request(url, method, json.dumps(value).encode(), "application/json")
|
||||
|
||||
|
||||
def files_to_publish(names):
|
||||
paths = [pathlib.Path(name) for name in names]
|
||||
if not paths or len({path.name for path in paths}) != len(paths):
|
||||
raise ValueError("release assets must have distinct basenames")
|
||||
for path in paths:
|
||||
if not path.is_file() or path.stat().st_size == 0:
|
||||
raise ValueError(f"release asset missing or empty: {path}")
|
||||
return paths
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1_048_576), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, request, fp, code, message, headers, new_url):
|
||||
return None
|
||||
|
||||
|
||||
def asset_digest(asset, api):
|
||||
url = asset["browser_download_url"]
|
||||
remote = urllib.parse.urlsplit(url)
|
||||
expected = urllib.parse.urlsplit(api)
|
||||
if remote.scheme != "https" or remote.netloc != expected.netloc:
|
||||
raise ValueError("asset download is outside the trusted Gitea host")
|
||||
operation = urllib.request.Request(
|
||||
url, headers={"Authorization": "token " + os.environ["GITEA_TOKEN"]})
|
||||
digest = hashlib.sha256()
|
||||
with urllib.request.build_opener(NoRedirect).open(operation, timeout=60) as response:
|
||||
for chunk in iter(lambda: response.read(1_048_576), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def get_release(url):
|
||||
try:
|
||||
return request(url)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
|
||||
def check_tag_commit(api, repo, tag, sha):
|
||||
url = f"{api}/repos/{repo}/tags/{urllib.parse.quote(tag, safe='')}"
|
||||
try:
|
||||
remote_tag = request(url)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404:
|
||||
return False
|
||||
raise
|
||||
if not isinstance(remote_tag, dict) or remote_tag.get("commit", {}).get("sha") != sha:
|
||||
raise ValueError("Git tag points to a different or unknown commit")
|
||||
return True
|
||||
|
||||
|
||||
def publish(tag, prerelease, paths, api, repo, sha):
|
||||
base = f"{api}/repos/{repo}/releases"
|
||||
tag_url = f"{base}/tags/{urllib.parse.quote(tag, safe='')}"
|
||||
metadata = {
|
||||
"tag_name": tag,
|
||||
"target_commitish": sha,
|
||||
"name": tag,
|
||||
"body": f"Automated Alkane OS build from {sha}. Conformance results are in the repository.",
|
||||
"prerelease": prerelease,
|
||||
}
|
||||
check_tag_commit(api, repo, tag, sha)
|
||||
release = get_release(tag_url)
|
||||
if release is None:
|
||||
release = json_request(base, "POST", {**metadata, "draft": True})
|
||||
elif release.get("target_commitish") != sha:
|
||||
raise ValueError("release tag already belongs to another source revision")
|
||||
release_url = f"{base}/{release['id']}"
|
||||
assets_url = f"{release_url}/assets"
|
||||
existing = request(assets_url)
|
||||
wanted = {path.name: path.stat().st_size for path in paths}
|
||||
digests = {path.name: sha256_file(path) for path in paths}
|
||||
present = {asset["name"]: asset for asset in existing}
|
||||
if not release.get("draft") and all(
|
||||
(asset := present.get(name)) is not None and asset["size"] == size
|
||||
and asset_digest(asset, api) == digests[name]
|
||||
for name, size in wanted.items()
|
||||
):
|
||||
if not check_tag_commit(api, repo, tag, sha):
|
||||
raise ValueError("published release has no Git tag")
|
||||
print(f"Release {tag} is already complete")
|
||||
return
|
||||
if not release.get("draft"):
|
||||
release = json_request(release_url, "PATCH", {**metadata, "draft": True})
|
||||
if not release.get("draft"):
|
||||
raise ValueError("incomplete release could not be returned to draft")
|
||||
for asset in existing:
|
||||
if asset["name"] in wanted:
|
||||
request(f"{assets_url}/{asset['id']}", "DELETE")
|
||||
for path in paths:
|
||||
query = urllib.parse.urlencode({"name": path.name})
|
||||
request(f"{assets_url}?{query}", "POST", path.read_bytes(),
|
||||
"application/octet-stream")
|
||||
uploaded = request(assets_url)
|
||||
actual = {asset["name"]: asset for asset in uploaded}
|
||||
if any((asset := actual.get(name)) is None or asset["size"] != size
|
||||
or asset_digest(asset, api) != digests[name]
|
||||
for name, size in wanted.items()):
|
||||
raise ValueError("draft release asset verification failed")
|
||||
check_tag_commit(api, repo, tag, sha)
|
||||
release = json_request(release_url, "PATCH", {**metadata, "draft": False})
|
||||
if release.get("draft"):
|
||||
raise ValueError("release remained a draft after publishing")
|
||||
if not check_tag_commit(api, repo, tag, sha):
|
||||
raise ValueError("published release did not create the expected Git tag")
|
||||
print(f"Published {tag} with {len(paths)} assets")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 4:
|
||||
sys.exit("usage: release.py TAG PRERELEASE FILE [FILE ...]")
|
||||
tag, prerelease, *names = sys.argv[1:]
|
||||
try:
|
||||
paths = files_to_publish(names)
|
||||
api = os.environ.get("GITHUB_API_URL", "https://gitea.bluefla.re/api/v1").rstrip("/")
|
||||
publish(tag, prerelease.lower() == "true", paths, api,
|
||||
os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_SHA"])
|
||||
except (ValueError, OSError, urllib.error.HTTPError) as error:
|
||||
sys.exit(f"release publication failed: {error}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"claims": [
|
||||
{
|
||||
"board": "a113d",
|
||||
"chip": "BM1366",
|
||||
"level": "protocol_decoded",
|
||||
"source": "miner-firmware/firmware-analysis/prong-b/aml-112/fullcov/capC1.strace",
|
||||
"sha256": "05303e93f6d00433a6db5a9ee973b6cdb0351f3efa35d293dd172ede7da89d54",
|
||||
"scope": "Historical BM1366 UART enumeration and nonce frames on an A113D S19k Pro"
|
||||
},
|
||||
{
|
||||
"board": "zynq-7010",
|
||||
"chip": "BM1366",
|
||||
"level": "catalogued",
|
||||
"source": "miner-firmware/firmware-analysis/prong-b/xil-137/fullcov/capC1.strace",
|
||||
"sha256": "3daa3f7381580ef87f3b5925d5a03fdb4d2e7cd93a82b943ef2578da3d545607",
|
||||
"scope": "Historical sensor and board observations; FPGA chip data path was not captured"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
gitea.bluefla.re/blueflare/alkane-ci@sha256:ad56db2fc456a3f1c68c715ba44309751cb5c455376d9f797ac346833c011e15
|
||||
@@ -0,0 +1,874 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Offline tests for the .afw producer and the CI brick-prevention gate."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
MAKE = ROOT / "ci" / "make-afw.sh"
|
||||
CHECK = ROOT / "ci" / "check-afw.py"
|
||||
REVISION = "0" * 40
|
||||
P1 = 16 * 1024 * 1024
|
||||
|
||||
|
||||
def run(command, **kwargs):
|
||||
return subprocess.run(command, text=True, capture_output=True, **kwargs)
|
||||
|
||||
|
||||
def fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
image = bytearray(4096)
|
||||
image[0x38:0x3C] = b"ARMd"
|
||||
image[0x08:0x10] = (0x200000).to_bytes(8, "little")
|
||||
(directory / "Image").write_bytes(image)
|
||||
|
||||
dtb = bytearray(1024)
|
||||
dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "cv-alkane.dtb").write_bytes(dtb)
|
||||
|
||||
(directory / "rootfs.cpio.gz").write_bytes(b"\x1f\x8b" + b"rootfs" + b"\0" * 64)
|
||||
|
||||
fit = bytearray(P1)
|
||||
fit[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
marker = b"config@cv1835_miner_emmc"
|
||||
fit[0x100 : 0x100 + len(marker)] = marker
|
||||
(directory / "alkane-cv1835-p1.fit").write_bytes(fit)
|
||||
return directory
|
||||
|
||||
|
||||
def build_afw(work, input_dir, name="good.afw", extra=()):
|
||||
output = work / "dist"
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"cv1835",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(input_dir),
|
||||
"--output",
|
||||
str(output),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
*extra,
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
def pack_members(directory, members, output):
|
||||
listing = output.with_suffix(".list")
|
||||
listing.write_text("\n".join(members) + "\n")
|
||||
result = run(
|
||||
[
|
||||
"tar",
|
||||
"--format=ustar",
|
||||
"--owner=0",
|
||||
"--group=0",
|
||||
"--numeric-owner",
|
||||
"--create",
|
||||
"--file",
|
||||
str(output),
|
||||
"-C",
|
||||
str(directory),
|
||||
"-T",
|
||||
str(listing),
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(result.stderr)
|
||||
listing.unlink()
|
||||
return output
|
||||
|
||||
|
||||
def rewrite_bundle(source, destination, edit_manifest=None, flip_payload=None):
|
||||
"""Unpack a bundle, edit the manifest or payload, and repack it strictly."""
|
||||
work = destination.parent / (destination.name + ".unpack")
|
||||
if work.exists():
|
||||
shutil.rmtree(work)
|
||||
work.mkdir()
|
||||
with tarfile.open(source, "r:") as archive:
|
||||
names = archive.getnames()
|
||||
archive.extractall(work)
|
||||
manifest_path = work / "manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
if edit_manifest is not None:
|
||||
edit_manifest(manifest, work)
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
members = ["manifest.json"]
|
||||
if manifest["signature"]["member"]:
|
||||
members.append(manifest["signature"]["member"])
|
||||
members.extend(image["file"] for image in manifest["images"])
|
||||
if flip_payload:
|
||||
for member in members:
|
||||
if member in ("manifest.json", "manifest.json.sig"):
|
||||
continue
|
||||
path = work / member
|
||||
if path.is_file():
|
||||
data = bytearray(path.read_bytes())
|
||||
if data:
|
||||
data[len(data) // 2] ^= 0x01
|
||||
path.write_bytes(data)
|
||||
break
|
||||
pack_members(work, members, destination)
|
||||
shutil.rmtree(work)
|
||||
return destination
|
||||
|
||||
|
||||
class AfwTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="afw-test."))
|
||||
self.input = fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_bundle_passes_and_reports_install(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "cv1835")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("install p1 -> p1", result.stdout)
|
||||
result = self.check(bundle, "--allow-unsigned", "--json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
summary = json.loads(result.stdout)
|
||||
self.assertEqual(summary["board"], "cv1835")
|
||||
self.assertEqual(summary["arch"], "arm64")
|
||||
self.assertEqual(summary["install"][0]["size"], P1)
|
||||
|
||||
def test_unsigned_bundle_needs_the_flag(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
result = self.check(bundle)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("unsigned", result.stderr)
|
||||
|
||||
def test_one_byte_tampered_payload_fails(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
tampered = rewrite_bundle(bundle, self.temp / "tampered.afw", flip_payload=True)
|
||||
result = self.check(tampered, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("sha256 mismatch", result.stderr)
|
||||
|
||||
def test_wrong_board_is_refused(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "zynq-7010")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("expected zynq-7010", result.stderr)
|
||||
|
||||
def test_manifest_cannot_claim_a_different_arch(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
manifest["arch"] = "armv7"
|
||||
|
||||
wrong = rewrite_bundle(bundle, self.temp / "wrong-arch.afw", edit_manifest=edit)
|
||||
result = self.check(wrong, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("must use arm64", result.stderr)
|
||||
|
||||
def test_truncated_tar_fails(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
truncated = self.temp / "truncated.afw"
|
||||
truncated.write_bytes(bundle.read_bytes()[:100])
|
||||
result = self.check(truncated, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("truncated", result.stderr)
|
||||
|
||||
def test_traversal_member_fails(self):
|
||||
stage = self.temp / "traversal"
|
||||
stage.mkdir()
|
||||
(stage / "manifest.json").write_text("{}\n")
|
||||
(stage / "payload").mkdir()
|
||||
(stage / "payload" / "p1.fit").write_bytes(b"\xd0\x0d\xfe\xed")
|
||||
bundle = self.temp / "traversal.afw"
|
||||
import io
|
||||
with tarfile.open(bundle, "w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for name, data in (
|
||||
("manifest.json", b"{}\n"),
|
||||
("payload/../escape", b"x"),
|
||||
):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
result = self.check(bundle, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("traversal", result.stderr)
|
||||
|
||||
def test_oversize_fit_is_refused_by_producer(self):
|
||||
fit = self.input / "alkane-cv1835-p1.fit"
|
||||
data = fit.read_bytes()
|
||||
fit.write_bytes(data + b"\0")
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"cv1835",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(self.input),
|
||||
"--output",
|
||||
str(self.temp / "dist"),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("larger than", result.stderr)
|
||||
|
||||
def test_oversize_fit_is_refused_by_checker(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"][-1]["size"] = P1 + 1
|
||||
manifest["images"][-1]["sha256"] = "0" * 64
|
||||
path = work / manifest["images"][-1]["file"]
|
||||
path.write_bytes(path.read_bytes() + b"\0")
|
||||
|
||||
oversize = rewrite_bundle(bundle, self.temp / "oversize.afw", edit_manifest=edit)
|
||||
result = self.check(oversize, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("exceeds partition", result.stderr)
|
||||
|
||||
def test_bootloader_member_under_preserve_is_refused(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append(
|
||||
{
|
||||
"name": "u-boot",
|
||||
"file": "payload/u-boot.img",
|
||||
"role": "bootloader",
|
||||
"format": "uimage",
|
||||
"size": 4,
|
||||
"sha256": "0" * 64,
|
||||
"partition": None,
|
||||
"install": False,
|
||||
}
|
||||
)
|
||||
(work / "payload" / "u-boot.img").write_bytes(b"\x27\x05\x19\x56")
|
||||
|
||||
wrong = rewrite_bundle(bundle, self.temp / "bootloader.afw", edit_manifest=edit)
|
||||
result = self.check(wrong, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("preserve", result.stderr)
|
||||
|
||||
def test_hash_mismatch_fails(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
manifest["images"][0]["sha256"] = "1" * 64
|
||||
|
||||
wrong = rewrite_bundle(bundle, self.temp / "hash.afw", edit_manifest=edit)
|
||||
result = self.check(wrong, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("sha256 mismatch", result.stderr)
|
||||
|
||||
def test_missing_image_fails_producer(self):
|
||||
(self.input / "Image").unlink()
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"cv1835",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(self.input),
|
||||
"--output",
|
||||
str(self.temp / "dist"),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("required image is missing", result.stderr)
|
||||
|
||||
def test_plan_size_cross_check(self):
|
||||
bundle = build_afw(self.temp, self.input)
|
||||
plan = self.temp / "plan.json"
|
||||
plan.write_text(json.dumps({
|
||||
"board": "cv1835",
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"partitions": [{"name": "p1", "size": P1}],
|
||||
}))
|
||||
result = self.check(bundle, "--allow-unsigned", "--plan", plan)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
plan.write_text(json.dumps({
|
||||
"board": "cv1835",
|
||||
"arch": "arm64",
|
||||
"bootloader_policy": "preserve",
|
||||
"partitions": [{"name": "p1", "size": P1 - 1}],
|
||||
}))
|
||||
result = self.check(bundle, "--allow-unsigned", "--plan", plan)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("differs from the manifest", result.stderr)
|
||||
|
||||
def test_unknown_board_fails(self):
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"whatsminer-h6",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(self.input),
|
||||
"--output",
|
||||
str(self.temp / "dist"),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("unknown board family", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
|
||||
AM_KERNEL_MAX = 0x500000
|
||||
AM_ROOT_MAX = 0x1400000
|
||||
|
||||
|
||||
def uimage_header(kind, payload=b"payload"):
|
||||
header = bytearray(64)
|
||||
header[0:4] = b"\x27\x05\x19\x56"
|
||||
header[12:16] = len(payload).to_bytes(4, "big")
|
||||
header[29] = 2 # ARM
|
||||
header[30] = kind # 2 kernel, 3 ramdisk
|
||||
header[31] = 0 if kind == 2 else 1
|
||||
header[32:48] = b"alkane-am335x\0\0\0"
|
||||
return bytes(header) + payload
|
||||
|
||||
|
||||
def am_fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "alkane-am335x.uImage").write_bytes(uimage_header(2, b"kernel"))
|
||||
dtb = bytearray(2048)
|
||||
dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "am335x-alkane.dtb").write_bytes(dtb)
|
||||
(directory / "alkane-am335x-ramdisk.uImage").write_bytes(
|
||||
uimage_header(3, b"ramdisk")
|
||||
)
|
||||
return directory
|
||||
|
||||
|
||||
def build_am_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-am"
|
||||
result = run(
|
||||
[
|
||||
"bash",
|
||||
str(MAKE),
|
||||
"--board",
|
||||
"am335x",
|
||||
"--version",
|
||||
"0.1.0",
|
||||
"--input",
|
||||
str(input_dir),
|
||||
"--output",
|
||||
str(output),
|
||||
"--sdk-revision",
|
||||
REVISION,
|
||||
"--os-revision",
|
||||
REVISION,
|
||||
"--allow-unsigned",
|
||||
*extra,
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class Am335xAfwTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="am335x-afw-test."))
|
||||
self.input = am_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_bundle_passes_and_reports_three_installs(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "am335x")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("board am335x arch arm", result.stdout)
|
||||
self.assertIn("bootloader preserve", result.stdout)
|
||||
result = self.check(bundle, "--allow-unsigned", "--json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
summary = json.loads(result.stdout)
|
||||
installs = {item["image"]: item["partition"] for item in summary["install"]}
|
||||
self.assertEqual(
|
||||
installs, {"kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
)
|
||||
|
||||
def test_oversize_kernel_is_refused_by_producer(self):
|
||||
path = self.input / "alkane-am335x.uImage"
|
||||
path.write_bytes(path.read_bytes() + b"\0" * (AM_KERNEL_MAX + 1))
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("larger than", result.stderr)
|
||||
|
||||
def test_oversize_root_is_refused_by_producer(self):
|
||||
path = self.input / "alkane-am335x-ramdisk.uImage"
|
||||
path.write_bytes(path.read_bytes() + b"\0" * (AM_ROOT_MAX + 1))
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("larger than", result.stderr)
|
||||
|
||||
def test_u_boot_member_under_preserve_is_refused(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append(
|
||||
{
|
||||
"name": "u-boot",
|
||||
"file": "payload/u-boot.img",
|
||||
"role": "component",
|
||||
"format": "uimage",
|
||||
"size": 4,
|
||||
"sha256": __import__("hashlib").sha256(b"boot").hexdigest(),
|
||||
"partition": None,
|
||||
"install": False,
|
||||
}
|
||||
)
|
||||
(work / "payload" / "u-boot.img").write_bytes(b"boot")
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "uboot.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("u-boot", result.stderr)
|
||||
|
||||
def test_manifest_cannot_claim_arm64(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
manifest["arch"] = "arm64"
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "wrong-arch.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("must use arm", result.stderr)
|
||||
|
||||
def test_mtd4_write_target_is_refused(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
for part in manifest["partitions"]:
|
||||
if part["name"] == "mtd4":
|
||||
part["write_order"] = 1
|
||||
part["image"] = "kernel"
|
||||
part["secure"] = False
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "mtd4.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("mtd4", result.stderr)
|
||||
|
||||
def test_offset_in_the_0x780000_hole_is_refused(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
for part in manifest["partitions"]:
|
||||
if part["name"] == "mtd8":
|
||||
part["offset"] = 0x780000
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "hole.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("hole", result.stderr)
|
||||
|
||||
def test_ramdisk_must_be_type_3(self):
|
||||
(self.input / "alkane-am335x-ramdisk.uImage").write_bytes(
|
||||
uimage_header(2, b"not-a-ramdisk")
|
||||
)
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("type-3 ramdisk", result.stderr)
|
||||
|
||||
def test_truncated_tar_fails(self):
|
||||
bundle = build_am_afw(self.temp, self.input)
|
||||
truncated = self.temp / "truncated.afw"
|
||||
truncated.write_bytes(bundle.read_bytes()[:100])
|
||||
result = self.check(truncated, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("truncated", result.stderr)
|
||||
|
||||
def test_traversal_member_fails(self):
|
||||
import io
|
||||
|
||||
bundle = self.temp / "traversal.afw"
|
||||
with tarfile.open(bundle, "w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for name, data in (
|
||||
("manifest.json", b"{}\n"),
|
||||
("payload/../escape", b"x"),
|
||||
):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
result = self.check(bundle, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("traversal", result.stderr)
|
||||
|
||||
def test_plan_json_cross_check(self):
|
||||
sdk = Path("/home/noah/projects/alkane-sdk")
|
||||
plan_yaml = sdk / "install" / "plans" / "am335x.yaml"
|
||||
if not plan_yaml.is_file():
|
||||
self.skipTest("alkane-sdk am335x plan not present")
|
||||
plan_json = self.temp / "am335x-plan.json"
|
||||
result = run(
|
||||
[
|
||||
sys.executable, str(sdk / "ci" / "check-plans.py"),
|
||||
"--plan", str(plan_yaml), "--emit-json", str(plan_json),
|
||||
]
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
bundle = build_am_afw(
|
||||
self.temp, self.input, extra=("--plan", str(plan_json))
|
||||
)
|
||||
result = self.check(
|
||||
bundle, "--allow-unsigned", "--plan", str(plan_json)
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
def am_stock_fixture_input(directory):
|
||||
"""The tier-3 from-stock input: adds our U-Boot (firmware uImage, type 5)
|
||||
alongside the kernel/dtb/ramdisk."""
|
||||
am_fixture_input(directory)
|
||||
(directory / "alkane-am335x-uboot-mtd4.uImage").write_bytes(
|
||||
uimage_header(5, b"u-boot")
|
||||
)
|
||||
return directory
|
||||
|
||||
|
||||
def build_am_stock_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-am-stock"
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x-stock", "--version", "0.1.0",
|
||||
"--input", str(input_dir), "--output", str(output),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned", *extra,
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class Am335xStockAfwTests(unittest.TestCase):
|
||||
"""Tier-3 from-stock bundle: writes U-Boot to mtd4 but must still refuse
|
||||
every SPL write and a wrongly-typed U-Boot member."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="am335x-stock-afw-test."))
|
||||
self.input = am_stock_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_stock_bundle_passes_with_four_installs(self):
|
||||
bundle = build_am_stock_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "am335x-stock")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("bootloader include", result.stdout)
|
||||
result = self.check(bundle, "--allow-unsigned", "--json")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
installs = {item["image"]: item["partition"] for item in json.loads(result.stdout)["install"]}
|
||||
self.assertEqual(
|
||||
installs, {"u-boot": "mtd4", "kernel": "mtd7", "dtb": "mtd6", "rootfs": "mtd8"}
|
||||
)
|
||||
|
||||
def test_u_boot_member_must_be_firmware_type(self):
|
||||
# A U-Boot payload wrongly built as a type-2 kernel uImage must be caught.
|
||||
(self.input / "alkane-am335x-uboot-mtd4.uImage").write_bytes(uimage_header(2, b"u-boot"))
|
||||
result = run(
|
||||
[
|
||||
"bash", str(MAKE), "--board", "am335x-stock", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "dist"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned",
|
||||
]
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("firmware", result.stderr + result.stdout)
|
||||
|
||||
def test_making_an_spl_copy_a_write_target_is_refused(self):
|
||||
bundle = build_am_stock_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, _work):
|
||||
for part in manifest["partitions"]:
|
||||
if part["name"] == "mtd0":
|
||||
part["secure"] = False
|
||||
part["write_order"] = 5
|
||||
part["image"] = "u-boot"
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "spl-write.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("mtd0", result.stderr)
|
||||
|
||||
|
||||
def zimage_blob(payload=b"zkernel"):
|
||||
# ARM zImage: magic 0x016f2818 (LE) at offset 0x24.
|
||||
b = bytearray(64)
|
||||
b[0x24:0x28] = b"\x18\x28\x6f\x01"
|
||||
return bytes(b) + payload
|
||||
|
||||
|
||||
def zynq_fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "zImage").write_bytes(zimage_blob())
|
||||
dtb = bytearray(1024); dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "zynq-alkane.dtb").write_bytes(dtb)
|
||||
(directory / "rootfs.cpio.gz").write_bytes(b"\x1f\x8b" + b"rootfs")
|
||||
return directory
|
||||
|
||||
|
||||
def build_zynq_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-zynq"
|
||||
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
|
||||
"--input", str(input_dir), "--output", str(output),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned", *extra])
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class ZynqAfwTests(unittest.TestCase):
|
||||
"""zynq-7010 tier-2 bundle: kernel(zImage)/dtb/rootfs, BOOT.bin preserved."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="zynq-afw-test."))
|
||||
self.input = zynq_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def test_good_zynq_bundle_passes(self):
|
||||
bundle = build_zynq_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "zynq-7010")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("bootloader preserve", result.stdout)
|
||||
|
||||
def test_non_zimage_kernel_is_refused(self):
|
||||
(self.input / "zImage").write_bytes(b"\x00" * 4096) # no zImage magic
|
||||
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "d"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("zImage", result.stderr + result.stdout)
|
||||
|
||||
def test_oversize_kernel_is_refused(self):
|
||||
(self.input / "zImage").write_bytes(zimage_blob(b"\x00" * (0x500000 + 1)))
|
||||
result = run(["bash", str(MAKE), "--board", "zynq-7010", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / "d"),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("ceiling", result.stderr + result.stdout)
|
||||
|
||||
def test_bootloader_member_is_refused(self):
|
||||
bundle = build_zynq_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append({
|
||||
"name": "u-boot", "file": "payload/BOOT.bin", "role": "bootloader",
|
||||
"format": "raw", "size": 4,
|
||||
"sha256": __import__("hashlib").sha256(b"boot").hexdigest(),
|
||||
"partition": None, "install": False,
|
||||
})
|
||||
(work / "payload" / "BOOT.bin").write_bytes(b"boot")
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "bl.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
|
||||
|
||||
def arm64_image_blob(payload=b"a64kernel"):
|
||||
# arm64 Linux Image: ASCII "ARMd" at offset 0x38.
|
||||
b = bytearray(64)
|
||||
b[0x38:0x3C] = b"ARMd"
|
||||
b[0x08:0x10] = (0x200000).to_bytes(8, "little") # text_offset / image_size hint
|
||||
return bytes(b) + payload
|
||||
|
||||
|
||||
def uramdisk_blob(payload=b"ramdisk"):
|
||||
# legacy uImage ramdisk (magic 0x27051956); a113d does not enforce arch/type.
|
||||
b = bytearray(64)
|
||||
b[0:4] = b"\x27\x05\x19\x56"
|
||||
b[12:16] = len(payload).to_bytes(4, "big")
|
||||
return bytes(b) + payload
|
||||
|
||||
|
||||
def a113d_fixture_input(directory):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "vmlinux.bin").write_bytes(arm64_image_blob())
|
||||
dtb = bytearray(2048); dtb[0:4] = b"\xd0\x0d\xfe\xed"
|
||||
(directory / "devicetree.dtb").write_bytes(bytes(dtb))
|
||||
(directory / "uramdisk.image.gz").write_bytes(uramdisk_blob())
|
||||
return directory
|
||||
|
||||
|
||||
def build_a113d_afw(work, input_dir, extra=()):
|
||||
output = work / "dist-a113d"
|
||||
result = run(["bash", str(MAKE), "--board", "a113d", "--version", "0.1.0",
|
||||
"--input", str(input_dir), "--output", str(output),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION,
|
||||
"--allow-unsigned", *extra])
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"producer failed:\n{result.stdout}\n{result.stderr}")
|
||||
files = list(output.glob("*.afw"))
|
||||
if len(files) != 1:
|
||||
raise AssertionError(f"expected one bundle, found {files}")
|
||||
return files[0]
|
||||
|
||||
|
||||
class A113dAfwTests(unittest.TestCase):
|
||||
"""a113d tier-2 bundle: kernel/dtb/rootfs staged into nvdata; FIP + mtd0-5 preserved."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = Path(tempfile.mkdtemp(prefix="a113d-afw-test."))
|
||||
self.input = a113d_fixture_input(self.temp / "sdk-out")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp, ignore_errors=True)
|
||||
|
||||
def check(self, path, *extra):
|
||||
return run([sys.executable, str(CHECK), str(path), *extra])
|
||||
|
||||
def make(self, outdir="d"):
|
||||
return run(["bash", str(MAKE), "--board", "a113d", "--version", "0.1.0",
|
||||
"--input", str(self.input), "--output", str(self.temp / outdir),
|
||||
"--sdk-revision", REVISION, "--os-revision", REVISION, "--allow-unsigned"])
|
||||
|
||||
def test_good_a113d_bundle_passes_and_preserves(self):
|
||||
bundle = build_a113d_afw(self.temp, self.input)
|
||||
result = self.check(bundle, "--allow-unsigned", "--expect-board", "a113d")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("afw: OK", result.stdout)
|
||||
self.assertIn("bootloader preserve", result.stdout)
|
||||
# all three images install into the nvdata UBI, never a raw mtd0-5 write
|
||||
self.assertEqual(result.stdout.count("-> nvdata"), 3)
|
||||
|
||||
def test_non_arm64_kernel_is_refused(self):
|
||||
(self.input / "vmlinux.bin").write_bytes(b"\x00" * 4096) # no ARMd magic
|
||||
result = self.make()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("arm64", (result.stderr + result.stdout).lower())
|
||||
|
||||
def test_oversize_kernel_is_refused(self):
|
||||
(self.input / "vmlinux.bin").write_bytes(arm64_image_blob(b"\x00" * (0x4000000 + 1)))
|
||||
result = self.make()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("ceiling", (result.stderr + result.stdout).lower())
|
||||
|
||||
def test_fip_member_is_refused(self):
|
||||
bundle = build_a113d_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
manifest["images"].append({
|
||||
"name": "fip", "file": "payload/fip.bin", "role": "bootloader",
|
||||
"format": "raw", "size": 4,
|
||||
"sha256": __import__("hashlib").sha256(b"fip!").hexdigest(),
|
||||
"partition": None, "install": False,
|
||||
})
|
||||
(work / "payload" / "fip.bin").write_bytes(b"fip!")
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "fip.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("fip", (result.stderr + result.stdout).lower())
|
||||
|
||||
def test_preserved_mtd_carrying_an_image_is_refused(self):
|
||||
bundle = build_a113d_afw(self.temp, self.input)
|
||||
|
||||
def edit(manifest, work):
|
||||
for partition in manifest["partitions"]:
|
||||
if partition["name"] != "nvdata":
|
||||
partition["image"] = "kernel" # try to aim a write at the FIP side
|
||||
break
|
||||
|
||||
bad = rewrite_bundle(bundle, self.temp / "pre.afw", edit_manifest=edit)
|
||||
result = self.check(bad, "--allow-unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("preserved", (result.stderr + result.stdout).lower())
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/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_baseline_must_match_cpu_class(self):
|
||||
first = "a" * 40
|
||||
host = {"architecture": "x86_64", "cpu_model": "A", "logical_cpus": 8}
|
||||
other = {"architecture": "x86_64", "cpu_model": "B", "logical_cpus": 8}
|
||||
index = {"entries": [{"sha": first, "metrics": {
|
||||
"bench_ns_per_op": {"hash": 10.0}, "bench_host": host}}]}
|
||||
distance = lambda _ancestor, _sha: 1
|
||||
self.assertEqual(previous_measurement(index, "b" * 40, distance, host),
|
||||
{"hash": 10.0})
|
||||
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
|
||||
|
||||
def test_site_escapes_history_content(self):
|
||||
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
|
||||
"metrics": {"bench_ns_per_op": {"hash": 10.0},
|
||||
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
|
||||
page = render_html({"entries": [entry]})
|
||||
self.assertIn("<script>", page)
|
||||
self.assertNotIn("<script>", page)
|
||||
self.assertIn("10.000", page)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Verify cleanup removes only generated files inside the CI checkout."""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"cleanup_generated", Path(__file__).resolve().with_name("cleanup-generated.py"))
|
||||
CLEANUP = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(CLEANUP)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-os-cleanup-") as temporary:
|
||||
root = Path(temporary)
|
||||
outside = root.parent / (root.name + "-outside")
|
||||
outside.mkdir()
|
||||
(outside / "keep").write_bytes(b"safe")
|
||||
previous = CLEANUP.ROOT
|
||||
CLEANUP.ROOT = root
|
||||
try:
|
||||
with patch.dict(os.environ, {"GITHUB_RUN_ID": "123"}):
|
||||
(root / "target").mkdir()
|
||||
(root / "target/build").write_bytes(b"generated")
|
||||
(root / "bench-current.txt").write_bytes(b"generated")
|
||||
CLEANUP.cleanup()
|
||||
assert not (root / "target").exists()
|
||||
assert not (root / "bench-current.txt").exists()
|
||||
(root / "target").symlink_to(outside, target_is_directory=True)
|
||||
try:
|
||||
CLEANUP.cleanup()
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("cleanup followed a symlink")
|
||||
assert (outside / "keep").read_bytes() == b"safe"
|
||||
finally:
|
||||
CLEANUP.ROOT = previous
|
||||
(outside / "keep").unlink()
|
||||
outside.rmdir()
|
||||
print("Alkane OS CI cleanup containment: PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Regression checks for the fail-closed release evidence gate."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).with_name("check-conformance.py")
|
||||
spec = importlib.util.spec_from_file_location("check_conformance", SCRIPT)
|
||||
gate = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gate)
|
||||
MANIFEST = json.loads(Path(__file__).with_name("conformance.json").read_text())
|
||||
TARGETS = {(row["board"], row["chip"]): gate.REQUIRED_ALGORITHMS[row["chip"]]
|
||||
for row in MANIFEST["targets"]}
|
||||
|
||||
|
||||
class ConformanceGateTest(unittest.TestCase):
|
||||
def test_placeholder_matrix_cannot_pass_without_current_run_artifacts(self):
|
||||
manifest = copy.deepcopy(MANIFEST)
|
||||
for row in manifest["targets"]:
|
||||
row.update(sdk_image_sha256="0" * 64,
|
||||
stock_image_sha256="0" * 64,
|
||||
simulator_trace_sha256="0" * 64,
|
||||
stock_result="mines",
|
||||
alkane_share_accept_capture="does-not-exist.json",
|
||||
bench_validation="not-run")
|
||||
with TemporaryDirectory() as directory:
|
||||
errors = gate.validate(manifest, TARGETS, Path(directory), "123",
|
||||
"a" * 40, "b" * 64)
|
||||
self.assertEqual(len(errors), 64)
|
||||
self.assertTrue(all("evidence invalid" in error for error in errors))
|
||||
|
||||
def test_stale_source_identity_is_rejected(self):
|
||||
row = copy.deepcopy(MANIFEST["targets"][0])
|
||||
row["stock_result"] = "mines"
|
||||
with TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
report = root / "123" / row["board"] / f"{row['chip']}.json"
|
||||
report.parent.mkdir(parents=True)
|
||||
report.write_text(json.dumps({"schema": 1, "run_id": "123",
|
||||
"source_commit": "f" * 40,
|
||||
"os_binary_sha256": "b" * 64,
|
||||
"board": row["board"], "chip": row["chip"],
|
||||
"stock_firmware_modified": False}))
|
||||
with self.assertRaisesRegex(ValueError, "different run, source"):
|
||||
gate.verify_cell(row, root, "123", "a" * 40, "b" * 64,
|
||||
TARGETS[(row["board"], row["chip"])])
|
||||
|
||||
def test_share_accept_requires_real_difficulty_one_work(self):
|
||||
capture = {"nonce_source": "real_silicon_capture",
|
||||
"header80": "00" * 80,
|
||||
"pool_target_le": "ff" * 32, "nonce": 0,
|
||||
"submission": {"id": 4, "method": "mining.submit",
|
||||
"params": ["worker", "job", "", "00000000", "00000000"]},
|
||||
"pool_response": {"id": 4, "result": True, "error": None}}
|
||||
with self.assertRaisesRegex(ValueError, "below difficulty one"):
|
||||
gate.verify_accept(capture, "Sha256")
|
||||
capture["submission"]["params"][4] = "00000001"
|
||||
with self.assertRaisesRegex(ValueError, "submitted nonce"):
|
||||
gate.verify_accept(capture, "Sha256")
|
||||
|
||||
def test_scrypt_proof_matches_litecoin_and_independent_vectors(self):
|
||||
header = bytes.fromhex(
|
||||
"01000000f615f7ce3b4fc6b8f61e8f89aedb1d0852507650533a9e3b10b9bbcc30639f27"
|
||||
"9fcaa86746e1ef52d3edb3c4ad8259920d509bd073605c9bf1d59983752a6b06b817bb4"
|
||||
"ea78e011d012d59d4"
|
||||
)
|
||||
self.assertEqual(len(header), 80)
|
||||
self.assertEqual(
|
||||
gate.proof_digest(header, "Scrypt")[::-1].hex(),
|
||||
"0000000110c8357966576df46f3b802ca897deb7ad18b12f1c24ecff6386ebd9",
|
||||
)
|
||||
self.assertEqual(
|
||||
gate.proof_digest(bytes(range(80)), "Scrypt").hex(),
|
||||
"bc540a1a801df96e493005c71e010e2d387607fbf0fec416fd3c2645aa1ba9d2",
|
||||
)
|
||||
|
||||
def test_equihash_cells_still_need_an_algorithm_specific_verifier(self):
|
||||
with self.assertRaisesRegex(ValueError, "Equihash share verifier"):
|
||||
gate.verify_accept({}, "Equihash")
|
||||
|
||||
def test_submitted_header_reconstruction_rejects_version_and_extranonce_changes(self):
|
||||
capture = {
|
||||
"subscription": {"extranonce1": "aa", "extranonce2_size": 1},
|
||||
"notify": {"method": "mining.notify", "params": [
|
||||
"job", "11" * 32, "01", "02", [],
|
||||
"20000000", "1d00ffff", "12345678", True]},
|
||||
"configure_response": {"result": {
|
||||
"version-rolling": True, "version-rolling.mask": "1fffe000"}},
|
||||
}
|
||||
params = ["worker", "job", "bb", "12345678", "00000001", "00002000"]
|
||||
header, _ = gate.reconstructed_header(capture, params)
|
||||
self.assertEqual(len(header), 80)
|
||||
self.assertEqual(header[:4], (0x20002000).to_bytes(4, "little"))
|
||||
self.assertEqual(header[4:8], b"\x11" * 4)
|
||||
changed = params.copy()
|
||||
changed[5] = "ffffffff"
|
||||
with self.assertRaisesRegex(ValueError, "version bits"):
|
||||
gate.reconstructed_header(capture, changed)
|
||||
changed[5] = params[5]
|
||||
changed[2] = "f"
|
||||
with self.assertRaisesRegex(ValueError, "Stratum hex"):
|
||||
gate.reconstructed_header(capture, changed)
|
||||
changed[2] = "cc"
|
||||
rebuilt, _ = gate.reconstructed_header(capture, changed)
|
||||
self.assertNotEqual(rebuilt, header)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Research observations cannot promote a target into release conformance."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
spec = importlib.util.spec_from_file_location("evidence_status", ROOT / "evidence_status.py")
|
||||
status = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(status)
|
||||
MATRIX = json.loads((ROOT / "conformance.json").read_text())
|
||||
RESEARCH = json.loads((ROOT / "research-evidence.json").read_text())
|
||||
|
||||
|
||||
class EvidenceStatusTest(unittest.TestCase):
|
||||
def test_historical_protocol_does_not_satisfy_release(self):
|
||||
report = status.summarize(MATRIX, RESEARCH)
|
||||
self.assertEqual(report["target_cells"], 64)
|
||||
self.assertEqual(report["research_only"], {"catalogued": 1, "protocol_decoded": 1})
|
||||
self.assertIsNone(report["verified_release_cells"])
|
||||
self.assertEqual(sum(report["release_manifest_declarations_unverified"].values()), 0)
|
||||
for level in ("stock_simulator_boot", "captured_nonce_pool_accept",
|
||||
"physical_install_update_uninstall_recovery", "full_release_cell"):
|
||||
self.assertIsNone(report["evidence_levels"][level]["current_run_verified"])
|
||||
|
||||
def test_rejects_missing_cell_and_unsupported_claim(self):
|
||||
matrix = copy.deepcopy(MATRIX)
|
||||
matrix["targets"].pop()
|
||||
with self.assertRaisesRegex(ValueError, "incomplete"):
|
||||
status.summarize(matrix, RESEARCH)
|
||||
research = copy.deepcopy(RESEARCH)
|
||||
research["claims"][0]["level"] = "pool_accept"
|
||||
with self.assertRaisesRegex(ValueError, "outside target matrix or level"):
|
||||
status.summarize(MATRIX, research)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Representative experiments preserve the full release target set."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
spec = importlib.util.spec_from_file_location("experiment_priority", ROOT / "experiment_priority.py")
|
||||
priority = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(priority)
|
||||
MATRIX = json.loads((ROOT / "conformance.json").read_text())
|
||||
QUEUE = json.loads((ROOT / "experiment-queue.json").read_text())
|
||||
|
||||
|
||||
class ExperimentPriorityTest(unittest.TestCase):
|
||||
def test_local_boot_model_ranks_first_without_reducing_gate(self):
|
||||
ordered = priority.rank(MATRIX, QUEUE)
|
||||
self.assertEqual(ordered[0]["id"], "am335x-original-nand-boot")
|
||||
self.assertEqual(ordered[0]["affected_release_cells"], 13)
|
||||
self.assertEqual(len(MATRIX["targets"]), 64)
|
||||
self.assertEqual(next(row for row in ordered if row["id"] == "bm1368-command-and-nonce")
|
||||
["affected_release_cells"], 4)
|
||||
|
||||
def test_no_selector_or_unexplained_blocker(self):
|
||||
queue = copy.deepcopy(QUEUE)
|
||||
queue["experiments"][0]["board"] = None
|
||||
with self.assertRaisesRegex(ValueError, "no target selector"):
|
||||
priority.rank(MATRIX, queue)
|
||||
queue = copy.deepcopy(QUEUE)
|
||||
queue["experiments"][1]["blocker"] = None
|
||||
with self.assertRaisesRegex(ValueError, "lacks a blocker"):
|
||||
priority.rank(MATRIX, queue)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Check that queued CI runs do not displace the last completed result."""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
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)
|
||||
environment = {
|
||||
"GITHUB_EVENT_NAME": "workflow_run",
|
||||
"GITHUB_REF": "refs/heads/main",
|
||||
"GITHUB_REPOSITORY": "owner/repo",
|
||||
"GITHUB_API_URL": "https://example.invalid/api/v1",
|
||||
"GITEA_TOKEN": "test-token",
|
||||
}
|
||||
with patch.dict(os.environ, environment), \
|
||||
patch.object(module, "latest_completed", side_effect=[(201, "success"),
|
||||
(202, "failure")]) as latest, \
|
||||
patch.object(module, "publish") as published:
|
||||
module.main()
|
||||
assert latest.call_count == 2
|
||||
assert [call.args[2] for call in published.call_args_list] == ["main", "next"]
|
||||
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "workflow_dispatch"}), \
|
||||
patch.object(module, "latest_completed", side_effect=[(201, "success"),
|
||||
(202, "failure")]), \
|
||||
patch.object(module, "publish") as published:
|
||||
module.main()
|
||||
assert published.call_count == 2
|
||||
with patch.dict(os.environ, {**environment, "GITHUB_EVENT_NAME": "schedule"}):
|
||||
try:
|
||||
module.main()
|
||||
except RuntimeError as error:
|
||||
assert "CI completion or manual dispatch" in str(error)
|
||||
else:
|
||||
raise AssertionError("scheduled event entered badge publisher")
|
||||
for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"):
|
||||
try:
|
||||
publish_file("https://example.invalid/api/v1", "owner/repo", invalid,
|
||||
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")
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Regression checks for measured benchmark and quality badges."""
|
||||
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from metrics import EXPECTED_BENCHES, bench_results, benchmark_delta, compact, quality_grade
|
||||
|
||||
|
||||
class MetricTests(unittest.TestCase):
|
||||
def test_quality_requires_both_static_checks(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "quality.json"
|
||||
path.write_text(json.dumps({"format": True, "clippy_warnings_denied": True}))
|
||||
self.assertEqual(quality_grade(path), "A")
|
||||
path.write_text(json.dumps({"format": True, "clippy_warnings_denied": False}))
|
||||
with self.assertRaises(ValueError):
|
||||
quality_grade(path)
|
||||
|
||||
def test_benchmark_parser_and_short_si_badge(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "bench.txt"
|
||||
path.write_text("test bench_sha ... BENCH sha 42.125 ns/op\n")
|
||||
self.assertEqual(bench_results(path), {"sha": 42.125})
|
||||
path.write_text("BENCH sha 42.125 ns/op\nBENCH sha 40.000 ns/op\n")
|
||||
with self.assertRaisesRegex(ValueError, "duplicate"):
|
||||
bench_results(path)
|
||||
path.write_text("BENCH sha 42.125 ns/op\nBENCH broken nan ns/op\n")
|
||||
with self.assertRaisesRegex(ValueError, "malformed"):
|
||||
bench_results(path)
|
||||
self.assertEqual(compact(1234567), "1.23M")
|
||||
|
||||
def test_benchmark_suite_and_baseline_must_be_complete(self):
|
||||
current = {name: 10.0 for name in EXPECTED_BENCHES}
|
||||
self.assertIsNone(benchmark_delta(current, {}))
|
||||
self.assertEqual(benchmark_delta(current, {"target_matrix": 20.0}), 50.0)
|
||||
with self.assertRaisesRegex(ValueError, "declared suite"):
|
||||
benchmark_delta({"target_matrix": 10.0}, {})
|
||||
with self.assertRaisesRegex(ValueError, "retired"):
|
||||
benchmark_delta(current, {"removed_bench": 20.0})
|
||||
with self.assertRaisesRegex(ValueError, "invalid measurements"):
|
||||
benchmark_delta(current, {"target_matrix": float("inf")})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Unknown PR paths must retain compiled source checks."""
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
spec = importlib.util.spec_from_file_location("pr_surface", Path(__file__).with_name("pr_surface.py"))
|
||||
surface = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(surface)
|
||||
|
||||
|
||||
class PrSurfaceTest(unittest.TestCase):
|
||||
def test_documentation_and_tooling(self):
|
||||
self.assertEqual(surface.classify(["README.md", "docs/boards.md"]), "documentation")
|
||||
self.assertEqual(surface.classify(["ci/evidence_status.py", "ci/CONFORMANCE.md"]), "tooling")
|
||||
|
||||
def test_unknown_and_rust_paths_fail_open_to_build(self):
|
||||
for paths in ([], ["src/main.rs"], ["Cargo.toml"], ["unknown/file"],
|
||||
["ci/evidence_status.py", "src/main.rs"]):
|
||||
with self.subTest(paths=paths):
|
||||
self.assertEqual(surface.classify(paths), "rust")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Check draft release recovery without making network requests."""
|
||||
|
||||
import importlib.util
|
||||
import hashlib
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).with_name("release.py")
|
||||
spec = importlib.util.spec_from_file_location("release", SCRIPT)
|
||||
release = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(release)
|
||||
|
||||
|
||||
class FakeGitea:
|
||||
def __init__(self):
|
||||
self.release = None
|
||||
self.assets = []
|
||||
self.blobs = {}
|
||||
self.fail_second_upload = True
|
||||
self.uploads = 0
|
||||
self.tag_sha = None
|
||||
|
||||
def request(self, url, method="GET", payload=None, content_type=None):
|
||||
if "/tags/" in url and "/releases/" not in url:
|
||||
if self.tag_sha is None:
|
||||
raise urllib.error.HTTPError(url, 404, "missing", {}, None)
|
||||
return {"commit": {"sha": self.tag_sha}}
|
||||
if "/assets" in url:
|
||||
if method == "GET":
|
||||
return list(self.assets)
|
||||
if method == "DELETE":
|
||||
asset_id = int(url.rsplit("/", 1)[1])
|
||||
self.assets = [item for item in self.assets if item["id"] != asset_id]
|
||||
self.blobs.pop(asset_id, None)
|
||||
return None
|
||||
self.uploads += 1
|
||||
if self.fail_second_upload and self.uploads == 2:
|
||||
raise OSError("injected upload failure")
|
||||
name = release.urllib.parse.parse_qs(url.split("?", 1)[1])["name"][0]
|
||||
item = {"id": self.uploads, "name": name, "size": len(payload),
|
||||
"browser_download_url": f"https://api/download/{self.uploads}"}
|
||||
self.assets.append(item)
|
||||
self.blobs[self.uploads] = payload
|
||||
return item
|
||||
if method == "GET":
|
||||
return self.release
|
||||
if method == "POST":
|
||||
assert self.release is None
|
||||
self.release = {**release.json.loads(payload), "id": 7}
|
||||
return dict(self.release)
|
||||
if method == "PATCH":
|
||||
self.release.update(release.json.loads(payload))
|
||||
if not self.release["draft"] and self.tag_sha is None:
|
||||
self.tag_sha = self.release["target_commitish"]
|
||||
return dict(self.release)
|
||||
raise AssertionError((method, url))
|
||||
|
||||
|
||||
class ReleaseTest(unittest.TestCase):
|
||||
def test_retry_after_partial_upload_keeps_release_draft_until_complete(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
paths = [Path(directory) / "source.tar.gz", Path(directory) / "bench.txt"]
|
||||
for path in paths:
|
||||
path.write_bytes(path.name.encode())
|
||||
fake = FakeGitea()
|
||||
def digest(asset, _api):
|
||||
return hashlib.sha256(fake.blobs[asset["id"]]).hexdigest()
|
||||
|
||||
with patch.object(release, "request", fake.request), \
|
||||
patch.object(release, "asset_digest", digest):
|
||||
with self.assertRaisesRegex(OSError, "injected upload failure"):
|
||||
release.publish("v1.2.3", False, paths, "https://api", "org/repo", "a" * 40)
|
||||
self.assertTrue(fake.release["draft"])
|
||||
self.assertEqual(len(fake.assets), 1)
|
||||
fake.fail_second_upload = False
|
||||
release.publish("v1.2.3", False, paths, "https://api", "org/repo", "a" * 40)
|
||||
self.assertFalse(fake.release["draft"])
|
||||
self.assertEqual({item["name"] for item in fake.assets},
|
||||
{path.name for path in paths})
|
||||
fake.assets[0]["size"] = len(fake.blobs[fake.assets[0]["id"]])
|
||||
fake.blobs[fake.assets[0]["id"]] = b"x" * fake.assets[0]["size"]
|
||||
release.publish("v1.2.3", False, paths, "https://api", "org/repo", "a" * 40)
|
||||
self.assertFalse(fake.release["draft"])
|
||||
self.assertEqual(digest(fake.assets[0], "https://api"),
|
||||
release.sha256_file(paths[0]))
|
||||
|
||||
def test_preflight_rejects_missing_and_duplicate_assets(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "one"
|
||||
with self.assertRaisesRegex(ValueError, "missing or empty"):
|
||||
release.files_to_publish([str(path)])
|
||||
path.write_bytes(b"x")
|
||||
with self.assertRaisesRegex(ValueError, "distinct"):
|
||||
release.files_to_publish([str(path), str(path)])
|
||||
|
||||
def test_existing_git_tag_mismatch_blocks_release_without_changes(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "image.tar.gz"
|
||||
path.write_bytes(b"image")
|
||||
fake = FakeGitea()
|
||||
fake.tag_sha = "b" * 40
|
||||
fake.release = {"id": 7, "tag_name": "v1.2.3",
|
||||
"target_commitish": "a" * 40, "draft": False}
|
||||
with patch.object(release, "request", fake.request):
|
||||
with self.assertRaisesRegex(ValueError, "Git tag points"):
|
||||
release.publish("v1.2.3", False, [path], "https://api",
|
||||
"org/repo", "a" * 40)
|
||||
self.assertEqual(fake.uploads, 0)
|
||||
self.assertFalse(fake.release["draft"])
|
||||
|
||||
def test_complete_release_without_git_tag_is_not_accepted(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "image.tar.gz"
|
||||
path.write_bytes(b"image")
|
||||
fake = FakeGitea()
|
||||
fake.release = {"id": 7, "tag_name": "v1.2.3",
|
||||
"target_commitish": "a" * 40, "draft": False}
|
||||
fake.assets = [{"id": 1, "name": path.name, "size": path.stat().st_size}]
|
||||
with patch.object(release, "request", fake.request), \
|
||||
patch.object(release, "asset_digest", lambda *_: release.sha256_file(path)):
|
||||
with self.assertRaisesRegex(ValueError, "no Git tag"):
|
||||
release.publish("v1.2.3", False, [path], "https://api",
|
||||
"org/repo", "a" * 40)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Check candidate numbering and covered-commit reruns with real Git tags."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
VERSION = Path(__file__).with_name("version.py")
|
||||
|
||||
|
||||
def git(root: Path, *args: str) -> str:
|
||||
result = subprocess.run(
|
||||
["git", *args], cwd=root, text=True, check=True, capture_output=True
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def selected(root: Path, branch: str) -> dict[str, str]:
|
||||
result = subprocess.run(
|
||||
["python3", str(VERSION), branch], cwd=root,
|
||||
text=True, check=True, capture_output=True
|
||||
)
|
||||
return dict(line.split("=", 1) for line in result.stdout.splitlines())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-os-version-") as path:
|
||||
root = Path(path)
|
||||
(root / "ci").mkdir()
|
||||
(root / "ci/version-x.txt").write_text("0\n")
|
||||
git(root, "init", "-q")
|
||||
git(root, "config", "user.name", "Alkane CI")
|
||||
git(root, "config", "user.email", "ci@example.invalid")
|
||||
git(root, "add", ".")
|
||||
git(root, "commit", "-qm", "First source")
|
||||
first = git(root, "rev-parse", "HEAD")
|
||||
assert selected(root, "next") == {
|
||||
"release": "true", "tag": "v0.1.0-rc.1", "version": "0.1.0-rc.1"
|
||||
}
|
||||
git(root, "tag", "v0.1.0-rc.1")
|
||||
assert selected(root, "next") == {"release": "false"}
|
||||
|
||||
(root / "README.md").write_text("A later merge.\n")
|
||||
git(root, "add", ".")
|
||||
git(root, "commit", "-qm", "Later source")
|
||||
assert selected(root, "next") == {
|
||||
"release": "true", "tag": "v0.1.0-rc.2", "version": "0.1.0-rc.2"
|
||||
}
|
||||
git(root, "tag", "v0.1.0-rc.2")
|
||||
assert selected(root, "next") == {"release": "false"}
|
||||
git(root, "checkout", "-q", first)
|
||||
assert selected(root, "next") == {"release": "false"}
|
||||
print("PASS: exact and superseded candidate reruns do not publish")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
0
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/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())
|
||||
# A rerun of a commit already covered by a published tag must not issue
|
||||
# a newer candidate number for older source.
|
||||
tagged_descendants = set(git("tag", "--contains", "HEAD", "-l", "v*").splitlines())
|
||||
known_tags = {tag for _, tag in versions("main") + versions("next")}
|
||||
if tagged_descendants & known_tags:
|
||||
print("release=false")
|
||||
return
|
||||
finals = versions("main")
|
||||
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()
|
||||
@@ -0,0 +1,110 @@
|
||||
# Code review report - alkane-os console/bus/login/dashboard/image
|
||||
|
||||
Scope: today's work on `feature/afw-os-bundle` (bus, registry, service, web, console,
|
||||
app, main, control, runtime, tuning, auth, dashboard, schema menus, image tooling).
|
||||
Method: code-review-harness, 4 parallel reviewers (correctness, security, reliability,
|
||||
maintainability) at high reasoning effort over the branch diff, then fixes applied and
|
||||
re-verified. Installation-from-stock / restore-to-stock method tooling was out of scope
|
||||
(DeepSeek Harness's domain; not in this repo).
|
||||
|
||||
## Verdict: READY TO SHIP (software checkpoint)
|
||||
|
||||
No Critical or High findings. The HTTP parser, login/session gate, bus semantics, and the
|
||||
crypto (HMAC-SHA256 / PBKDF2 / SHA-256 against RFC 4231 / RFC 7914 vectors) were verified
|
||||
correct; the session gate cannot be bypassed. Every Medium finding has been fixed and
|
||||
re-verified. Remaining items are Low / maintainability and are listed as deferred.
|
||||
|
||||
External tooling: `cargo clippy --all-targets -- -D warnings` clean; 206 lib tests + all
|
||||
integration tests pass; no emojis.
|
||||
|
||||
## Fixed in this pass
|
||||
|
||||
Security
|
||||
- `/api/files` and `/api/file` were reachable with a session but no token, contradicting
|
||||
the module docs and the Security page (arbitrary root-readable file exfiltration). Now
|
||||
token-gated via `authorised()`, matching the advertised control. (web.rs)
|
||||
- Response/header-splitting: `__section`/`__tab` from the settings form were interpolated
|
||||
into the `Location:` header; `%0d%0a` decoded to CRLF. Now constrained to safe slugs
|
||||
(`safe_slug`) before the redirect. (web.rs)
|
||||
- RNG degradation: an unreadable `/dev/urandom` substituted the published constant
|
||||
`"dev-csrf-token"` and second-granular, guessable session ids. Now a single token source
|
||||
(`auth::rand_hex`) that warns loudly and falls back to a per-call, non-constant mix; the
|
||||
CSRF generator delegates to it. (auth.rs, web.rs)
|
||||
- The UI token was compared with `==` (timing oracle). Now `auth::ct_eq` (constant time).
|
||||
(web.rs)
|
||||
- `auth.json` (password hash) was written umask-default (world-readable). Now created 0600
|
||||
with the parent dir 0700. (auth.rs)
|
||||
- Unbounded thread-per-connection + no absolute read deadline (flood DoS on the open :80).
|
||||
Now a 64-connection cap (503 beyond it) and a 10 s head-read deadline, on top of the
|
||||
per-read timeout. (web.rs)
|
||||
|
||||
Reliability / correctness
|
||||
- Settings persistence swallowed its write error and reported success with a misleading
|
||||
comment. Now the error propagates (surfaced as the form's rejection) and the write is
|
||||
atomic (temp + rename). Deck save is atomic too. (dashboard.rs, service.rs)
|
||||
- `Auth::login` returned a cookie even if the session insert failed (redirect loop). Now
|
||||
returns `None` on a poisoned lock. (auth.rs)
|
||||
- `TuningLoop::set_target` carried the PID integral across modes whose error is in
|
||||
different units (watts vs millidegrees vs TH/s), injecting a stale push on a mode switch.
|
||||
Now the accumulator resets on a target change while the operating point is kept. (tuning.rs)
|
||||
- Editable-deck JS: new-block ids collided after remove-then-add (duplicate ids, both
|
||||
deleted on remove); the default new-block source `power_w` wasn't in the live-value map
|
||||
(rendered n/a); drag-drop placement was asymmetric; save didn't re-render the normalized
|
||||
doc. All fixed. (console.rs)
|
||||
- Drivers page showed `"temperature"` with JSON quotes for the stopped reason. Now the bare
|
||||
string. (web.rs)
|
||||
|
||||
Maintainability
|
||||
- `percent_decode` / form-field parsing existed in three divergent copies; consolidated into
|
||||
one `form` module used by web, service and dashboard. The CSPRNG-to-hex helper is now one
|
||||
function (`auth::rand_hex`).
|
||||
- Added a test asserting the published state topics match the registry contract (the
|
||||
"single source of truth" claim for topics was previously unenforced).
|
||||
|
||||
## Deferred (reported, not blocking)
|
||||
|
||||
- `ui.rs` is now largely dead: only `validate_deck` / `default_deck` (+ two consts) are used
|
||||
(by `service.rs`); the legacy console (`page`, `dashboard_page`, `sidebar`, `NAV`, the CSS/JS
|
||||
consts, `icon`/`group_icon_svg` which `Box::leak`) has no callers. Recommend moving the two
|
||||
deck helpers to a `deck` module and deleting the rest. (~34 KB)
|
||||
- `control::target_label` vs `app::target_label` are two implementations of the same mapping;
|
||||
recommend one canonical (e.g. in `tuning`).
|
||||
- `DECK_CSS` / `DECK_JS` / `TERMINAL_JS` are large inline strings; recommend moving to
|
||||
`assets/*.js|css`, `include_str!`, and serving under `/assets` like the stylesheets, so they
|
||||
can be linted.
|
||||
- `web.rs` still owns host-fact gatherers (`system_rows`, ...) that `console.rs` consumes;
|
||||
recommend a `hostfacts` module both depend on.
|
||||
- `route()` is long; the `/api/*` arm could be an `api_route()`.
|
||||
- `Dashboard::page()` is now test-only (console renders pages); remove or mark reference-only.
|
||||
- serve_sim's control loop spins silently if the in-process HAL thread dies; recommend
|
||||
surfacing the fault and dropping `running` (the real-hardware `boot_hal` loop already exits
|
||||
on a HAL write error, so this is dev-path only).
|
||||
- `make-zynq-afw.sh` usage comment omits `--sdk-dir` (doc drift).
|
||||
- No change-password route exists though the login page tells the operator to change
|
||||
admin/admin; wire one or soften the text.
|
||||
|
||||
## Accepted-by-design posture (stated, not defects)
|
||||
|
||||
The box is SSH-guarded and the console is defense-in-depth on a shared network:
|
||||
- No TLS: the console is HTTP on `0.0.0.0:80`, so a passive sniffer can capture the password
|
||||
and session cookie. This is the dominant residual risk and should be made explicit to the
|
||||
operator. A TLS front (or binding the console to a management interface / WireGuard) is the
|
||||
real mitigation.
|
||||
- Factory `admin`/`admin` with nothing forcing a change; the login page prints it.
|
||||
- `/api/terminal` is a gated (session + token) root `/bin/sh` - an accepted diagnostic on an
|
||||
already-root-reachable box. Note the shipped terminal UI does not send the token, so it is
|
||||
fail-closed/unusable until a token is supplied.
|
||||
- The web process runs as root (binds 80); consider a post-bind privilege drop.
|
||||
- `/api/hardware|summary|control` are intentionally open (interface of record, mirror of the
|
||||
cgminer socket).
|
||||
- PBKDF2 at 50k iterations - low by modern standards, accepted behind SSH; matters only if the
|
||||
hash leaks (now 0600).
|
||||
- `make-zynq-afw.sh` always passes `--allow-unsigned` (bench-only helper; do not reuse on a
|
||||
release path).
|
||||
|
||||
## Verification after fixes
|
||||
|
||||
Live `--serve-sim`: unauthenticated GET / serves the login page; admin/admin issues a session
|
||||
and the console renders; `/api/files` returns 403 without a token; a CRLF-injected `__section`
|
||||
is neutralized (303, no header split); the editable deck saves and reloads. clippy -D warnings
|
||||
clean; 206 lib tests + integration pass.
|
||||
@@ -0,0 +1,179 @@
|
||||
# .afw OS install bundle format
|
||||
|
||||
Status: schema 2. Released only by `alkane-os`. One `.afw` is valid for exactly
|
||||
one board family.
|
||||
|
||||
An `.afw` is a full OS install bundle: kernel, device tree, rootfs, the
|
||||
bootable image(s), the partition plan, the boot switch, the preflight rules and
|
||||
the network recovery path. It is not an application package.
|
||||
|
||||
## Container
|
||||
|
||||
A strict POSIX ustar archive. No compression, no directory entries, no leading
|
||||
`./`, no GNU long-name or pax members, and no links. Members are, in this exact
|
||||
order:
|
||||
|
||||
1. `manifest.json`
|
||||
2. `manifest.json.sig` (only for an Ed25519-signed bundle)
|
||||
3. Each payload member named by `manifest.images[].file`, in manifest order.
|
||||
|
||||
Every member is a regular file. The manifest is at most 64 KiB. The verifier
|
||||
reads the tar itself: it checks the header checksum, rejects path traversal,
|
||||
absolute paths, duplicate names, non-regular members and truncated archives,
|
||||
and requires the two-block end marker. It verifies the manifest and every
|
||||
payload hash before any consumer may write to a board.
|
||||
|
||||
## Manifest
|
||||
|
||||
Required members:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `schema` | `2` |
|
||||
| `format` | `afw` |
|
||||
| `board` | One board family, for example `cv1835` |
|
||||
| `arch` | `arm64` or `armv7`; must match the board profile |
|
||||
| `version` | Release version |
|
||||
| `build_date` | UTC ISO-8601 |
|
||||
| `sdk_revision` | 40-character SDK git revision |
|
||||
| `os_revision` | 40-character alkane-os git revision |
|
||||
| `payload_type` | `os` |
|
||||
| `bootloader_policy` | `include` or `preserve` |
|
||||
| `signature` | Signature object, see below |
|
||||
| `partitions` | Partition plan, see below |
|
||||
| `images` | Payload images, see below |
|
||||
| `boot_switch` | How the preserved or written boot path selects the new OS |
|
||||
| `preflight` | Required commands, forbidden devices, free space, source OS list |
|
||||
| `recovery` | Network recovery command, held partition, golden copy location |
|
||||
| `marker` | String served by the installed OS, used by `afw verify-live` |
|
||||
| `kernel_version` | Kernel release the installed OS must report |
|
||||
|
||||
`notes` is optional. Unknown keys are ignored by this schema so a future field
|
||||
does not break old readers.
|
||||
|
||||
### Images
|
||||
|
||||
Each image entry has `name`, `file`, `role`, `format`, `size`, `sha256`,
|
||||
`partition` (or null) and `install` (bool). Roles are `kernel`, `dtb`,
|
||||
`rootfs`, `bootloader`, `boot` and `component`. Formats are `fit`,
|
||||
`arm64-image`, `fdt`, `cpio-gzip`, `uimage` and `raw`.
|
||||
|
||||
An image with `install: true` must name a partition and is the only kind the
|
||||
installer writes. Component images (kernel, dtb, rootfs) are carried for
|
||||
inspection and for boards whose installer composes them; for CV1835 they are
|
||||
also the inputs of the p1 FIT.
|
||||
|
||||
`bootloader_policy: preserve` means no image with role `bootloader` may be
|
||||
present. `include` means exactly one must be present. The toolkit refuses a
|
||||
bundle whose policy does not match its board module.
|
||||
|
||||
### Partitions
|
||||
|
||||
Each partition entry has `name`, `device`, `offset`, `size`, `secure`,
|
||||
`boot_critical`, `write_order` and `image` (or null). Secure partitions and
|
||||
`boot0` are declared so preflight can refuse them, never as write targets.
|
||||
`write_order` is 0 for a region that is not written and a positive order for
|
||||
an install target.
|
||||
|
||||
For CV1835 the plan is:
|
||||
|
||||
| Region | Device | Size | Secure | Written |
|
||||
|---|---|---|---|---|
|
||||
| `p1` | `/dev/mmcblk0p1` | 16 MiB | no | yes, order 1 |
|
||||
| `p3` | `/dev/mmcblk0p3` | 32 MiB | yes | no |
|
||||
| `boot0` | `/dev/mmcblk0boot0` | 4 MiB | yes | no |
|
||||
| `boot1` | `/dev/mmcblk0boot1` | 4 MiB | yes | no |
|
||||
|
||||
The p1 payload is the 16 MiB padded FIT. A FIT larger than the partition is a
|
||||
build failure. A wrong or missing FIT is a boot failure, not a write failure,
|
||||
as long as the held p1 backup is present.
|
||||
|
||||
## Signatures
|
||||
|
||||
`signature` is always an object:
|
||||
|
||||
```json
|
||||
{"type": "unsigned", "member": null, "public_key_hex": null}
|
||||
```
|
||||
|
||||
A signed bundle uses:
|
||||
|
||||
```json
|
||||
{"type": "ed25519", "member": "manifest.json.sig",
|
||||
"public_key_hex": "<64 hex characters>"}
|
||||
```
|
||||
|
||||
`manifest.json.sig` is the 64-byte raw Ed25519 signature over the exact
|
||||
`manifest.json` bytes, and is the second member. The key is a 32-byte raw seed
|
||||
or 64 hex characters in a file named by the release environment; no key value
|
||||
is stored in this repository. Adding a signature changes only the member set,
|
||||
not the schema, so unsigned bundles remain readable.
|
||||
|
||||
Site use requires a signed bundle. The bench allows an unsigned bundle only
|
||||
with `--allow-unsigned`, which prints a warning and the payload SHA-256.
|
||||
|
||||
## Build and check
|
||||
|
||||
The producer stages the manifest and payload, pads the CV p1 FIT to exactly
|
||||
16 MiB, and packs the members. The checker is the release gate. Both are
|
||||
offline and use only the Python standard library, except that Ed25519 signing
|
||||
and verification use the `cryptography` package.
|
||||
|
||||
```sh
|
||||
alkane-os/ci/make-afw.sh \
|
||||
--board cv1835 --version 0.1.0 \
|
||||
--input alkane-sdk/build/out/cv1835 \
|
||||
--sdk-revision "$(git -C alkane-sdk rev-parse HEAD)" \
|
||||
--os-revision "$(git -C alkane-os rev-parse HEAD)" \
|
||||
--output alkane-os/dist --allow-unsigned
|
||||
|
||||
python3 alkane-os/ci/check-afw.py \
|
||||
alkane-os/dist/alkane-os-0.1.0-cv1835-arm64.afw \
|
||||
--allow-unsigned --expect-board cv1835
|
||||
```
|
||||
|
||||
The checker fails on a wrong board or arch, a missing image, an image larger
|
||||
than its partition, a bootloader member under `preserve`, a hash or size
|
||||
mismatch, a path-traversal member, a truncated tar, a signed bundle without a
|
||||
valid signature, or an unsigned bundle without the explicit flag.
|
||||
|
||||
## Install rule
|
||||
|
||||
The toolkit verifies the whole bundle before opening a transport. It then
|
||||
preflights the board, holds the current p1 over the network, writes only the
|
||||
declared install partition, reads the whole partition back, and compares the
|
||||
hash before it reboots. No install step needs a serial console, an SD card, a
|
||||
U-Boot prompt, JTAG or a button.
|
||||
|
||||
## AM335x (legacy-uImage, non-FIT)
|
||||
|
||||
`am335x` is the BeagleBone-class AM335x slice. The board already runs our
|
||||
non-RSA U-Boot, so the bundle preserves mtd0-5 (SPL, U-Boot, bootenv) and
|
||||
writes only:
|
||||
|
||||
| Region | Device | Size | Image | Order |
|
||||
|---|---|---|---|---|
|
||||
| `mtd8` | `/dev/mtd8` | 20 MiB | type-3 ramdisk uImage | 1 |
|
||||
| `mtd6` | `/dev/mtd6` | 128 KiB | dtb (FDT) | 2 |
|
||||
| `mtd7` | `/dev/mtd7` | 5 MiB | type-2 kernel uImage | 3 |
|
||||
|
||||
`mtd0-5` are declared secure, image-free and outside the write order. Every
|
||||
partition offset is taken from the 12-entry map, including the unmapped
|
||||
512 KiB hole at `0x780000-0x800000`; mtd7 ends at `0x780000` and mtd8 starts
|
||||
at `0x800000`, never `0x780000`. The producer and both checkers refuse an
|
||||
offset in the hole, a write to mtd0-5, an image over its mtd ceiling, a
|
||||
bundle carrying an spl/u-boot member, a wrong arch, an oversize image, a
|
||||
truncated tar, or a traversal member. The images are legacy ARM uImages
|
||||
(kernel type 2, ramdisk type 3); a FIT is rejected.
|
||||
|
||||
```sh
|
||||
alkane-os/ci/make-afw.sh \
|
||||
--board am335x --version 0.1.0 \
|
||||
--input alkane-sdk/build/out/am335x \
|
||||
--sdk-dir alkane-sdk --plan am335x-plan.json \
|
||||
--output alkane-os/dist --allow-unsigned
|
||||
|
||||
python3 alkane-os/ci/check-afw.py \
|
||||
alkane-os/dist/alkane-os-0.1.0-am335x-arm.afw \
|
||||
--allow-unsigned --expect-board am335x
|
||||
```
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Bounded host-only check: captured BM13xx report through HAL to a strict pool.
|
||||
|
||||
use alkane_os::hal_wire::HalClient;
|
||||
use alkane_os::miner::Bm1366Miner;
|
||||
use alkane_os::stratum_client::{PoolConnection, PoolEvent, ReportEvent};
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const CAPTURED_HEADER: [u8; 80] = [
|
||||
0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38, 0x9d,
|
||||
0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, 0x57, 0xb6, 0xc2, 0x25,
|
||||
0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78,
|
||||
0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38,
|
||||
0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
|
||||
const BM1362_HEADER_HEX: &str = concat!(
|
||||
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
|
||||
"b4213a0503969b7384e1215aace8cfc65dae22d8493ad48fec0b7ac3b0ad7b4e7",
|
||||
"fb0c5c0012e6a8f06021700000000"
|
||||
);
|
||||
|
||||
fn bm1362_header() -> Result<[u8; 80], io::Error> {
|
||||
let mut header = [0_u8; 80];
|
||||
for (index, pair) in BM1362_HEADER_HEX.as_bytes().chunks_exact(2).enumerate() {
|
||||
let digits = std::str::from_utf8(pair).map_err(io::Error::other)?;
|
||||
header[index] = u8::from_str_radix(digits, 16).map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
fn failure(message: impl Into<String>) -> io::Error {
|
||||
io::Error::other(message.into())
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let socket = args.next().ok_or_else(|| {
|
||||
failure("usage: simulator_pool_replay_probe HAL_SOCKET POOL_ADDRESS [SHARES] [CHIP]")
|
||||
})?;
|
||||
let address: SocketAddr = args
|
||||
.next()
|
||||
.ok_or_else(|| failure("missing pool address"))?
|
||||
.parse()?;
|
||||
let expected_accepts: usize = args.next().map_or(Ok(1), |value| value.parse())?;
|
||||
if !(1..=64).contains(&expected_accepts) {
|
||||
return Err(failure("SHARES must be between 1 and 64").into());
|
||||
}
|
||||
let chip = args.next().unwrap_or_else(|| "BM1366".to_owned());
|
||||
let first_header = match chip.as_str() {
|
||||
"BM1366" => CAPTURED_HEADER,
|
||||
"BM1362" if expected_accepts == 1 => bm1362_header()?,
|
||||
"BM1362" => return Err(failure("BM1362 has one captured header").into()),
|
||||
_ => return Err(failure("unsupported captured chip").into()),
|
||||
};
|
||||
if args.next().is_some() {
|
||||
return Err(failure("unexpected argument").into());
|
||||
}
|
||||
if !address.ip().is_loopback() {
|
||||
return Err(failure("probe pool must be on loopback").into());
|
||||
}
|
||||
|
||||
let mut backend = HalClient::connect(socket)?;
|
||||
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000)
|
||||
.ok_or_else(|| failure("invalid simulator configuration"))?;
|
||||
let mut pool = PoolConnection::connect(
|
||||
address,
|
||||
"alkane-simulator-probe",
|
||||
"alkane.test",
|
||||
"x",
|
||||
Duration::from_secs(2),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.map_err(|error| failure(format!("pool handshake: {error:?}")))?;
|
||||
miner.start()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(10 + 2 * expected_accepts as u64);
|
||||
let mut issued = 0;
|
||||
let mut submitted = 0;
|
||||
let mut accepted = 0;
|
||||
while Instant::now() < deadline {
|
||||
let (event, reports) = pool
|
||||
.cycle(&mut miner)
|
||||
.map_err(|error| failure(format!("mining cycle: {error:?}")))?;
|
||||
submitted += reports
|
||||
.iter()
|
||||
.filter(|report| matches!(report, ReportEvent::Submitted(_)))
|
||||
.count();
|
||||
match event {
|
||||
PoolEvent::Work(work) => {
|
||||
if issued == 0 && work.header != first_header {
|
||||
return Err(failure("pool job differs from real-silicon capture").into());
|
||||
}
|
||||
issued += 1;
|
||||
}
|
||||
PoolEvent::ShareAccepted(_) => {
|
||||
if accepted >= submitted || accepted >= issued {
|
||||
return Err(failure("unattributed pool acceptance").into());
|
||||
}
|
||||
accepted += 1;
|
||||
if accepted == expected_accepts {
|
||||
miner.stop()?;
|
||||
println!(
|
||||
"{chip} real captured nonce accepted by strict loopback pool ({accepted} shares)"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
PoolEvent::ShareRejected(_) => return Err(failure("pool rejected share").into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(failure("captured share was not accepted before deadline").into())
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Exercise the SDK's host-only BM13xx HAL simulator with a captured job.
|
||||
|
||||
use alkane_os::hal_wire::HalClient;
|
||||
use alkane_os::miner::{Bm1366Miner, ChipModel};
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
|
||||
const HEADER: [u8; 80] = [
|
||||
0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38, 0x9d,
|
||||
0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, 0x57, 0xb6, 0xc2, 0x25,
|
||||
0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78,
|
||||
0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38,
|
||||
0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
|
||||
const BM1362_HEADER_HEX: &str = concat!(
|
||||
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
|
||||
"b4213a0503969b7384e1215aace8cfc65dae22d8493ad48fec0b7ac3b0ad7b4e7",
|
||||
"fb0c5c0012e6a8f06021700000000"
|
||||
);
|
||||
|
||||
fn bm1362_header() -> Result<[u8; 80], io::Error> {
|
||||
let mut header = [0_u8; 80];
|
||||
for (index, pair) in BM1362_HEADER_HEX.as_bytes().chunks_exact(2).enumerate() {
|
||||
let digits = std::str::from_utf8(pair).map_err(io::Error::other)?;
|
||||
header[index] = u8::from_str_radix(digits, 16).map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let path = args
|
||||
.next()
|
||||
.ok_or("usage: simulator_replay_probe SOCKET_PATH [BM1366|BM1362]")?;
|
||||
let chip = args.next().unwrap_or_else(|| "BM1366".to_owned());
|
||||
if args.next().is_some() {
|
||||
return Err("unexpected argument".into());
|
||||
}
|
||||
let (header, nonce, model) = match chip.as_str() {
|
||||
"BM1366" => (HEADER, 0xedad_ff38, ChipModel::Bm1366),
|
||||
"BM1362" => (bm1362_header()?, 0x630b_2533, ChipModel::Bm1362),
|
||||
_ => return Err("unsupported captured chip".into()),
|
||||
};
|
||||
let mut backend = HalClient::connect(path)?;
|
||||
// Chip initialization is outside this host-only check.
|
||||
let mut miner = Bm1366Miner::new_for_chip(&mut backend, model, 0, 0, 0, 100, 80_000)
|
||||
.ok_or("invalid simulator probe configuration")?;
|
||||
miner.start()?;
|
||||
let mut target = [0_u8; 32];
|
||||
target[26..28].fill(0xff);
|
||||
miner.submit(header, target, 0x18)?;
|
||||
let share = miner.poll()?.ok_or("missing captured nonce report")?;
|
||||
miner.stop()?;
|
||||
assert_eq!(share.nonce, nonce);
|
||||
println!("{chip} captured report verified at difficulty 1");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Vendored flare-ui pin. Re-vendor with scripts, never edit the tree by hand.
|
||||
repo = https://gitea.bluefla.re/blueflare/flare-ui
|
||||
branch = sprint
|
||||
commit = 0e1f5a259faa32798bbb9ff3fedaa0b5faf5302d
|
||||
vendored = 2026-11-10
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a zynq-7010 .afw carrying the current alkane-os console.
|
||||
#
|
||||
# The SDK builds the base OS (kernel, dtb, rootfs) for the board; this script
|
||||
# cross-compiles the current alkane-os binary for armv7 (static musl, matching
|
||||
# the SDK rootfs), drops it and the image overlay (image/overlay) into the SDK's
|
||||
# rootfs, repacks the ramdisk, and packages the three images into a .afw with
|
||||
# ci/make-afw.sh. The rootfs is repacked under fakeroot so device nodes and root
|
||||
# ownership survive. Unsigned is bench-only.
|
||||
#
|
||||
# usage:
|
||||
# image/make-zynq-afw.sh [--sdk-out DIR] [--version X.Y.Z] [--skip-build]
|
||||
# defaults: --sdk-out ../alkane-sdk/build/out/zynq-7010 --version 0.1.0
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
SDK_OUT="$ROOT/../alkane-sdk/build/out/zynq-7010"
|
||||
SDK_DIR="$ROOT/../alkane-sdk"
|
||||
VERSION=0.1.0
|
||||
TARGET=armv7-unknown-linux-musleabihf
|
||||
SKIP_BUILD=0
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--sdk-out) SDK_OUT=$2; shift 2 ;;
|
||||
--sdk-dir) SDK_DIR=$2; shift 2 ;;
|
||||
--version) VERSION=$2; shift 2 ;;
|
||||
--skip-build) SKIP_BUILD=1; shift ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
command -v fakeroot >/dev/null 2>&1 || { echo "fakeroot is required" >&2; exit 1; }
|
||||
SDK_OUT="$(cd "$SDK_OUT" && pwd)"
|
||||
for f in zImage zynq-alkane.dtb rootfs.cpio.gz; do
|
||||
[ -f "$SDK_OUT/$f" ] || { echo "missing SDK image: $SDK_OUT/$f (build it in alkane-sdk first)" >&2; exit 1; }
|
||||
done
|
||||
|
||||
TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}"
|
||||
BIN="$TARGET_DIR/$TARGET/release/alkane-os"
|
||||
if [ "$SKIP_BUILD" -eq 0 ]; then
|
||||
echo "cross-compiling alkane-os for $TARGET (static)"
|
||||
# rustc drives the final link through a C compiler; the host cc cannot link
|
||||
# ARM objects, so use the ARM cross-gcc as the linker (musl crt + libs come
|
||||
# from rustup's self-contained target, so only the ARM linker driver is used).
|
||||
export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER="${ARMV7_LINKER:-arm-linux-gnueabihf-gcc}"
|
||||
( cd "$ROOT" && cargo build --release --offline --target "$TARGET" --bin alkane-os )
|
||||
fi
|
||||
[ -f "$BIN" ] || { echo "cross-compiled binary not found: $BIN" >&2; exit 1; }
|
||||
|
||||
WORK=$(mktemp -d "${TMPDIR:-/tmp}/zynq-afw.XXXXXX")
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
mkdir -p "$WORK/in"
|
||||
|
||||
echo "staging the console binary"
|
||||
cp "$BIN" "$WORK/alkane-os"
|
||||
command -v arm-linux-gnueabihf-strip >/dev/null 2>&1 && arm-linux-gnueabihf-strip "$WORK/alkane-os" || true
|
||||
|
||||
echo "repacking the SDK rootfs with the console + overlay (under fakeroot)"
|
||||
cat > "$WORK/pack.sh" <<'PACK'
|
||||
set -e
|
||||
RFS=$1; SDK_OUT=$2; WORK=$3; OVERLAY=$4; VERSION=$5
|
||||
mkdir -p "$RFS"
|
||||
( cd "$RFS" && zcat "$SDK_OUT/rootfs.cpio.gz" | cpio -idm --quiet )
|
||||
install -D -m 0755 "$WORK/alkane-os" "$RFS/usr/bin/alkane-os"
|
||||
# The .afw version, reported by GET /api/identity (fleet discovery).
|
||||
printf '%s\n' "$VERSION" > "$RFS/etc/alkane-os-version"
|
||||
if [ -d "$OVERLAY" ]; then
|
||||
( cd "$OVERLAY" && find . -type f ) | while IFS= read -r f; do
|
||||
install -D -m 0755 "$OVERLAY/${f#./}" "$RFS/${f#./}"
|
||||
done
|
||||
fi
|
||||
( cd "$RFS" && find . | cpio -o -H newc --owner=0:0 --quiet | gzip -9 > "$WORK/in/rootfs.cpio.gz" )
|
||||
PACK
|
||||
fakeroot -- bash "$WORK/pack.sh" "$WORK/rootfs" "$SDK_OUT" "$WORK" "$ROOT/image/overlay" "$VERSION"
|
||||
|
||||
cp "$SDK_OUT/zImage" "$WORK/in/zImage"
|
||||
cp "$SDK_OUT/zynq-alkane.dtb" "$WORK/in/zynq-alkane.dtb"
|
||||
|
||||
echo "packaging the .afw"
|
||||
"$ROOT/ci/make-afw.sh" \
|
||||
--board zynq-7010 \
|
||||
--version "$VERSION" \
|
||||
--input "$WORK/in" \
|
||||
--sdk-dir "$SDK_DIR" \
|
||||
--os-revision "$(git -C "$ROOT" rev-parse HEAD)" \
|
||||
--output "$ROOT/dist" \
|
||||
--allow-unsigned
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
# S60alkane-web: serve the Alkane console and HTTP API.
|
||||
#
|
||||
# Starts after the network (S40). `alkane-os --serve` brings up the web console
|
||||
# (gated on a login) and the read-only JSON API on port 80, falling back to 8080
|
||||
# without privilege. The board HAL/mining backend is started separately; this
|
||||
# only needs the box to be reachable and observable, so every page renders and
|
||||
# the console works before any hashboard is driven.
|
||||
#
|
||||
# This file is part of the alkane-os image overlay (image/overlay), dropped into
|
||||
# the SDK rootfs at build time. It is intentionally not in the SDK's own init,
|
||||
# which owns board-detect / network / ssh and leaves the console to alkane-os.
|
||||
|
||||
PIDFILE=/run/alkane-web.pid
|
||||
BIN=/usr/bin/alkane-os
|
||||
|
||||
start() {
|
||||
[ -x "$BIN" ] || { echo "alkane-web: $BIN missing"; exit 1; }
|
||||
echo "alkane-web: starting console on :80 (falls back to :8080)"
|
||||
start-stop-daemon -S -b -m -p "$PIDFILE" -x "$BIN" -- --serve
|
||||
}
|
||||
|
||||
stop() {
|
||||
echo "alkane-web: stopping console"
|
||||
start-stop-daemon -K -q -p "$PIDFILE" 2>/dev/null
|
||||
rm -f "$PIDFILE"
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
restart) stop; start ;;
|
||||
*) echo "usage: $0 {start|stop|restart}"; exit 1 ;;
|
||||
esac
|
||||
@@ -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 +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 |
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"profiles": [
|
||||
{
|
||||
"name": "s19jpro-bm1362-pic",
|
||||
"chip": "bm1362",
|
||||
"sensor": "pic",
|
||||
"chains": 3,
|
||||
"envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700}
|
||||
},
|
||||
{
|
||||
"name": "s19kpro-bm1366-nopic",
|
||||
"chip": "bm1366",
|
||||
"sensor": "nopic",
|
||||
"chains": 3,
|
||||
"envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
{
|
||||
"format": 1,
|
||||
"id": "alkane.bb",
|
||||
"kind": "base",
|
||||
"menus": [
|
||||
{
|
||||
"id": "dashboard",
|
||||
"slug": "dashboard",
|
||||
"title": "Dashboard",
|
||||
"icon": "dashboard",
|
||||
"band": 0,
|
||||
"order": 10
|
||||
},
|
||||
{
|
||||
"id": "dashboard/overview",
|
||||
"slug": "overview",
|
||||
"title": "Overview",
|
||||
"order": 10,
|
||||
"page": "dashboard.overview"
|
||||
},
|
||||
{
|
||||
"id": "dashboard/alerts",
|
||||
"slug": "alerts",
|
||||
"title": "Alerts",
|
||||
"order": 20,
|
||||
"page": "dashboard.alerts"
|
||||
},
|
||||
{
|
||||
"id": "mining",
|
||||
"slug": "mining",
|
||||
"title": "Mining",
|
||||
"icon": "pickaxe",
|
||||
"band": 1,
|
||||
"order": 10
|
||||
},
|
||||
{
|
||||
"id": "mining/overview",
|
||||
"slug": "overview",
|
||||
"title": "Overview",
|
||||
"order": 10,
|
||||
"page": "mining.overview"
|
||||
},
|
||||
{
|
||||
"id": "mining/hashboards",
|
||||
"slug": "hashboards",
|
||||
"title": "Hashboards",
|
||||
"order": 20,
|
||||
"page": "mining.hashboards"
|
||||
},
|
||||
{
|
||||
"id": "mining/power",
|
||||
"slug": "power",
|
||||
"title": "Power Supply",
|
||||
"order": 30,
|
||||
"page": "mining.power"
|
||||
},
|
||||
{
|
||||
"id": "mining/fans",
|
||||
"slug": "fans",
|
||||
"title": "Fans",
|
||||
"order": 40,
|
||||
"page": "mining.fans"
|
||||
},
|
||||
{
|
||||
"id": "settings",
|
||||
"slug": "settings",
|
||||
"title": "Settings",
|
||||
"icon": "gear",
|
||||
"band": 2,
|
||||
"order": 10
|
||||
},
|
||||
{
|
||||
"id": "settings/system",
|
||||
"slug": "system",
|
||||
"title": "System",
|
||||
"order": 10,
|
||||
"page": "settings.system"
|
||||
},
|
||||
{
|
||||
"id": "settings/tuning",
|
||||
"slug": "tuning",
|
||||
"title": "Tuning",
|
||||
"order": 20,
|
||||
"page": "settings.tuning"
|
||||
},
|
||||
{
|
||||
"id": "settings/pools",
|
||||
"slug": "pools",
|
||||
"title": "Pools",
|
||||
"order": 30,
|
||||
"page": "settings.pools"
|
||||
},
|
||||
{
|
||||
"id": "settings/network",
|
||||
"slug": "network",
|
||||
"title": "Network",
|
||||
"order": 40,
|
||||
"page": "settings.network"
|
||||
},
|
||||
{
|
||||
"id": "settings/security",
|
||||
"slug": "security",
|
||||
"title": "Security",
|
||||
"order": 50,
|
||||
"page": "settings.security"
|
||||
},
|
||||
{
|
||||
"id": "settings/logs",
|
||||
"slug": "logs",
|
||||
"title": "Logs",
|
||||
"order": 60,
|
||||
"page": "settings.logs"
|
||||
},
|
||||
{
|
||||
"id": "settings/drivers",
|
||||
"slug": "drivers",
|
||||
"title": "Drivers",
|
||||
"order": 50,
|
||||
"page": "settings.drivers"
|
||||
},
|
||||
{
|
||||
"id": "settings/services",
|
||||
"slug": "services",
|
||||
"title": "Services",
|
||||
"order": 70,
|
||||
"page": "settings.services"
|
||||
},
|
||||
{
|
||||
"id": "settings/monitor",
|
||||
"slug": "monitor",
|
||||
"title": "Monitor",
|
||||
"order": 80,
|
||||
"page": "settings.monitor"
|
||||
},
|
||||
{
|
||||
"id": "settings/files",
|
||||
"slug": "files",
|
||||
"title": "Files",
|
||||
"order": 70,
|
||||
"page": "settings.files"
|
||||
},
|
||||
{
|
||||
"id": "settings/terminal",
|
||||
"slug": "terminal",
|
||||
"title": "Terminal",
|
||||
"order": 80,
|
||||
"page": "settings.terminal"
|
||||
}
|
||||
],
|
||||
"pages": [],
|
||||
"settings": [
|
||||
{
|
||||
"path": "tuning.mode",
|
||||
"label": "Tuning target",
|
||||
"help": "What the controller holds: a power draw, a hashrate, an ambient margin, or a fan ceiling.",
|
||||
"kind": {
|
||||
"t": "enum",
|
||||
"values": [
|
||||
{
|
||||
"v": "power",
|
||||
"label": "Power"
|
||||
},
|
||||
{
|
||||
"v": "hashrate",
|
||||
"label": "Hashrate"
|
||||
},
|
||||
{
|
||||
"v": "ambient",
|
||||
"label": "Ambient"
|
||||
},
|
||||
{
|
||||
"v": "max-fan",
|
||||
"label": "Max Fan"
|
||||
}
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"value": "power"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "dropdown"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.power_w",
|
||||
"label": "Power target",
|
||||
"help": "DC power to hold when the target is power.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 200,
|
||||
"hi": 4000,
|
||||
"units": "W"
|
||||
},
|
||||
"default": {
|
||||
"value": 1200
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.hashrate_ths",
|
||||
"label": "Hashrate target",
|
||||
"help": "Hashrate to maximise up to, when the target is hashrate.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 200,
|
||||
"units": "TH/s"
|
||||
},
|
||||
"default": {
|
||||
"value": 60
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 30,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.ambient_margin_c",
|
||||
"label": "Ambient margin",
|
||||
"help": "Hold the hottest sensor this far above measured ambient.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 40,
|
||||
"units": "C"
|
||||
},
|
||||
"default": {
|
||||
"value": 20
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 40,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.max_fan_pwm",
|
||||
"label": "Fan ceiling",
|
||||
"help": "Fan duty cap, percent, when the target is max-fan.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 100,
|
||||
"units": "%"
|
||||
},
|
||||
"default": {
|
||||
"value": 80
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 50,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.ceiling_mc",
|
||||
"label": "Frequency ceiling",
|
||||
"help": "Upper bound on the operating frequency, MHz.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 100,
|
||||
"hi": 1000,
|
||||
"units": "MHz"
|
||||
},
|
||||
"default": {
|
||||
"value": 700
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 60,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.kp_milli",
|
||||
"label": "Proportional gain",
|
||||
"help": "PID proportional term, thousandths of a unit.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 500
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 100,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.ki_milli",
|
||||
"label": "Integral gain",
|
||||
"help": "PID integral term, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 100
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 110,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.kd_milli",
|
||||
"label": "Derivative gain",
|
||||
"help": "PID derivative term, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 0
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 120,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.out_min_milli",
|
||||
"label": "Output floor",
|
||||
"help": "Lowest control output the loop may emit, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 1000000
|
||||
},
|
||||
"default": {
|
||||
"value": 0
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 130,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.out_max_milli",
|
||||
"label": "Output ceiling",
|
||||
"help": "Highest control output the loop may emit, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 5000000
|
||||
},
|
||||
"default": {
|
||||
"value": 1000000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 140,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.max_step_milli",
|
||||
"label": "Maximum step",
|
||||
"help": "Largest output change per second, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 500000
|
||||
},
|
||||
"default": {
|
||||
"value": 50000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 150,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.deadband_milli",
|
||||
"label": "Deadband",
|
||||
"help": "Errors inside this band are ignored, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 50000
|
||||
},
|
||||
"default": {
|
||||
"value": 1000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 160,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.zone_count",
|
||||
"label": "Fan zones",
|
||||
"help": "Number of independently driven fan zones.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 8
|
||||
},
|
||||
"default": {
|
||||
"value": 4
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.pwm_min",
|
||||
"label": "Minimum duty",
|
||||
"help": "Duty floor applied to every zone, percent.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 100,
|
||||
"units": "%"
|
||||
},
|
||||
"default": {
|
||||
"value": 20
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.sweep_steps",
|
||||
"label": "Sweep steps",
|
||||
"help": "Steps per zone when mapping fans to sensors.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 32
|
||||
},
|
||||
"default": {
|
||||
"value": 8
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 30,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "detect.chain_ports",
|
||||
"label": "Chain ports",
|
||||
"help": "Chain UART ports to probe, comma separated.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "1,2,3"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "detect",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "list"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "detect.probe_budget",
|
||||
"label": "Probe budget",
|
||||
"help": "Attempts per chain before detection gives up.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 20
|
||||
},
|
||||
"default": {
|
||||
"value": 3
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "detect",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "profiles.db",
|
||||
"label": "Profile database",
|
||||
"help": "Path to the board's tuning profile database.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "/etc/alkane/profiles.json"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "system",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "text"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "system.name",
|
||||
"label": "Board name",
|
||||
"help": "Name shown in the dashboard header.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "alkane"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "system",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "text"
|
||||
}
|
||||
}
|
||||
],
|
||||
"groups": [],
|
||||
"actions": [],
|
||||
"rules": [],
|
||||
"maps": [],
|
||||
"legacy_keys": [],
|
||||
"requires": {
|
||||
"display_api": 1,
|
||||
"checks_api": 1
|
||||
},
|
||||
"vocab": []
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Process wiring: start the API and UI servers and publish the hardware snapshot.
|
||||
//!
|
||||
//! The binary and the tests use the same function, so the wiring that CI exercises is the wiring
|
||||
//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover
|
||||
//! ephemeral ports instead of guessing them.
|
||||
|
||||
use crate::bus::Bus;
|
||||
use crate::detect::{
|
||||
run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget,
|
||||
SensorTopology,
|
||||
};
|
||||
use crate::fanmap::{FanMap, MapThresholds, SweepConfig};
|
||||
use crate::fanmap_store::ensure_map;
|
||||
use crate::fault::FaultPolicy;
|
||||
use crate::hal_wire::{HalClient, HalError};
|
||||
use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus};
|
||||
use crate::profiles::{ProfileDb, ProfileError};
|
||||
use crate::runtime::MinerRuntime;
|
||||
use crate::tuning::{PidConfig, TuningTarget};
|
||||
use crate::web;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Bound servers and their worker threads.
|
||||
pub struct Servers {
|
||||
pub api: Option<SocketAddr>,
|
||||
pub web: Option<SocketAddr>,
|
||||
handles: Vec<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Servers {
|
||||
/// Addresses actually bound, which matters when port 0 was requested.
|
||||
pub fn addresses(&self) -> (Option<SocketAddr>, Option<SocketAddr>) {
|
||||
(self.api, self.web)
|
||||
}
|
||||
|
||||
/// Wait for the workers. Only useful in tests; the binary runs until it is killed.
|
||||
pub fn join(self) {
|
||||
for handle in self.handles {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind and start the cgminer-style API and the web UI, each when an address is given.
|
||||
pub fn start(
|
||||
status: Arc<MiningStatus>,
|
||||
api: Option<SocketAddr>,
|
||||
web_bind: Option<SocketAddr>,
|
||||
bus: Arc<Bus>,
|
||||
) -> io::Result<Servers> {
|
||||
let api_listener = match api {
|
||||
Some(address) => Some(bind_local(address)?),
|
||||
None => None,
|
||||
};
|
||||
let api_address = api_listener
|
||||
.as_ref()
|
||||
.map(|listener| listener.local_addr())
|
||||
.transpose()?;
|
||||
let web_listener = match web_bind {
|
||||
Some(address) => Some(TcpListener::bind(address)?),
|
||||
None => None,
|
||||
};
|
||||
let web_address = web_listener
|
||||
.as_ref()
|
||||
.map(|listener| listener.local_addr())
|
||||
.transpose()?;
|
||||
|
||||
let mut handles = Vec::new();
|
||||
if let Some(listener) = api_listener {
|
||||
let snapshot = Arc::clone(&status);
|
||||
handles.push(std::thread::spawn(move || {
|
||||
if let Err(error) = serve(listener, snapshot) {
|
||||
eprintln!("management API stopped: {error}");
|
||||
}
|
||||
}));
|
||||
}
|
||||
if let Some(listener) = web_listener {
|
||||
let ctx = web::WebContext::new(Arc::clone(&bus));
|
||||
handles.push(std::thread::spawn(move || {
|
||||
if let Err(error) = web::serve_listener(listener, ctx) {
|
||||
eprintln!("web UI stopped: {error}");
|
||||
}
|
||||
}));
|
||||
}
|
||||
Ok(Servers {
|
||||
api: api_address,
|
||||
web: web_address,
|
||||
handles,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the API snapshot from the live runtime.
|
||||
pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot {
|
||||
let plan = runtime.plan();
|
||||
HardwareSnapshot {
|
||||
plan: plan.clone(),
|
||||
active_chains: runtime.active_chains(),
|
||||
stopped: runtime.stop_reason().map(|reason| match reason {
|
||||
crate::fault::StopReason::Temperature => "temperature",
|
||||
crate::fault::StopReason::NoChainsLeft => "no chains left",
|
||||
}),
|
||||
frequency_mhz: runtime.operating_point().frequency_mhz,
|
||||
target: target.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything a boot needs besides the backend.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BootConfig {
|
||||
pub profile_db_json: String,
|
||||
pub chain_ports: Vec<u8>,
|
||||
pub sensor: SensorTopology,
|
||||
pub budget: ProbeBudget,
|
||||
pub fan_zones: Vec<FanZone>,
|
||||
pub target: TuningTarget,
|
||||
pub pid: PidConfig,
|
||||
pub ceiling_mc: i32,
|
||||
pub fault_policy: FaultPolicy,
|
||||
}
|
||||
|
||||
/// Why boot did not reach a running runtime.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum BootError<E> {
|
||||
Profile(ProfileError),
|
||||
Detection(DetectionFailure<E>),
|
||||
/// The board backend could not be reached or refused an operation.
|
||||
Backend(E),
|
||||
}
|
||||
|
||||
impl<E: fmt::Debug> fmt::Display for BootError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Profile(error) => write!(f, "profile database rejected: {error:?}"),
|
||||
Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"),
|
||||
Self::Backend(error) => write!(f, "hardware backend failed: {error:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Debug> std::error::Error for BootError<E> {}
|
||||
|
||||
/// Operator target in the form the API and UI report.
|
||||
pub fn target_label(target: &TuningTarget) -> String {
|
||||
match *target {
|
||||
TuningTarget::PowerW(watts) => format!("power:{watts:.0}"),
|
||||
TuningTarget::HashrateThs(rate) => format!("hashrate:{rate:.0}"),
|
||||
TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"),
|
||||
TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect, decide, and publish: the sequence a family image runs at start-up.
|
||||
pub fn boot<B: DetectionBackend>(
|
||||
backend: &mut B,
|
||||
config: &BootConfig,
|
||||
status: &MiningStatus,
|
||||
) -> Result<MinerRuntime, BootError<B::Error>> {
|
||||
let db = ProfileDb::from_json(&config.profile_db_json).map_err(BootError::Profile)?;
|
||||
let request = DetectionRequest {
|
||||
chain_ports: &config.chain_ports,
|
||||
budget: config.budget,
|
||||
sensor: config.sensor,
|
||||
fan_zones: config.fan_zones.clone(),
|
||||
};
|
||||
let plan = run_detection(backend, &db, &request).map_err(BootError::Detection)?;
|
||||
let runtime = MinerRuntime::new(
|
||||
plan,
|
||||
config.fault_policy,
|
||||
config.target,
|
||||
config.pid,
|
||||
config.ceiling_mc,
|
||||
);
|
||||
status.set_hardware(snapshot(&runtime, &target_label(&config.target)));
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
/// A boot over the real local HAL contract, including the one-time fan sweep.
|
||||
pub struct HalBoot<'a> {
|
||||
pub config: &'a BootConfig,
|
||||
pub sweep: SweepConfig,
|
||||
pub thresholds: MapThresholds,
|
||||
pub map_path: &'a Path,
|
||||
}
|
||||
|
||||
/// Connect the board backend, detect, map the fans once, and publish.
|
||||
///
|
||||
/// This is the path an image takes on real hardware; the fakes in the tests speak the same HAL
|
||||
/// protocol, so the wiring is exercised rather than assumed.
|
||||
pub fn boot_from_hal(
|
||||
socket: &Path,
|
||||
settings: &HalBoot<'_>,
|
||||
status: &MiningStatus,
|
||||
) -> Result<(MinerRuntime, FanMap), BootError<HalError>> {
|
||||
let mut client = HalClient::connect(socket).map_err(BootError::Backend)?;
|
||||
let zone_count = settings.sweep.zones;
|
||||
let map = if zone_count == 0 {
|
||||
FanMap::default()
|
||||
} else {
|
||||
ensure_map(
|
||||
&mut client,
|
||||
&settings.sweep,
|
||||
settings.thresholds,
|
||||
settings.map_path,
|
||||
|millis| std::thread::sleep(std::time::Duration::from_millis(u64::from(millis))),
|
||||
)
|
||||
.map_err(|error| match error {
|
||||
crate::fanmap_store::StoreError::Sweep(crate::fanmap::SweepError::Backend(error)) => {
|
||||
BootError::Backend(error)
|
||||
}
|
||||
crate::fanmap_store::StoreError::Sweep(_) => {
|
||||
BootError::Backend(HalError::Protocol("fan sweep configuration rejected"))
|
||||
}
|
||||
crate::fanmap_store::StoreError::Io(message) => {
|
||||
BootError::Backend(HalError::Protocol(message))
|
||||
}
|
||||
})?
|
||||
};
|
||||
let config = BootConfig {
|
||||
fan_zones: map.assignments.clone(),
|
||||
..settings.config.clone()
|
||||
};
|
||||
let runtime = boot(&mut client, &config, status)?;
|
||||
Ok((runtime, map))
|
||||
}
|
||||
|
||||
/// Read one HTTP response body from a bound server, for health checks and tests.
|
||||
pub fn http_get(address: SocketAddr, path: &str) -> io::Result<String> {
|
||||
use std::io::{Read, Write};
|
||||
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())?;
|
||||
let mut reply = String::new();
|
||||
stream.read_to_string(&mut reply)?;
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::detect::{
|
||||
ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint,
|
||||
};
|
||||
use crate::detect::{ProbeOutcome, PsuCapability};
|
||||
use crate::fanmap::{MapThresholds, SweepConfig};
|
||||
use crate::fault::FaultPolicy;
|
||||
use crate::tuning::{PidConfig, TuningTarget};
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn runtime() -> MinerRuntime {
|
||||
MinerRuntime::new(
|
||||
HardwarePlan {
|
||||
profile: "s19jpro-bm1362-pic".into(),
|
||||
chip: ChipModel::Bm1362,
|
||||
chains: vec![ChainReport {
|
||||
index: 0,
|
||||
chip: ChipModel::Bm1362,
|
||||
chips_found: 126,
|
||||
eeprom: EepromState::Absent,
|
||||
response_per_mille: Some(950),
|
||||
}],
|
||||
envelope: Envelope {
|
||||
v_min_mv: 1100,
|
||||
v_max_mv: 1500,
|
||||
f_min_mhz: 300,
|
||||
f_max_mhz: 700,
|
||||
},
|
||||
operating_point: OperatingPoint {
|
||||
voltage_mv: 1200,
|
||||
frequency_mhz: 300,
|
||||
confirmed: false,
|
||||
},
|
||||
psu: "APW12".into(),
|
||||
fan_zones: vec![FanZone {
|
||||
fan: 0,
|
||||
zones: vec![0],
|
||||
}],
|
||||
},
|
||||
FaultPolicy::default(),
|
||||
TuningTarget::PowerW(2_400.0),
|
||||
PidConfig::default(),
|
||||
95_000,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_servers_serve_the_published_snapshot() {
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
status.set_hardware(snapshot(&runtime(), "power:2400"));
|
||||
let bus = crate::bus::Bus::new();
|
||||
let control = Arc::new(crate::control::Control::default());
|
||||
crate::service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
crate::service::publish(&bus, &status, &control);
|
||||
let servers = start(
|
||||
Arc::clone(&status),
|
||||
Some("127.0.0.1:0".parse().unwrap()),
|
||||
Some("127.0.0.1:0".parse().unwrap()),
|
||||
bus,
|
||||
)
|
||||
.expect("start");
|
||||
let (api, web) = servers.addresses();
|
||||
let api = api.expect("api address");
|
||||
let web = web.expect("web address");
|
||||
|
||||
let page = http_get(web, "/api/hardware").expect("web");
|
||||
assert!(page.contains("s19jpro-bm1362-pic"));
|
||||
assert!(page.contains("power:2400"));
|
||||
|
||||
let mut client =
|
||||
TcpStream::connect_timeout(&api, Duration::from_secs(2)).expect("api connect");
|
||||
client
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("timeout");
|
||||
client.write_all(b"summary").expect("api write");
|
||||
let mut summary = String::new();
|
||||
client.read_to_string(&mut summary).expect("api read");
|
||||
assert!(summary.contains("SUMMARY"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_are_optional() {
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
let servers = start(status, None, None, crate::bus::Bus::new()).expect("start");
|
||||
assert_eq!(servers.addresses(), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snapshot_reports_runtime_state_not_boot_defaults() {
|
||||
let mut runtime = runtime();
|
||||
runtime.tick(&crate::runtime::Tick {
|
||||
power_w: Some(1_000.0),
|
||||
hashrate_ths: None,
|
||||
hottest_mc: Some(60_000),
|
||||
ambient_mc: None,
|
||||
dt_s: 1.0,
|
||||
});
|
||||
let snapshot = snapshot(&runtime, "power:2400");
|
||||
assert_eq!(snapshot.target, "power:2400");
|
||||
assert_eq!(snapshot.active_chains, vec![0]);
|
||||
assert!(snapshot.frequency_mhz > 300);
|
||||
assert!(snapshot.stopped.is_none());
|
||||
}
|
||||
|
||||
struct BootBackend {
|
||||
outcome: ProbeOutcome,
|
||||
psu: Option<PsuCapability>,
|
||||
}
|
||||
|
||||
impl DetectionBackend for BootBackend {
|
||||
type Error = ();
|
||||
|
||||
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
|
||||
Ok(self.outcome)
|
||||
}
|
||||
|
||||
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
|
||||
Ok(EepromState::Absent)
|
||||
}
|
||||
|
||||
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
|
||||
Ok(self.psu.clone())
|
||||
}
|
||||
}
|
||||
|
||||
const DB: &str = r#"{"schema":1,"profiles":[{"name":"s19jpro-bm1362-pic",
|
||||
"chip":"bm1362","sensor":"pic","chains":3,
|
||||
"envelope":{"v_min_mv":1100,"v_max_mv":1500,"f_min_mhz":300,"f_max_mhz":700}}]}"#;
|
||||
|
||||
fn boot_config() -> BootConfig {
|
||||
BootConfig {
|
||||
profile_db_json: DB.into(),
|
||||
chain_ports: vec![0, 1, 2],
|
||||
sensor: SensorTopology::Pic,
|
||||
budget: ProbeBudget::default(),
|
||||
fan_zones: Vec::new(),
|
||||
target: TuningTarget::PowerW(2_400.0),
|
||||
pid: PidConfig::default(),
|
||||
ceiling_mc: 95_000,
|
||||
fault_policy: FaultPolicy::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn psu() -> PsuCapability {
|
||||
PsuCapability {
|
||||
name: "APW12".into(),
|
||||
envelope: Envelope {
|
||||
v_min_mv: 1200,
|
||||
v_max_mv: 1600,
|
||||
f_min_mhz: 0,
|
||||
f_max_mhz: 1_000,
|
||||
},
|
||||
max_dc_watts: 3_600,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_detects_and_publishes() {
|
||||
let mut backend = BootBackend {
|
||||
outcome: ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
psu: Some(psu()),
|
||||
};
|
||||
let status = MiningStatus::new();
|
||||
let runtime = boot(&mut backend, &boot_config(), &status).expect("boot");
|
||||
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
|
||||
let document = status.hardware_document();
|
||||
assert_eq!(document["available"], true);
|
||||
assert_eq!(document["target"], "power:2400");
|
||||
assert_eq!(document["psu"], "APW12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_refuses_an_unknown_chip() {
|
||||
let mut backend = BootBackend {
|
||||
outcome: ProbeOutcome::Silent,
|
||||
psu: Some(psu()),
|
||||
};
|
||||
let status = MiningStatus::new();
|
||||
assert!(matches!(
|
||||
boot(&mut backend, &boot_config(), &status),
|
||||
Err(BootError::Detection(DetectionFailure::Refused(_)))
|
||||
));
|
||||
assert_eq!(status.hardware_document()["available"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_refuses_a_bad_profile_database() {
|
||||
let mut backend = BootBackend {
|
||||
outcome: ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
psu: Some(psu()),
|
||||
};
|
||||
let mut config = boot_config();
|
||||
config.profile_db_json = "{\"schema\": 9}".into();
|
||||
assert!(matches!(
|
||||
boot(&mut backend, &config, &MiningStatus::new()),
|
||||
Err(BootError::Profile(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_refuses_a_missing_psu() {
|
||||
let mut backend = BootBackend {
|
||||
outcome: ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
psu: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
boot(&mut backend, &boot_config(), &MiningStatus::new()),
|
||||
Err(BootError::Detection(DetectionFailure::Refused(_)))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_labels_are_stable() {
|
||||
assert_eq!(target_label(&TuningTarget::PowerW(3_000.0)), "power:3000");
|
||||
assert_eq!(
|
||||
target_label(&TuningTarget::HashrateThs(200.0)),
|
||||
"hashrate:200"
|
||||
);
|
||||
assert_eq!(
|
||||
target_label(&TuningTarget::AmbientC { margin_mc: 20_000 }),
|
||||
"ambient:20000"
|
||||
);
|
||||
assert_eq!(
|
||||
target_label(&TuningTarget::MaxFan { max_pwm: 100 }),
|
||||
"fan:100"
|
||||
);
|
||||
}
|
||||
|
||||
fn hal_server(socket: std::path::PathBuf) -> std::thread::JoinHandle<()> {
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::net::UnixListener;
|
||||
let listener = UnixListener::bind(&socket).expect("bind hal");
|
||||
std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept");
|
||||
loop {
|
||||
let mut header = [0_u8; 16];
|
||||
if stream.read_exact(&mut header).is_err() {
|
||||
return;
|
||||
}
|
||||
let opcode = header[5];
|
||||
let sequence = header[8..12].to_vec();
|
||||
let length =
|
||||
u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
|
||||
let mut payload = vec![0_u8; length];
|
||||
if length > 0 && stream.read_exact(&mut payload).is_err() {
|
||||
return;
|
||||
}
|
||||
let body: Vec<u8> = match opcode {
|
||||
// CAPABILITIES: chain probe, EEPROM, PSU identity.
|
||||
7 => {
|
||||
let mut body = vec![0_u8];
|
||||
body.extend_from_slice(&7_u32.to_le_bytes());
|
||||
body
|
||||
}
|
||||
// PROBE_CHAIN: identified, bm1362, 126 chips.
|
||||
8 => vec![0, 0, 1, 126, 0],
|
||||
// READ_EEPROM: absent.
|
||||
9 => vec![0, 1],
|
||||
// IDENTIFY_PSU: APW12 with its envelope.
|
||||
10 => {
|
||||
let name = b"APW12";
|
||||
let mut body = vec![0_u8, name.len() as u8];
|
||||
body.extend_from_slice(name);
|
||||
for word in [1200_u16, 1600, 0, 1000, 3600] {
|
||||
body.extend_from_slice(&word.to_le_bytes());
|
||||
}
|
||||
body
|
||||
}
|
||||
_ => vec![1],
|
||||
};
|
||||
let mut out = [0_u8; 16];
|
||||
out[..4].copy_from_slice(b"ALKH");
|
||||
out[4] = 1;
|
||||
out[5] = opcode;
|
||||
out[6..8].copy_from_slice(&1_u16.to_le_bytes());
|
||||
out[8..12].copy_from_slice(&sequence);
|
||||
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
if stream.write_all(&out).is_err() || stream.write_all(&body).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_over_the_hal_socket_detects_and_publishes() {
|
||||
let base = std::env::temp_dir().join(format!("alkane-hal-{}", std::process::id()));
|
||||
let socket = base.with_extension("sock");
|
||||
let map_path = base.with_extension("map.json");
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
let server = hal_server(socket.clone());
|
||||
let status = MiningStatus::new();
|
||||
let config = boot_config();
|
||||
let settings = HalBoot {
|
||||
config: &config,
|
||||
sweep: SweepConfig {
|
||||
fans: 0,
|
||||
zones: 0,
|
||||
low_pwm: 40,
|
||||
high_pwm: 100,
|
||||
repeats: 1,
|
||||
settle_ms: 0,
|
||||
},
|
||||
thresholds: MapThresholds::default(),
|
||||
map_path: &map_path,
|
||||
};
|
||||
let (runtime, map) = boot_from_hal(&socket, &settings, &status).expect("boot over hal");
|
||||
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
|
||||
assert!(map.assignments.is_empty());
|
||||
let document = status.hardware_document();
|
||||
assert_eq!(document["available"], true);
|
||||
assert_eq!(document["psu"], "APW12");
|
||||
assert_eq!(document["chip"], "bm1362");
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
let _ = server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_over_a_missing_socket_is_a_backend_error() {
|
||||
let socket =
|
||||
std::env::temp_dir().join(format!("alkane-missing-{}.sock", std::process::id()));
|
||||
let status = MiningStatus::new();
|
||||
let config = boot_config();
|
||||
let settings = HalBoot {
|
||||
config: &config,
|
||||
sweep: SweepConfig {
|
||||
fans: 0,
|
||||
zones: 0,
|
||||
low_pwm: 40,
|
||||
high_pwm: 100,
|
||||
repeats: 1,
|
||||
settle_ms: 0,
|
||||
},
|
||||
thresholds: MapThresholds::default(),
|
||||
map_path: &socket,
|
||||
};
|
||||
assert!(matches!(
|
||||
boot_from_hal(&socket, &settings, &status),
|
||||
Err(BootError::Backend(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Web console authentication: a local account and session cookies.
|
||||
//!
|
||||
//! Modeled on wardenOS's web auth (spec d05): a local account whose password is
|
||||
//! stored only as a salted KDF hash, and a `wsid` session cookie issued on
|
||||
//! login. wardenOS uses Argon2 from its `warden-verifier` crate; alkane-os is
|
||||
//! dependency-light, so this uses PBKDF2-HMAC-SHA256 built on the crate's own
|
||||
//! pure-Rust SHA-256 (`pow::sha256`) - a standard password KDF with no new
|
||||
//! dependency. OIDC and FLARE bundle users are out of scope (no portal here).
|
||||
//!
|
||||
//! The box is guarded by SSH; this login is defense-in-depth for the console on
|
||||
//! a shared network, and the factory account is `admin` / `admin`, which the
|
||||
//! operator is expected to change.
|
||||
|
||||
use crate::pow::sha256;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// PBKDF2 iterations. A compromise for the crate's pure-Rust SHA-256: strong
|
||||
/// enough as defense-in-depth behind SSH, while a single login stays well under
|
||||
/// a second even on a slow control board.
|
||||
const PBKDF2_ITERS: u32 = 50_000;
|
||||
/// How long a session cookie stays valid.
|
||||
const SESSION_TTL: Duration = Duration::from_secs(12 * 3600);
|
||||
const AUTH_FILE: &str = "/etc/alkane/auth.json";
|
||||
|
||||
fn now_unix() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 16 bytes (32 hex) from the OS CSPRNG. The single random-token source for the
|
||||
/// console (CSRF token and session ids). If `/dev/urandom` is unreadable it
|
||||
/// fails LOUD and still avoids a fixed/guessable value: a per-call mix (nanos,
|
||||
/// pid, a process counter, a stack address) hashed through SHA-256, distinct on
|
||||
/// every call. Not a CSPRNG, but never the published constant it replaced.
|
||||
pub(crate) fn rand_hex() -> String {
|
||||
if let Ok(mut f) = fs::File::open("/dev/urandom") {
|
||||
let mut b = [0_u8; 16];
|
||||
if f.read_exact(&mut b).is_ok() {
|
||||
return hex(&b);
|
||||
}
|
||||
}
|
||||
static CTR: AtomicU64 = AtomicU64::new(0);
|
||||
eprintln!("alkane auth: WARNING /dev/urandom unreadable; session/token entropy is degraded");
|
||||
let n = CTR.fetch_add(1, Ordering::Relaxed);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let stack = &n as *const _ as u64;
|
||||
let mix = nanos
|
||||
^ (std::process::id() as u64).rotate_left(17)
|
||||
^ n.rotate_left(33)
|
||||
^ stack.rotate_left(49);
|
||||
hex(&sha256(&mix.to_le_bytes())[..16])
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
s.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.filter_map(|i| u8::from_str_radix(text.get(i * 2..i * 2 + 2)?, 16).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HMAC-SHA256 over the crate's SHA-256.
|
||||
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
|
||||
const BLOCK: usize = 64;
|
||||
let mut k = [0_u8; BLOCK];
|
||||
if key.len() > BLOCK {
|
||||
k[..32].copy_from_slice(&sha256(key));
|
||||
} else {
|
||||
k[..key.len()].copy_from_slice(key);
|
||||
}
|
||||
let mut ipad = [0x36_u8; BLOCK];
|
||||
let mut opad = [0x5c_u8; BLOCK];
|
||||
for i in 0..BLOCK {
|
||||
ipad[i] ^= k[i];
|
||||
opad[i] ^= k[i];
|
||||
}
|
||||
let mut inner = Vec::with_capacity(BLOCK + msg.len());
|
||||
inner.extend_from_slice(&ipad);
|
||||
inner.extend_from_slice(msg);
|
||||
let ih = sha256(&inner);
|
||||
let mut outer = Vec::with_capacity(BLOCK + 32);
|
||||
outer.extend_from_slice(&opad);
|
||||
outer.extend_from_slice(&ih);
|
||||
sha256(&outer)
|
||||
}
|
||||
|
||||
/// PBKDF2-HMAC-SHA256 producing one 32-byte block (dkLen == hLen).
|
||||
fn pbkdf2_sha256(password: &[u8], salt: &[u8], iters: u32) -> [u8; 32] {
|
||||
let mut block1 = salt.to_vec();
|
||||
block1.extend_from_slice(&1_u32.to_be_bytes());
|
||||
let mut u = hmac_sha256(password, &block1);
|
||||
let mut t = u;
|
||||
for _ in 1..iters.max(1) {
|
||||
u = hmac_sha256(password, &u);
|
||||
for i in 0..32 {
|
||||
t[i] ^= u[i];
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Constant-time comparison of two byte slices.
|
||||
pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0_u8;
|
||||
for i in 0..a.len() {
|
||||
diff |= a[i] ^ b[i];
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// The stored local account.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Account {
|
||||
user: String,
|
||||
salt: Vec<u8>,
|
||||
iters: u32,
|
||||
hash: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
fn factory() -> Self {
|
||||
Self::with_password("admin", "admin")
|
||||
}
|
||||
|
||||
fn with_password(user: &str, password: &str) -> Self {
|
||||
let salt = unhex(&rand_hex());
|
||||
let hash = pbkdf2_sha256(password.as_bytes(), &salt, PBKDF2_ITERS).to_vec();
|
||||
Self {
|
||||
user: user.to_string(),
|
||||
salt,
|
||||
iters: PBKDF2_ITERS,
|
||||
hash,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"user": self.user,
|
||||
"salt": hex(&self.salt),
|
||||
"iters": self.iters,
|
||||
"hash": hex(&self.hash),
|
||||
})
|
||||
}
|
||||
|
||||
fn from_json(v: &Value) -> Option<Self> {
|
||||
Some(Self {
|
||||
user: v.get("user")?.as_str()?.to_string(),
|
||||
salt: unhex(v.get("salt")?.as_str()?),
|
||||
iters: v.get("iters")?.as_u64()? as u32,
|
||||
hash: unhex(v.get("hash")?.as_str()?),
|
||||
})
|
||||
}
|
||||
|
||||
fn verify(&self, user: &str, password: &str) -> bool {
|
||||
let candidate = pbkdf2_sha256(password.as_bytes(), &self.salt, self.iters);
|
||||
// Compare the user name too, but not in constant time (it is not secret).
|
||||
user == self.user && ct_eq(&candidate, &self.hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// The console auth state: one local account and the live sessions.
|
||||
pub struct Auth {
|
||||
account: Account,
|
||||
sessions: Mutex<HashMap<String, u64>>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// Load the account from `AUTH_FILE`, creating the factory `admin`/`admin`
|
||||
/// account (persisted when the path is writable) on first run.
|
||||
pub fn load() -> Self {
|
||||
Self::load_from(Path::new(AUTH_FILE))
|
||||
}
|
||||
|
||||
pub fn load_from(path: &Path) -> Self {
|
||||
let account = fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.and_then(|v| Account::from_json(&v))
|
||||
.unwrap_or_else(|| {
|
||||
let account = Account::factory();
|
||||
persist(path, &account);
|
||||
account
|
||||
});
|
||||
Self {
|
||||
account,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
path: path.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a login. On success return a fresh `wsid`.
|
||||
pub fn login(&self, user: &str, password: &str) -> Option<String> {
|
||||
if !self.account.verify(user, password) {
|
||||
return None;
|
||||
}
|
||||
let wsid = rand_hex() + &rand_hex();
|
||||
// Only hand back a cookie if the session was actually recorded; a
|
||||
// poisoned lock must not mint a token that `valid` will always reject.
|
||||
match self.sessions.lock() {
|
||||
Ok(mut s) => {
|
||||
s.insert(wsid.clone(), now_unix() + SESSION_TTL.as_secs());
|
||||
Some(wsid)
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `wsid` names a live, unexpired session.
|
||||
pub fn valid(&self, wsid: &str) -> bool {
|
||||
if wsid.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let now = now_unix();
|
||||
let mut sessions = match self.sessions.lock() {
|
||||
Ok(s) => s,
|
||||
Err(_) => return false,
|
||||
};
|
||||
sessions.retain(|_, &mut exp| exp > now);
|
||||
sessions.get(wsid).is_some_and(|&exp| exp > now)
|
||||
}
|
||||
|
||||
/// End a session.
|
||||
pub fn logout(&self, wsid: &str) {
|
||||
if let Ok(mut s) = self.sessions.lock() {
|
||||
s.remove(wsid);
|
||||
}
|
||||
}
|
||||
|
||||
/// The path the account is stored at (for diagnostics).
|
||||
pub fn store_path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(path: &Path, account: &Account) {
|
||||
if let Some(parent) = path.parent() {
|
||||
if fs::create_dir_all(parent).is_err() {
|
||||
eprintln!(
|
||||
"alkane auth: cannot create {}; account not persisted",
|
||||
parent.display()
|
||||
);
|
||||
return;
|
||||
}
|
||||
let _ = fs::set_permissions(parent, fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
// The file holds the password hash: create it 0600, not umask-default.
|
||||
let text = serde_json::to_string_pretty(&account.to_json()).unwrap_or_default();
|
||||
match OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
{
|
||||
Ok(mut file) => {
|
||||
let _ = file.write_all(text.as_bytes());
|
||||
}
|
||||
Err(error) => eprintln!("alkane auth: cannot write {}: {error}", path.display()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hmac_matches_rfc4231_case_2() {
|
||||
// RFC 4231 test case 2: key "Jefe", data "what do ya want for nothing?".
|
||||
let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
|
||||
assert_eq!(
|
||||
hex(&mac),
|
||||
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pbkdf2_matches_a_known_vector() {
|
||||
// RFC 7914 / standard PBKDF2-HMAC-SHA256: P="passwd", S="salt", c=1.
|
||||
let dk = pbkdf2_sha256(b"passwd", b"salt", 1);
|
||||
assert_eq!(&hex(&dk)[..16], "55ac046e56e3089f");
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let mut p = std::env::temp_dir();
|
||||
p.push(format!("alkane-auth-{name}-{}.json", std::process::id()));
|
||||
let _ = fs::remove_file(&p);
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factory_account_accepts_admin_admin_and_rejects_others() {
|
||||
let auth = Auth::load_from(&temp("factory"));
|
||||
assert!(auth.login("admin", "admin").is_some());
|
||||
assert!(auth.login("admin", "wrong").is_none());
|
||||
assert!(auth.login("root", "admin").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_is_valid_until_logout() {
|
||||
let auth = Auth::load_from(&temp("session"));
|
||||
let wsid = auth.login("admin", "admin").expect("login");
|
||||
assert!(auth.valid(&wsid));
|
||||
assert!(!auth.valid("not-a-session"));
|
||||
auth.logout(&wsid);
|
||||
assert!(!auth.valid(&wsid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_account_persists_and_reloads() {
|
||||
let path = temp("persist");
|
||||
let _ = Auth::load_from(&path);
|
||||
assert!(path.exists(), "the factory account should be written");
|
||||
let again = Auth::load_from(&path);
|
||||
assert!(again.login("admin", "admin").is_some());
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Control for the size measurement: the same page shape rendered without
|
||||
//! flare-ui, so `check-ui-size.sh` reports the marginal cost of the dependency
|
||||
//! rather than the cost of a Rust binary at all.
|
||||
|
||||
fn main() {
|
||||
let sections = [
|
||||
("dashboard", "Dashboard"),
|
||||
("mining", "Mining"),
|
||||
("settings", "Settings"),
|
||||
];
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
p class="bf-text-body" { "Schema-driven page." }
|
||||
}
|
||||
};
|
||||
let mut html = String::from("<!doctype html><html><body>");
|
||||
for (slug, title) in sections {
|
||||
html.push_str(&format!("<a href=\"/{slug}\">{title}</a>"));
|
||||
}
|
||||
html.push_str(&body.into_string());
|
||||
html.push_str("</body></html>");
|
||||
println!(
|
||||
"{} {}",
|
||||
html.len(),
|
||||
serde_json::json!({"sections": sections.len()})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Spike: render the on-box UI from a schema document through flare-ui.
|
||||
//!
|
||||
//! This is the incorporation test, not the final UI. It answers three questions
|
||||
//! with evidence rather than argument:
|
||||
//!
|
||||
//! 1. does a hand-authored Alkane schema drive the unified sidebar through
|
||||
//! `flare_ui::nav` + `flare_ui::shell`?
|
||||
//! 2. does the page render with the shared design tokens?
|
||||
//! 3. what does it cost in a firmware binary?
|
||||
//!
|
||||
//! Run it, then compare `--size` against the current hand-rolled renderer.
|
||||
|
||||
use flare_ui::assets::PageAssets;
|
||||
use flare_ui::nav::{self, AllowAll, AppSet, CapSet};
|
||||
use flare_ui::shell::{self, Active};
|
||||
use flare_ui::url::Routes;
|
||||
use wschema::model::{Document, Surface};
|
||||
|
||||
/// The schema is the single source of the UI: sections, tabs and their order.
|
||||
const RECIPE_SCHEMA: &str = include_str!("../../schema/alkane-bb.json");
|
||||
|
||||
fn main() {
|
||||
let schema = match Document::from_json(RECIPE_SCHEMA) {
|
||||
Ok(schema) => schema,
|
||||
Err(error) => {
|
||||
eprintln!("schema did not parse: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Capabilities the board actually reports decide what is visible. On a real
|
||||
// board these come from the HAL; here they are the bb set.
|
||||
let caps = CapSet::new(["hashboard-bm1395", "psu-apm", "pid-fan", "cgminer-api"]);
|
||||
let routes = Routes::console();
|
||||
let apps = AppSet::default();
|
||||
let ctx = nav::NavContext {
|
||||
surface: Surface::Web,
|
||||
principal: &AllowAll,
|
||||
caps: &caps,
|
||||
apps: &apps,
|
||||
routes: &routes,
|
||||
};
|
||||
|
||||
let visible = nav::visible(&schema.menus, &ctx);
|
||||
let first = visible
|
||||
.first_tab()
|
||||
.map(|(section, tab)| Active { section, tab });
|
||||
let active = first.unwrap_or(Active {
|
||||
section: "",
|
||||
tab: "",
|
||||
});
|
||||
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
p class="bf-text-body" { "Schema-driven page. Sections and tabs above come from dashboard.json." }
|
||||
}
|
||||
};
|
||||
let assets = PageAssets::default();
|
||||
let page = shell::page("Alkane OS", &assets, &visible, active, body);
|
||||
let html = page.into_string();
|
||||
|
||||
if std::env::args().any(|arg| arg == "--size") {
|
||||
println!("html_bytes {}", html.len());
|
||||
println!("sections {}", visible.sections.len());
|
||||
for section in &visible.sections {
|
||||
println!(
|
||||
"section {} ({}) tabs={}",
|
||||
section.slug,
|
||||
section.title,
|
||||
section.tabs.len()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
println!("{html}");
|
||||
}
|
||||
}
|
||||