Compare commits

..
Author SHA1 Message Date
x 997771ab5e Wire the schema-driven dashboard and add the .afw firmware package
Dashboard (src/dashboard.rs): the on-box UI now renders from
schema/alkane-bb.json through flare-ui and wschema. The sidebar, the tab strip
and all 20 settings controls come from the schema; the host boundary does what
the crates require - validate the submitted batch with wschema before persisting,
ignore keys that are not in the schema, and never write on a rejected form.
Settings live in /etc/alkane/settings.json (temp dir when the root is read-only).

Web: GET /<section> and /<section>/<tab> render the dashboard, /assets/* serves
the crate's embedded token/component/theme stylesheets, POST /settings applies a
form. The existing JSON API routes are untouched.

Settings wired (all from real runtime knobs): tuning target mode and its four
values, frequency ceiling, the PID gains and limits in milli-units (the schema
has integer kinds only), fan zones/duty/sweep, detection ports and budget,
profile database path, board name.

Tests: 10 dashboard tests (schema loads, all settings present, page renders
inputs, valid submit persists and reloads, out-of-range rejected with nothing
written, unknown keys ignored, percent decoding) plus the existing 162. 172 pass.

Packaging (ci/make-afw.sh): .afw modelled on the Warden .wfw bundle - strict
POSIX ustar, manifest first, payload verified by size and sha256 - with three
deliberate differences: the payload is gzip-compressed, the manifest carries
 and x86_64, and both appear in the file name
(alkane-os-0.1.0-am335x-bb-armv7.afw) so a bundle cannot be mistaken for another
family. Signature is declared  in the manifest until a release key
exists; the sha256 is the only integrity claim today.
2026-11-04 14:06:25 -06:00
x ad31cfbafa Vendor flare-ui v0.2.9 and prove the schema-driven UI in an image
Spike, not the final UI: it answers whether flare-ui can drive Alkane OS's
on-box pages, and what it costs.

What works:

- schema/alkane-bb.json authors the sidebar as data (3 sections, 14 tabs);
- src/bin/ui-spike.rs renders it through flare_ui::nav + flare_ui::shell, so
  the unified sidebar, ordering and surface filtering come from the schema
  rather than from hand-written HTML;
- the render uses the shared bf- design tokens, the same ones the rest of the
  suite uses.

Size, measured rather than assumed (armv7, release, stripped):

  ui-baseline   323 KiB   (maud + serde_json, no flare-ui)
  ui-spike      771 KiB   (flare-ui + wschema + sha2)
  marginal      448 KiB

Vendoring: third-party/flare-ui is the full v0.2.9 tree pinned in
flare-ui/flare-ui.lock (a partial archive does not compile, since the crate
include_str!s assets from dash-editor/). vendor/ is re-generated as a cargo
directory source with the new registry dependencies (maud, sha2, typenum,
digest, generic-array, block-buffer, crypto-common, cfg-if, etc.) so the build
still works offline. third-party/README.md records how to re-pin.
2026-11-04 14:06:25 -06:00
noah 67a33b8221 Gate the OS image payloads against the formats a board can actually boot
The SDK refuses a bad payload before writing it; this is the same rule on the
producing side, so a release cannot ship an image that would not boot or would
not fit the partition it targets.

Checks every payload artefact it can find: magic must match the claimed format
(FDT d00dfeed, legacy uImage 27051956, raw ARM zImage 016f2818 at 0x24) and the
size must fit the partition. Absent artefacts pass with a note, so the gate can
be wired before the first image exists.

Proven both ways: it accepts the four payload files that actually installed
OurOS, and rejects a zImage renamed to the ramdisk slot on size.
2026-11-04 14:06:24 -06:00
noah 13b1787e1a Square corners, a full-screen mobile drawer, and populated settings
The design system retired every radius step on 2026-07-14 (tokens/radius.json
resolves xs..pill to 0), so the cards, buttons, inputs, pills and code blocks
lose their rounded corners.

Below 901px the rail is now the design's mobile menu: a full-screen drawer on
the page background with the brand and a close control in its head, rows split
by 1px dividers. It closes by the X, the backdrop, Escape, or picking a
destination; without a script the :target fragment still opens it.

Settings stops being a bare list: System now groups Identity, Network and
Updates the way the Warden console does, and Drivers groups Chains and
Firmware. Verified on the bench S21 Pro at port 80.
2026-11-04 14:06:24 -06:00
noah 5a6b895113 Style the UI on the FLARE unified rail
Follows the rebuild's design rather than inventing a palette: the 232px navy
rail from portal.css (#192858), its 44px head and appbar, cyan-400 for the
current page and its 2px left marker, 18px stroke icons, 11px uppercase
headings with 2px tracking, and the navy surface/border steps from tokens.css.

Behaviour comes from the same place: one native <details> per group so the tree
opens without a script and the current page's path renders open, a one-item
group rendered as a plain link, aria-current instead of a class, inward focus
rings because the rail scrolls, and an off-canvas rail below 901px reopened by
a :target fragment. A collapse toggle shrinks it to the 40px icon cell and
remembers the choice.

Verified on the bench S21 Pro: the page on port 80 renders the rail with icons
and the open Mining section.
2026-11-04 14:06:24 -06:00
noah 93c47d90ef Add the on-box web UI: sidebar, editable dashboards, settings pages
The UI follows the Warden/FLARE console shape rather than inventing one: a
fixed sidebar of groups and items, hash-routed pages, and dashboards that are a
JSON document an operator edits in place, with a default template per deck and
server-side caps on what a save may contain.

Sections: Dashboard and Mining/Overview are editable dashboards (drag to
reorder, add a block, save, reset). Mining also serves Hashboards, Power Supply
and Fans from the hardware document. Settings serves System, Drivers, Security,
Services, Monitor, Logs, Files and Terminal. Files and Terminal are gated on a
token at /var/lib/alkane/ui-token so a shared network cannot use them.

Served on port 80 of the miner's own address (8080 if 80 cannot be bound), and
started from the runlevel so the page is up without an operator. The JSON API
remains the interface of record: every value shown is also at /api/, and nothing
is reachable only through the page.

Verified: 165 tests, clippy clean, all 13 pages answering, and on the bench S21
Pro the UI answers on port 80 after an unattended reboot.
2026-11-04 14:06:24 -06:00
noah f6af71138c Publish the live operating point every control period
source-pr / source (pull_request) Successful in 12s
A client watching the API during a run saw the boot-time snapshot: status was
published at boot and again when the loop exited, so frequency and voltage were
frozen at their starting values for the whole run. The loop now publishes each
period, which is what makes the UI and the API honest while the machine is
actually mining.
2026-10-22 11:10:32 -06:00
noah 8564ced65d Validate profile databases and make the power check meaningful
source-pr / source (pull_request) Successful in 12s
--check-profiles parses a database and reports schema, count and validation,
so envelope work can be checked before an image ever boots with it. An inverted
envelope is rejected with a non-zero exit.

The conformance power check now sets 500 MHz before reading, because a backend
that always reports 0 W passed a range check while being useless to a
power-target loop. It must now report a plausible non-zero draw at a known
operating point.
2026-10-22 11:08:07 -06:00
noah 78baeb8c31 Add a HAL conformance harness for family backends
source-pr / source (pull_request) Successful in 12s
A family backend is only useful if it answers the contract the OS expects, and
until now the only way to know was to boot a board and watch it fail somewhere
downstream. --check-hal walks the contract in order (capabilities, probe,
EEPROM, PSU, frequency and temperature, power, fan) and reports each check
separately, using a fresh connection per check so one desynchronised exchange
cannot invalidate the rest.

It catches the failure modes that matter for autodetect: a backend that does
not advertise chain probing, one that reports an inverted envelope, one that
returns an implausible temperature or power, and one that cannot accept
frequency or fan commands.
2026-10-22 11:06:22 -06:00
noah a16a4385f8 Drive an SV2 session against a socket pool end to end
source-pr / source (pull_request) Successful in 12s
The codec and session had only ever been tested in memory. This runs the real
path over TCP: the client handshakes, opens a channel, receives SetNewPrevHash
and an active NewMiningJob, submits a share and consumes the acknowledgement,
against a mock pool that speaks the same frames.

It also pins the ordering the protocol depends on: the job is interpreted only
after the prev hash, and the submit sequence starts at one.
2026-10-22 11:03:41 -06:00
noah 79f492e5e8 Make the reference server thermal model fan-aware
source-pr / source (pull_request) Successful in 13s
Zones now respond to the fan that actually cools them (round-robin by zone
index), so the active fan sweep can be demonstrated end to end without
hardware: with two fans and three zones the learned map is fan 0 -> zones 0,2
and fan 1 -> zone 1, persisted to the map file.

The settle interval is configurable (ALKANE_FAN_SETTLE_MS) because the real
twenty-second settle makes an interactive sweep last minutes.
2026-10-22 11:02:02 -06:00
noah b0d81b5d0e Add a reference HAL server and power telemetry
source-pr / source (pull_request) Successful in 13s
The reference server answers the real ALKH contract from a fixed machine
description, so the whole OS path can run on a development host and a backend
author has a concrete example of every opcode. It serves detection, frequency,
fan, temperature and power over one socket.

Power was the missing measurement: a power target could not regulate because
the HAL had no way to report watts, so READ_POWER joins the verbs behind
CAP_POWER. With it, --boot against the reference server settles the loop at
623 MHz for a 2400 W target (4 W per MHz in the model) instead of holding at
the boot frequency.

Fan mapping stays opt-in for --boot (ALKANE_FAN_FANS/ALKANE_FAN_ZONES) because
it perturbs the machine and takes minutes.
2026-10-22 10:59:53 -06:00
noah dccbefc8b7 Add the HAL frequency actuator and a --boot command
source-pr / source (pull_request) Successful in 14s
The tuner produced a frequency the hardware contract had no way to apply, so
detection and tuning could not affect a real board. SET_CHAIN_FREQUENCY joins
the HAL verbs behind its own capability bit, and HalClient refuses to use it
when the backend does not advertise it.

--boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] now runs the real
path: detect over the socket, serve the API and UI, read the hottest sensor,
tick the runtime, apply the frequency to each active chain and the fan duty
when the target owns the fan, then print the published document. A missing
socket exits 1 with a backend error instead of a half-booted miner.
2026-10-22 10:56:43 -06:00
noah 894b22277f Boot over the real HAL contract
source-pr / source (pull_request) Successful in 14s
boot_from_hal connects the board backend, detects through the actual HAL
verbs, runs the one-time fan sweep through the same socket, publishes the
snapshot and returns the runtime and the learned map.

The tests drive it against a mock backend that speaks the real wire protocol
(ALKH framing, CAPABILITIES, PROBE_CHAIN, READ_EEPROM, IDENTIFY_PSU), so the
detection path is exercised end to end rather than assumed, and a missing
socket surfaces as a backend error instead of a half-booted miner.
2026-10-22 10:54:35 -06:00
noah 64e1a9ae2b Report one operating point, not two
source-pr / source (pull_request) Successful in 13s
The live frequency and the boot-time operating point were both in the
hardware document, so a client could read 563 MHz in one field and 300 MHz in
another. The document and the cgminer stats now both derive the operating point
from the live frequency and the envelope, which is also what makes the reported
voltage correct.
2026-10-22 10:51:45 -06:00
noah 2b07d27c67 Pair voltage with frequency across the profile envelope
source-pr / source (pull_request) Successful in 12s
Boards do not run at a fixed voltage across their frequency range, so the
reported operating point was describing a machine that does not exist: the
voltage stayed at the boot value while the tuner moved the frequency.

Envelope::voltage_for interpolates linearly between the profile floor and
ceiling and clamps outside it, and MinerRuntime now reports the voltage that
pairs with the applied frequency. A single-frequency envelope reports its
floor without dividing by zero.
2026-10-22 10:50:56 -06:00
noah 42509a6383 Add a runnable self-check for the boot path
source-pr / source (pull_request) Successful in 12s
alkane-os --self-check drives the whole chain without hardware: parse the
example profile database, detect three BM1362 chains with a dead EEPROM,
identify an APW12, boot the runtime, tick toward a power target and print the
published hardware document. It fails loudly if the profile database does not
parse, detection refuses, the tuner does not move, or the chain set is wrong,
which makes it usable as a bench smoke test on a bare control board.

profiles.example.json is a shape example, not validated hardware data: the
envelopes are placeholders until real captures fill the database.
2026-10-22 10:49:04 -06:00
noah 5048156b74 Persist the learned fan map and reuse it until the hardware changes
source-pr / source (pull_request) Successful in 12s
Mapping fans perturbs the machine, so it is done once and stored. ensure_map
reuses a stored map only when the fan and sensor counts match the current
machine; a mismatch is ignored rather than trusted, because applying a map
learned on four fans to a two-fan machine would mis-control thermals.

The store is a small schema-1 document; corrupt or foreign files are ignored
and trigger a fresh sweep instead of failing the boot.
2026-10-22 10:47:19 -06:00
noah 5a1a7948b1 Add the boot sequence from backend and profiles to runtime
source-pr / source (pull_request) Successful in 12s
app::boot is the sequence a family image runs at start-up: validate the
profile database, detect the hardware through the backend, build the runtime
with the operator target and fault policy, and publish the API snapshot in one
step. It returns the runtime or an explicit BootError, so a refusal is visible
to the caller instead of a half-configured miner.

Target labels are defined once (power:3000, hashrate:200, ambient:20000,
fan:100) so the API, UI and logs cannot drift apart.
2026-10-22 10:45:33 -06:00
noah 2c6535f948 Wire the API and UI through one start-up path
source-pr / source (pull_request) Successful in 12s
Add an app layer that binds and starts the management API and the web UI,
publishes the runtime snapshot, and exposes a bound-address result so callers
can discover ephemeral ports. The binary now uses the same function the tests
use, so the wiring CI exercises is the wiring that runs on a board, and it
gained ALKANE_WEB_LISTEN alongside ALKANE_API_LISTEN.

The snapshot is built from the live runtime: active chains, stop reason and
the last applied frequency rather than the boot default.
2026-10-22 10:43:39 -06:00
noah e3e0dab0ec Add the SV2 TCP link and the V1 fallback policy
source-pr / source (pull_request) Successful in 12s
TcpLink turns a TCP stream into framed SV2 messages: it buffers partial reads
and returns one frame at a time, so a frame split across packets is not a
protocol error and two frames in one read are still delivered separately. A
closed stream is an error, never an empty frame.

The fallback policy permits Stratum V1 only when the operator allowed it and
the failure is not transport-level: a dead route or a dropped stream fails
identically on V1, so falling back there would only delay the real error. V1
failures never loop back to V2.
2026-10-22 10:41:23 -06:00
noah 97ea7a4f65 Add the mining runtime state machine
source-pr / source (pull_request) Successful in 13s
Tie the detection plan, the fault ladder and the tuner together, where their
order is decided: a stopped machine is never tuned, a disabled chain is never
dispatched to, and a missing measurement holds the last command instead of
inventing one.

MinerRuntime exposes the active chain set, the stop reason and an operating
point that reflects the last applied command rather than the boot-time
default, which is what the API snapshot reports.
2026-10-22 10:39:43 -06:00
noah b25d6b2a71 Serve an on-box web UI backed by the JSON API
source-pr / source (pull_request) Successful in 12s
The miner now serves a single page that polls /api/hardware and shows profile,
chip, PSU, operating point, chains and EEPROM state, active chains, target and
whether hashing stopped. The page is a convenience; the API routes it uses are
the interface of record, so a JSON-only client loses nothing.

No framework and no new dependency: the request parser is bounded, only GET is
accepted, responses close the connection and are not cached. MiningStatus now
exposes its hardware and summary documents so the UI and the cgminer-style
server build them once, in one place.
2026-10-22 10:38:07 -06:00
noah 914fb8bef7 Add the Stratum V2 session: handshake, jobs and submissions
source-pr / source (pull_request) Successful in 11s
Drive the client half of an SV2 mining connection: send SetupConnection,
verify the success reply, open a standard channel and remember its id, target
and extranonce prefix. Afterwards the session interprets NewMiningJob,
SetNewPrevHash, SetTarget and share acknowledgements, and submits standard
shares with a monotonic sequence number.

State is explicit rather than assumed: a job that arrives before any
SetNewPrevHash reports no previous hash instead of a zero one, a setup or
channel rejection carries the server's error code, and an unknown message is
ignored instead of killing the session.
2026-10-22 10:36:29 -06:00
noah 6ab645e731 Add the Stratum V2 mining-protocol codec
source-pr / source (pull_request) Successful in 12s
Implement the client half of SV2 as framed messages: the 6-byte header
(extension_type U16, msg_type U8, msg_length U24), SetupConnection and its
success reply, OpenStandardMiningChannel and its success reply, NewMiningJob
with both the active and future ntime forms, SetNewPrevHash and
SubmitSharesStandard.

Field layouts and message identifiers come from the published specification
(03-Protocol-Overview 3.2/3.6, 08-Message-Types, 05-Mining-Protocol 5.3) and
were checked against it rather than recalled. Decoding is strict: truncated
payloads, bad option markers, bad UTF-8 and a non-finite or negative hashrate
are protocol errors, never defaults.
2026-10-22 10:34:44 -06:00
noah b62d64adfb Split hashrate across pools with smooth weighted round-robin
source-pr / source (pull_request) Successful in 12s
Each dispatched work slot comes from exactly one pool, and the router hands
out slots in proportion to the configured weights. Smooth weighted
round-robin is used instead of a plain repeating pattern because it keeps the
mix correct at every prefix: a miner with three chains still gets the intended
ratio in the first three slots, not only after a hundred.

Weights parse from a simple list, a zero-weight pool never receives work, and
malformed configurations (empty, all zero, non-numeric, too many pools) are
refused rather than silently normalised.
2026-10-22 10:32:42 -06:00
noah fe0c2d43ce Expose detection, envelope and tuning state on the management API
source-pr / source (pull_request) Successful in 12s
The cgminer-compatible surface only answered summary and version, which hides
everything detection learned. The API now also answers hardware (profile, chip,
PSU, envelope, operating point, per-chain chip count and EEPROM state, fan
zones, active chains, stop reason, target and live frequency) and stats (the
same data in cgminer's flat STATS shape).

MiningStatus carries an optional HardwareSnapshot behind a mutex, so a client
can tell unavailable apart from an empty machine, and unknown commands still
refuse. Chip models gained a stable API name so the wire strings do not drift
from the enum.
2026-10-22 10:30:49 -06:00
noah 96f84dc283 Add the ambient-temperature and max-fan tuning targets
source-pr / source (pull_request) Successful in 12s
Ambient mode holds the hottest sensor a configured margin above the measured
intake temperature, which is the efficiency-at-this-ambient operating point;
missing either sensor is an error rather than a guess. Max-fan mode pins the
fan at its cap, ramps frequency toward the envelope ceiling, and still defers
to the thermal guard.

step() now returns a Command carrying the frequency and, when the target owns
the fan, the duty to apply. The max-fan ramp is explicit rather than a
setpoint loop: a P controller fed its own output settles at half the ceiling,
which the ramp test caught.
2026-10-22 10:28:53 -06:00
noah 5aa6349e27 Add adaptive PID tuning with a thermal derate guard
source-pr / source (pull_request) Successful in 12s
Replace preset tuning with a bounded controller: a PID over chain frequency
that targets a DC power draw or a hashrate, inside the profile envelope. The
controller rate-limits its output, ignores errors inside a deadband, takes the
derivative on the measurement so a setpoint change does not kick it, and uses
conditional integration so a saturated actuator does not wind the integral up.

A thermal guard runs before the target logic: any sensor at or above the
ceiling derates the frequency regardless of what the operator asked for, so a
hashrate target can never cook a board.
2026-10-22 10:26:30 -06:00
noah 724b3da478 Add the fault-tolerance escalation ladder
source-pr / source (pull_request) Successful in 12s
The machine should keep hashing with as many dead chips or chains as
possible, so faults escalate in steps instead of stopping at the first one:
a chain error retries up to a policy limit, then the chain is disabled and the
rest keep running; a chip fault disables only that chip; a chain whose nonce
response stays below the policy floor for consecutive windows is disabled; a
temperature fault stops the machine immediately.

Disabling every chain stops with NoChainsLeft rather than leaving the miner
spinning on an empty active set. The supervisor owns no hardware and no
thermal limits; those come from the profile envelope.
2026-10-22 10:24:38 -06:00
noah ef399d0ca5 Drive fan probing through the HAL client
source-pr / source (pull_request) Successful in 12s
HalClient implements FanProbe, so the measurement sweep runs against a real
board over the same local contract: set_fan maps to SET_FAN_TARGET and
read_zone maps to READ_TEMPERATURE. The wire round-trip test now exercises
both fan verbs through the mock backend.
2026-10-22 10:22:52 -06:00
noah 4139576155 Add the fan-mapping measurement sweep
source-pr / source (pull_request) Successful in 11s
sweep() drives the probing run that map_fans consumes: it moves one fan at a
time between the low and high duty while the others hold their setting, waits
for the settle interval, and records every zone reading. Repeat readings are
emitted so the mapper averages noise.

Safety is enforced in the loop, not by convention: a probe duty below the
minimum, an empty duty range, an inverted range, zero reads and zero fans are
all refused before any fan is touched, and the run always ends with every fan
restored to the high duty so the machine is not left under-cooled.
2026-10-22 10:21:26 -06:00
noah c616429669 Map fans to thermal zones by active probing
source-pr / source (pull_request) Successful in 11s
Fans are not labeled by the hardware: a fan can cool one hashboard heavily
and another barely, and front/back top/bottom is physical. map_fans learns the
map from a stepped run: for every fan compare zone temperatures at the lowest
and highest duty, then give each zone to the fan with the strongest cooling
response.

A response must clear min_drop_mc and beat the runner-up by
min_margin_per_mille, otherwise the zone is reported unresolved rather than
guessed, so a noisy run cannot invent a map. One fan may own several zones,
and a fan with no duty range contributes no evidence.
2026-10-22 10:19:45 -06:00
noah 9ed94bd01f Add the profile database and the end-to-end detection driver
source-pr / source (pull_request) Successful in 12s
Profiles carry the only envelopes detection may use, so a combination absent
from the database is refused rather than guessed. The schema-1 document is
validated on load: unknown chips or sensor wiring, inverted or zero envelopes,
zero chain counts and duplicate names are all rejected.

run_detection now ties the pieces together: probe every declared port, select
a profile by chip, sensor wiring and physical port count, identify the PSU, and
emit a HardwarePlan. A machine with a dead chain still matches its three-chain
profile and runs degraded instead of being reclassified; plan() now tolerates
unidentified chains and refuses only when nothing identified.

The detection backend contract gains identify_psu(), and HalClient answers it
through the new HAL verb.
2026-10-22 10:17:34 -06:00
noah 3028ef29fb Carry detection verbs over the HAL wire contract
source-pr / source (pull_request) Successful in 12s
Add capability negotiation and three detection verbs to the local HAL
contract: CAPABILITIES, PROBE_CHAIN, READ_EEPROM and IDENTIFY_PSU. A backend
that predates them rejects the capability query, which surfaces as a protocol
error instead of a silent zero. HalClient implements ChainProbe, so the OS
detection driver can run against a real board without knowing the family.

The probe contract is now error-aware: a transport failure propagates as an
error and is never reported as a silent port, and probe_chain/detect_chains
are generic over the backend. A wire round-trip test drives a mock backend
over a socket pair and checks the encoding of all three verbs.
2026-10-22 10:15:29 -06:00
noah 99fb12d725 Add chain probing policy to the detection core
source-pr / source (pull_request) Successful in 12s
Define the backend contract for identification (ChainProbe) with a bounded
ProbeBudget and a ProbeOutcome that distinguishes an identified chain from a
silent port and from unframed bytes. probe_chain retries a chain until it
identifies or the budget is spent, and reports an exhausted chain as an
unknown chip instead of dropping it; detect_chains walks every declared port.

Framing and baud switching stay in the per-family SDK backend. Tests cover
retry-until-identified, budget exhaustion, EEPROM state retention and the
refusal path when a chain never identifies.
2026-10-22 10:13:18 -06:00
noah 367f07d956 Add hardware detection plan model
source-pr / source (pull_request) Successful in 14s
Introduce the detection core data model: chain observations, board profile
and PSU envelopes, envelope intersection, and a conservative operating point
when the hardware is not confirmed by an EEPROM. Refusal is explicit for
unknown chips, missing PSUs and empty envelopes, and degraded chains are
reported rather than fatal.
2026-10-22 10:11:52 -06:00
noah 29749fee4a Merge pull request 'Name each Alkane evidence milestone without promoting claims' (#13) from tooling/evidence-levels into next
next-build / build (push) Successful in 26s
2026-10-21 07:50:26 -06:00
noah 1f558ef596 Name each Alkane evidence milestone without promoting claims
source-pr / source (pull_request) Successful in 58s
2026-10-21 07:48:45 -06:00
noah 576f834169 Merge pull request 'Separate research evidence and speed scoped OS PR checks' (#12) from tooling/lab-evidence-ci into next
next-build / build (push) Successful in 38s
2026-10-21 07:40:53 -06:00
noah 093cb62212 Separate research evidence and speed scoped OS PR checks
source-pr / source (pull_request) Successful in 10s
2026-10-21 07:38:30 -06:00
noah 2e42bedb84 Merge pull request 'Route trusted OS next jobs to verifier' (#10) from ci/isolate-fast-runner-next into next
next-build / build (push) Successful in 29s
2026-10-20 18:56:41 -06:00
noah 0b785eebb5 Route trusted OS next jobs to verifier
source-pr / source (pull_request) Successful in 57s
2026-10-20 18:45:04 -06:00
noah 885a71b6fe Merge pull request 'Preserve queued OS merge builds and guard reruns' (#9) from ci/preserve-next-runs into next
next-build / build (push) Successful in 42s
2026-10-19 14:46:44 -06:00
noah 8672507fa4 Preserve queued OS merge builds and guard reruns
source-pr / source (pull_request) Successful in 42s
2026-10-19 14:45:35 -06:00
noah 37f1f8433b Merge pull request 'Route short OS builds to Alkane fast runner' (#8) from ci/route-os-fast-runner into next
next-build / build (push) Successful in 25s
2026-10-19 14:43:50 -06:00
noah b703c757e4 Route short OS builds to Alkane fast runner
source-pr / source (pull_request) Successful in 29s
2026-10-19 14:42:54 -06:00
noah 98d891fc67 Merge pull request 'Expose observed BM1370 work ID correlation' (#7) from feature/bm1370-work-id into next
next-build / build (push) Canceled after 0s
2026-10-19 14:35:26 -06:00
noah d6e043d79f Expose observed BM1370 work ID correlation
source-pr / source (pull_request) Successful in 10s
2026-10-19 13:48:13 -06:00
noah ba286758c7 Merge BM1370 captured wire primitives
next-build / build (push) Successful in 13s
Pure Rust framing; chain, work attribution, and pool acceptance remain open.
2026-10-19 12:17:42 -06:00
noah b65e6bc9f1 Install rustfmt in Alkane OS pull request job
source-pr / source (pull_request) Successful in 12s
2026-10-19 12:15:30 -06:00
noah f7aeeaa2eb Run protected Alkane OS source checks on pull requests
source-pr / source (pull_request) Failing after 5s
2026-10-19 12:12:48 -06:00
noah 1b0607cbd8 Add capture-checked BM1370 wire primitives 2026-10-19 12:11:00 -06:00
noah 7c361aecd9 Invalidate ASIC work when pool version mask changes
next-build / build (push) Successful in 21s
2026-10-17 06:05:03 -06:00
noah 212c9198eb docs: shorten OS entry guide
next-build / build (push) Successful in 19s
2026-10-17 01:42:42 -06:00
noah be0a57a1d9 Publish benchmark Pages on the standing Alkane runner
next-build / build (push) Successful in 15s
2026-10-17 01:17:56 -06:00
noah 8bdcd8fb83 Pin benchmark Pages SSH host key
next-build / build (push) Successful in 15s
2026-10-17 01:05:04 -06:00
noah 885a4571ff Make wrong-sequence HAL test stop after rejected header
next-build / build (push) Successful in 12s
2026-10-16 23:02:56 -06:00
noah e746efcb94 Bound management request lifetime
next-build / build (push) Successful in 12s
2026-10-16 21:04:27 -06:00
noah 16c9d4962a Add local read-only mining status API
next-build / build (push) Canceled after 0s
2026-10-16 21:03:40 -06:00
noah 283287f74f Benchmark captured BM1366 report poll path
next-build / build (push) Canceled after 0s
2026-10-16 17:02:10 -06:00
noah 98f3eb75c0 Benchmark BM13xx protocol checksums
next-build / build (push) Canceled after 0s
2026-10-16 14:06:25 -06:00
noah 853cb845ff Benchmark HAL and Stratum socket exchanges
next-build / build (push) Canceled after 0s
2026-10-16 11:06:59 -06:00
noah e9a3c3a669 Benchmark BM1362 work and Stratum handshake paths
next-build / build (push) Canceled after 0s
2026-10-16 09:02:45 -06:00
noah 895081e509 Validate public benchmark page before upload
next-build / build (push) Canceled after 0s
2026-10-16 08:47:19 -06:00
noah b76b74cb63 Describe selected BM13xx host mining formats
next-build / build (push) Canceled after 0s
2026-10-16 08:12:51 -06:00
noah 289ad40d86 Select BM1362 work encoding for captured replay
next-build / build (push) Canceled after 0s
2026-10-16 08:11:46 -06:00
noah f0c9d4d904 Set captured midstate count in BM1366 work
next-build / build (push) Canceled after 0s
2026-10-16 08:03:40 -06:00
noah f6b5df831e Publish OS benchmarks to public Pages site
next-build / build (push) Canceled after 0s
2026-10-16 07:19:41 -06:00
noah d1d7c576cf Bound queued OS CI attempts per branch
next-build / build (push) Canceled after 0s
2026-10-16 07:08:18 -06:00
noah 8d19cdeae6 Schedule CI badge refresh without workflow recursion
next-build / build (push) Successful in 18s
2026-10-16 07:03:17 -06:00
noah 52e6093011 Require complete OS microbenchmark measurements
next-build / build (push) Successful in 18s
2026-10-16 05:02:08 -06:00
noah 7fd9c8eee3 Keep buffered Stratum partial line deadline across drains
next-build / build (push) Successful in 13s
2026-10-16 04:01:56 -06:00
noah f302bbbb24 Attach OS quality gate evidence to metrics
next-build / build (push) Successful in 14s
2026-10-16 02:06:01 -06:00
noah b22b494ede Grade OS code quality from static checks
next-build / build (push) Successful in 15s
2026-10-16 02:02:53 -06:00
noah 6c23ce847d Coalesce pending CI badge updates
next-build / build (push) Successful in 15s
2026-10-16 01:02:52 -06:00
noah 6a466a611f Reject invalid BM1362 geometry and baud requests
next-build / build (push) Successful in 18s
2026-10-15 22:07:45 -06:00
noah 1300d7e372 Benchmark BM1362 frame encoding
next-build / build (push) Successful in 18s
2026-10-15 22:06:01 -06:00
noah 66e4f3d47a Add Rust BM1362 wire frame encoders
next-build / build (push) Successful in 18s
2026-10-15 22:04:07 -06:00
noah 37028cc3eb Verify Litecoin Scrypt shares in conformance gate
next-build / build (push) Successful in 18s
2026-10-15 21:05:08 -06:00
noah 0e6fd9269b Add simulator mining command to Alkane OS
next-build / build (push) Canceled after 0s
2026-10-15 18:22:49 -06:00
noah 3d63bbb3eb Set Rust-first core implementation policy
next-build / build (push) Canceled after 0s
2026-10-15 14:46:30 -06:00
noah 5d8f14c992 Shorten OS README to scope and release gates
next-build / build (push) Canceled after 0s
2026-10-15 14:37:04 -06:00
noah 6f87f48dca Document miner work ID and shutdown guards
next-build / build (push) Successful in 10s
2026-10-15 13:04:51 -06:00
noah 7d398caa66 Reserve ASIC work IDs until hardware flush and fault on failed shutdown
next-build / build (push) Successful in 16s
2026-10-15 13:04:14 -06:00
noah 96dd7bf6d2 Clean OS CI outputs after build and release
next-build / build (push) Canceled after 0s
2026-10-15 11:48:14 -06:00
noah 59249d44d3 Verify BM1362 capture through shared miner work path
next-build / build (push) Canceled after 0s
2026-10-15 05:50:00 -06:00
noah f011557cd5 Add MIT Litecoin Scrypt share verifier
next-build / build (push) Canceled after 0s
2026-10-15 04:56:39 -06:00
noah d52996c02a Accept captured BM1362 share through strict pool
next-build / build (push) Canceled after 0s
2026-10-15 04:28:46 -06:00
noah b59aa8d9c1 Verify BM1362 captured share through HAL replay
next-build / build (push) Canceled after 0s
2026-10-15 04:20:29 -06:00
noah 523ec5fd0b Replay 33 captured BM1366 shares through pool
next-build / build (push) Canceled after 0s
2026-10-15 04:11:00 -06:00
noah a1d8e34390 Flush ASIC work before recycling job IDs
next-build / build (push) Canceled after 0s
2026-10-15 03:55:13 -06:00
noah 2d6233cdc7 Verify captured BM1366 share through strict pool replay
next-build / build (push) Canceled after 0s
2026-10-15 03:47:59 -06:00
noah eb9dcf830b Calibrate microbenchmarks and measure quality grade
next-build / build (push) Canceled after 0s
2026-10-15 03:17:58 -06:00
noah af49d4905d Require Git tag for completed release
next-build / build (push) Canceled after 0s
2026-10-15 03:09:11 -06:00
noah 8fa9e5d9e6 Bind share evidence to Stratum work and improve pool polling
next-build / build (push) Canceled after 0s
2026-10-15 03:07:16 -06:00
noah 492fe68c9e Verify release artifacts and keep uploads draft until complete
next-build / build (push) Canceled after 0s
2026-10-15 02:49:03 -06:00
noah f215cb3196 Fail closed on pool and HAL faults and bind release evidence to CI run
next-build / build (push) Canceled after 0s
2026-10-15 02:33:33 -06:00
noah 6e3b798273 Cross-check release evidence against built target matrix
next-build / build (push) Canceled after 0s
2026-10-15 02:16:34 -06:00
noah 16b55b58e3 Bound pool share replies and advance mining cycle
next-build / build (push) Canceled after 0s
2026-10-15 02:12:19 -06:00
noah 90a2fe12d5 Track pool jobs and share replies in connection
next-build / build (push) Canceled after 0s
2026-10-15 01:56:55 -06:00
noah bc38a4a787 Negotiate pool extensions and authorize over bounded transport
next-build / build (push) Canceled after 0s
2026-10-15 01:44:12 -06:00
noah 654b205e00 Add bounded Stratum TCP transport and request frames
next-build / build (push) Canceled after 0s
2026-10-15 01:31:33 -06:00
noah ece32ef55f Track Stratum jobs across ASIC work IDs
next-build / build (push) Canceled after 0s
2026-10-15 01:16:19 -06:00
noah 5cd77eb5de Convert pool difficulty to exact share targets
next-build / build (push) Successful in 11s
2026-10-15 01:00:53 -06:00
noah e7a23faa5a Decode Stratum pool control notifications
next-build / build (push) Canceled after 0s
2026-10-15 00:49:35 -06:00
noah e0f9b1ab50 Vendor pinned Rust dependencies for offline SDK builds
next-build / build (push) Canceled after 0s
2026-10-15 00:15:24 -06:00
noah 323e45ab0e Decode bounded Stratum V1 pool jobs
next-build / build (push) Canceled after 0s
2026-10-15 00:05:19 -06:00
noah 6fd329e047 Format mask-checked Stratum V1 share submissions
next-build / build (push) Canceled after 0s
2026-10-15 00:00:22 -06:00
noah 7d602d2f03 Keep in-flight ASIC work across pool job changes
next-build / build (push) Canceled after 0s
2026-10-14 20:57:56 -06:00
noah 78b9416985 Use Gitea-compatible pinned artifact uploads
next-build / build (push) Canceled after 0s
2026-10-14 20:51:16 -06:00
noah d2afef19a9 Construct SHA-256 Stratum work headers for BM1366
next-build / build (push) Canceled after 0s
2026-10-14 20:24:34 -06:00
noah e67ffcd204 Record private per-commit OS benchmark history
next-build / build (push) Canceled after 0s
2026-10-14 20:17:31 -06:00
noah 6cf9ed1620 Publish measured OS badges to private branch
next-build / build (push) Canceled after 0s
2026-10-14 20:11:09 -06:00
noah 4f21677ae5 Ignore cancelled runs in completed CI badge
next-build / build (push) Canceled after 0s
2026-10-14 19:58:25 -06:00
noah 9f7d8ebb51 Add fail-safe BM1366 mining session
next-build / build (push) Canceled after 0s
2026-10-14 19:53:40 -06:00
noah 81d726cca2 Publish branch badges from completed CI runs
next-build / build (push) Successful in 11s
2026-10-14 19:47:07 -06:00
noah 74ba049b5c Add reusable BM1366 work and report codec
next-build / build (push) Successful in 10s
2026-10-14 19:43:06 -06:00
noah 46a4f58019 Verify captured ASIC shares and probe SDK simulator
next-build / build (push) Successful in 13s
2026-10-14 19:37:38 -06:00
noah e9d7200a05 Keep bounded HAL connections dependency free
next-build / build (push) Canceled after 0s
2026-10-14 19:19:37 -06:00
noah 544711885e Bound HAL socket exchanges and validate errors
next-build / build (push) Canceled after 0s
2026-10-14 19:17:12 -06:00
noah 7d3cebea79 Add versioned SDK HAL socket client
next-build / build (push) Canceled after 0s
2026-10-14 19:10:17 -06:00
noah 1ce22d9d9f Merge branch 'main' into next
next-build / build (push) Successful in 9s
2026-10-13 11:59:47 -06:00
noah befa97d82b Install Rust quality tools in CI
main-release-gate / verify-and-release (push) Failing after 1m1s
2026-10-13 11:59:11 -06:00
noah 4eef88b5df Point next CI badge at next attempts
next-build / build (push) Successful in 8s
2026-10-13 11:46:20 -06:00
noah ab264f4923 Add measured badges and coverage reports
main-release-gate / verify-and-release (push) Failing after 8s
next-build / build (push) Successful in 8s
2026-10-13 11:45:56 -06:00
noah af8a33b1a0 Add target inventory executable for SDK images
main-release-gate / verify-and-release (push) Failing after 4s
next-build / build (push) Successful in 7s
2026-10-13 11:22:39 -06:00
noah 3ab9d1a4bf Initialize Alkane OS target matrix and release gates
main-release-gate / verify-and-release (push) Failing after 4s
next-build / build (push) Successful in 4s
2026-10-13 11:13:39 -06:00
3517 changed files with 1263462 additions and 2250 deletions
+5
View File
@@ -0,0 +1,5 @@
[source.crates-io]
replace-with = "vendored-sources"
[source.vendored-sources]
directory = "vendor"
+36
View File
@@ -0,0 +1,36 @@
name: public-benchmark-pages
on:
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:
concurrency:
group: alkane-os-public-benchmark-pages
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
- 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
+23
View File
@@ -0,0 +1,23 @@
name: completed-ci-badge
on:
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:
concurrency:
group: alkane-os-completed-ci-badge
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-ci
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
+136
View File
@@ -0,0 +1,136 @@
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
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: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
- name: Install Rust quality tools
run: rustup component add rustfmt clippy
- name: Image safety gate
run: sh ci/check-image-safety.sh
- 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
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
cargo install --locked cargo-llvm-cov --version 0.8.7
fi
- name: Unit test coverage
run: |
mkdir -p coverage
CARGO_TARGET_DIR=target/coverage-tests cargo llvm-cov --json \
--output-path coverage/tests.json --locked
- name: Microbenchmark coverage
run: |
CARGO_TARGET_DIR=target/coverage-bench cargo llvm-cov --json \
--output-path coverage/bench.json --locked -- --ignored
- name: Load previous main benchmark measurement
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py prepare
- name: Generate measured badges
run: |
python3 ci/metrics.py --tests-output tests-current.txt \
--tests-coverage coverage/tests.json --bench-output bench-current.txt \
--bench-coverage coverage/bench.json --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
+38
View File
@@ -0,0 +1,38 @@
name: next-build
on:
push:
branches: [next]
jobs:
build:
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env:
CARGO_TARGET_DIR: target
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Image safety gate
run: sh ci/check-image-safety.sh
- 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
+57
View File
@@ -0,0 +1,57 @@
name: source-pr
on:
pull_request:
branches: [next, main]
workflow_dispatch:
concurrency:
group: alkane-os-source-pr-${{ github.ref }}
cancel-in-progress: true
jobs:
source:
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env:
CARGO_TARGET_DIR: target
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect changed surface
id: surface
run: python3 ci/pr_surface.py >> "$GITHUB_OUTPUT"
- name: Check patch whitespace
run: |
if [ "${GITHUB_EVENT_NAME:-}" = pull_request ]; then
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
else
git diff --check HEAD^ HEAD
fi
- name: Check CI and evidence tools
if: steps.surface.outputs.surface != 'documentation'
run: |
python3 -m compileall -q ci
for test in ci/test-*.py; do python3 "$test"; done
python3 ci/evidence_status.py
python3 ci/experiment_priority.py
- name: Install source formatter
if: steps.surface.outputs.surface == 'rust'
run: rustup component add rustfmt
- name: Check source formatting
if: steps.surface.outputs.surface == 'rust'
run: cargo fmt --check
- name: Check changed Rust source
if: steps.surface.outputs.surface == 'rust'
run: |
if [ "${GITHUB_BASE_REF:-}" = main ]; then
cargo build --release --offline --locked
else
cargo check --offline --locked
fi
- name: Clean generated build
if: always()
run: python3 ci/cleanup-generated.py
+4
View File
@@ -0,0 +1,4 @@
/target/
/dist/
/coverage/
__pycache__/
+7
View File
@@ -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.
Generated
+548
View File
@@ -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"
+28
View File
@@ -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
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2026 BlueFlare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+64 -2
View File
@@ -1,3 +1,65 @@
# CI badges
# Alkane OS
Machine-maintained status for the last completed main and next workflow attempts.
[![CI](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-os/actions)
![tests](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/tests.svg)
![coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/coverage.svg)
![bench](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench.svg)
![bench coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench-coverage.svg)
![lines of code](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/loc.svg)
![dependencies](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/dependencies.svg)
![code quality](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/quality.svg)
![license](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/license.svg)
Rust mining and tuning core for Alkane control boards. The
[SDK](https://gitea.bluefla.re/blueflare/alkane-sdk) builds board images and
provides the hardware backend. The miner has no on-board web frontend.
## 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.
## 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
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="157" height="20" role="img" aria-label="bench coverage: 11.0%"><rect width="110" height="20" rx="3" fill="#555"/><rect x="110" width="47" height="20" rx="3" fill="#dfb317"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="55.0" y="14">bench coverage</text><text x="133.5" y="14">11.0%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="157" height="20" role="img" aria-label="bench coverage: 32.6%"><rect width="110" height="20" rx="3" fill="#555"/><rect x="110" width="47" height="20" rx="3" fill="#dfb317"/><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,sans-serif" font-size="11"><text x="55.0" y="14">bench coverage</text><text x="133.5" y="14">32.6%</text></g></svg>

Before

Width:  |  Height:  |  Size: 397 B

After

Width:  |  Height:  |  Size: 397 B

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

Before

Width:  |  Height:  |  Size: 393 B

After

Width:  |  Height:  |  Size: 390 B

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

Before

Width:  |  Height:  |  Size: 379 B

After

Width:  |  Height:  |  Size: 382 B

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

Before

Width:  |  Height:  |  Size: 385 B

After

Width:  |  Height:  |  Size: 383 B

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

Before

Width:  |  Height:  |  Size: 395 B

After

Width:  |  Height:  |  Size: 391 B

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

Before

Width:  |  Height:  |  Size: 368 B

After

Width:  |  Height:  |  Size: 364 B

+63
View File
@@ -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.
+54
View File
@@ -0,0 +1,54 @@
# SPDX-License-Identifier: MIT
"""Write small badge artifacts to the private Gitea CI badge branch."""
import base64
import json
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
BADGE_BRANCH = "ci-badges"
def request_json(url: str, token: str, method: str = "GET",
payload: dict | None = None) -> dict:
body = None if payload is None else json.dumps(payload).encode()
request = Request(url, data=body, method=method,
headers={"Authorization": f"token {token}",
"Content-Type": "application/json"})
with urlopen(request, timeout=20) as response:
return json.load(response)
def publish_file(api: str, repo: str, filename: str, data: bytes,
token: str, message: str, max_bytes: int = 65_536) -> None:
if not filename or filename.startswith("/") or any(
part in ("", ".", "..") for part in filename.split("/")):
raise ValueError("invalid badge path")
if len(data) > max_bytes:
raise ValueError("artifact exceeds size limit")
path = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}"
encoded = base64.b64encode(data).decode("ascii")
for attempt in range(3):
try:
current = request_json(path + "?ref=" + BADGE_BRANCH, token)
if base64.b64decode(current["content"]) == data:
return
sha = current["sha"]
method = "PUT"
except HTTPError as error:
if error.code != 404:
raise
sha = None
method = "POST"
payload = {"branch": BADGE_BRANCH, "content": encoded,
"message": message + " [skip ci]"}
if sha is not None:
payload["sha"] = sha
try:
request_json(path, token, method, payload)
return
except HTTPError as error:
if error.code not in (409, 422) or attempt == 2:
raise
raise RuntimeError("badge write did not complete")
+159
View File
@@ -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()
+19
View File
@@ -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}
+401
View File
@@ -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()
+92
View File
@@ -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"
+37
View File
@@ -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))
+43
View File
@@ -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)
+763
View File
@@ -0,0 +1,763 @@
{
"schema": 1,
"boards": [
"am335x-bb",
"zynq-7010",
"cv1835",
"a113d",
"allwinner-h3",
"allwinner-h6",
"allwinner-h616"
],
"chips": [
"BM1384",
"BM1387",
"BM1360",
"BM1362",
"BM1366",
"BM1368",
"BM1370",
"BM1396",
"BM1397",
"BM1398",
"BM1489",
"BM1491",
"BM1746",
"KF1950",
"ID-1968",
"ID-1980",
"ID-1990"
],
"vendors": {
"am335x-bb": "bitmain",
"zynq-7010": "bitmain",
"cv1835": "bitmain",
"a113d": "bitmain",
"allwinner-h3": "whatsminer",
"allwinner-h6": "whatsminer",
"allwinner-h616": "whatsminer",
"BM1384": "bitmain",
"BM1387": "bitmain",
"BM1360": "bitmain",
"BM1362": "bitmain",
"BM1366": "bitmain",
"BM1368": "bitmain",
"BM1370": "bitmain",
"BM1396": "bitmain",
"BM1397": "bitmain",
"BM1398": "bitmain",
"BM1489": "bitmain",
"BM1491": "bitmain",
"BM1746": "bitmain",
"KF1950": "whatsminer",
"ID-1968": "whatsminer",
"ID-1980": "whatsminer",
"ID-1990": "whatsminer"
},
"targets": [
{
"board": "am335x-bb",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "am335x-bb",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "zynq-7010",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "cv1835",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1384",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1387",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1360",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1362",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1366",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1368",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1370",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1396",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1397",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1398",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1489",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1491",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "a113d",
"chip": "BM1746",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "KF1950",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "ID-1968",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "ID-1980",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h3",
"chip": "ID-1990",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "KF1950",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "ID-1968",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "ID-1980",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h6",
"chip": "ID-1990",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "KF1950",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "ID-1968",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "ID-1980",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
},
{
"board": "allwinner-h616",
"chip": "ID-1990",
"sdk_image_sha256": null,
"stock_image_sha256": null,
"stock_result": null,
"stock_first_rejection": null,
"alkane_share_accept_capture": null,
"simulator_trace_sha256": null,
"bench_validation": null
}
]
}
+84
View File
@@ -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()
+65
View File
@@ -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"
}
]
}
+62
View File
@@ -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()
+73
View File
@@ -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 ("schedule", "workflow_dispatch"):
raise RuntimeError("badge publisher must run on a timer 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()
+68
View File
@@ -0,0 +1,68 @@
#!/bin/sh
# Build an .afw firmware package for one control board and architecture.
#
# Modelled on the Warden `.wfw` bundle (scada/flare-edge/docs/firmware-format.md):
# one file, a strict POSIX ustar tar, a JSON manifest first, then the payload,
# with the payload's size and sha256 in the manifest so the device can verify
# before it touches flash.
#
# Differences from .wfw, both deliberate:
#
# * the payload is COMPRESSED (`payload.tar.gz`) because these images ship to
# boards over metered links, and a firmware bundle is mostly redundant;
# * the manifest carries `board` and `arch`, and both go in the file name, so a
# bundle can never be mistaken for another board family. Flashing the wrong
# family is how boards are lost.
#
# Signature: `.wfw` carries an Ed25519 detached signature. We have no release
# key yet, so `.afw` currently ships `members=2` and says so in the manifest
# (`signature: "unsigned"`). Do not claim integrity beyond the sha256 until a
# key exists.
#
# usage: make-afw.sh BOARD ARCH VERSION INPUT_DIR [OUTPUT_DIR]
# e.g. make-afw.sh am335x-bb armv7 0.1.0 /tmp/release
set -eu
BOARD=${1:?board family, e.g. am335x-bb}
ARCH=${2:?architecture, e.g. armv7 or aarch64}
VERSION=${3:?version, e.g. 0.1.0}
INPUT=${4:?directory holding the release files}
OUTPUT=${5:-dist}
mkdir -p "$OUTPUT"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
# The payload is a tar of the release tree, gzipped at maximum.
tar --format=ustar --owner=0 --group=0 --numeric-owner \
--create --file "$WORK/payload.tar" -C "$INPUT" .
gzip -9 -n -c "$WORK/payload.tar" > "$WORK/payload.tar.gz"
PAYLOAD_SIZE=$(wc -c < "$WORK/payload.tar.gz")
PAYLOAD_SHA=$(sha256sum "$WORK/payload.tar.gz" | cut -d' ' -f1)
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
cat > "$WORK/manifest.json" <<MANIFEST
{
"schema": 1,
"format": "afw",
"board": "$BOARD",
"arch": "$ARCH",
"version": "$VERSION",
"build_date": "$BUILD_DATE",
"compression": "gzip",
"signature": "unsigned",
"payload": {
"file": "payload.tar.gz",
"size": $PAYLOAD_SIZE,
"sha256": "$PAYLOAD_SHA"
}
}
MANIFEST
NAME="alkane-os-$VERSION-$BOARD-$ARCH.afw"
(cd "$WORK" && tar --format=ustar --owner=0 --group=0 --numeric-owner \
--create --file "$OUTPUT/$NAME" manifest.json payload.tar.gz)
printf '%s\n' "$OUTPUT/$NAME"
printf 'board %s\narch %s\npayload %s bytes\nsha256 %s\n' \
"$BOARD" "$ARCH" "$PAYLOAD_SIZE" "$PAYLOAD_SHA"
+147
View File
@@ -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()
+47
View File
@@ -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")
+121
View File
@@ -0,0 +1,121 @@
#!/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]:
return subprocess.run(args, env=env, cwd=cwd, text=True,
capture_output=True, check=True)
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()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish measured main-branch metric badges to the private badge branch."""
import os
from pathlib import Path
from badge_store import publish_file
ROOT = Path(__file__).resolve().parents[1]
NAMES = ("tests", "coverage", "bench", "bench-coverage", "loc",
"dependencies", "quality", "license")
def main() -> None:
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
for name in NAMES:
data = (ROOT / "badges" / f"{name}.svg").read_bytes()
if not data.lstrip().startswith(b"<svg"):
raise ValueError(f"invalid {name} SVG")
publish_file(api, repo, f"badges/{name}.svg", data, token,
f"Update measured {name} badge")
data = (ROOT / "badges/metrics.json").read_bytes()
publish_file(api, repo, "badges/metrics.json", data, token,
"Update measured badge data")
print(f"Published {len(NAMES)} measured badge SVGs and metrics.json")
if __name__ == "__main__":
main()
+160
View File
@@ -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()
+21
View File
@@ -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"
}
]
}
+58
View File
@@ -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("&lt;script&gt;", page)
self.assertNotIn("<script>", page)
self.assertIn("10.000", page)
if __name__ == "__main__":
unittest.main()
+50
View File
@@ -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()
+115
View File
@@ -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()
+43
View File
@@ -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()
+41
View File
@@ -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()
+67
View File
@@ -0,0 +1,67 @@
#!/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": "schedule",
"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_run"}):
try:
module.main()
except RuntimeError as error:
assert "timer or manual dispatch" in str(error)
else:
raise AssertionError("workflow_run 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")
+51
View File
@@ -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()
+28
View File
@@ -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()
+133
View File
@@ -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()
+59
View File
@@ -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()
+1
View File
@@ -0,0 +1 @@
0
+63
View File
@@ -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()
+116
View File
@@ -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())
}
+59
View File
@@ -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(())
}
@@ -1,49 +0,0 @@
{
"sha": "0c9731a8f94bfd865df59164dbb03ff1e5528fb7",
"timestamp": "2026-10-17T07:13:35+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 165.617,
"bm1362_job_encoding": 201.374,
"bm1362_work_encoding": 201.031,
"bm1366_captured_report_poll": 991.977,
"bm1366_report_decode": 83.607,
"bm1366_session_cycle": 255.529,
"bm1366_work_encoding": 207.648,
"bm13xx_crc16": 219.14,
"bm13xx_crc5": 34.822,
"difficulty_target": 656.388,
"hal_socket_exchange": 36781.484,
"power_policy": 0.877,
"scrypt_share_verification": 256913.781,
"share_verification": 887.985,
"stratum_accept_parse": 426.494,
"stratum_authorize_format": 664.446,
"stratum_configure_format": 1200.607,
"stratum_configure_parse": 1665.166,
"stratum_control_parse": 728.588,
"stratum_header": 4721.786,
"stratum_job_issue": 3712.656,
"stratum_notify_parse": 1477.922,
"stratum_socket_round_trip": 57735.305,
"stratum_submission": 551.557,
"stratum_subscribe_format": 583.6,
"stratum_subscription_parse": 928.84,
"target_matrix": 31.78
},
"bench_improvement_pct": 10.177633367079036,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5780,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "148a0ce5e4daa4582a7a34489fe47a56dd95ca2e",
"timestamp": "2026-10-17T07:08:13+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 129.337,
"bm1362_job_encoding": 152.174,
"bm1362_work_encoding": 153.276,
"bm1366_captured_report_poll": 708.34,
"bm1366_report_decode": 57.134,
"bm1366_session_cycle": 183.153,
"bm1366_work_encoding": 148.746,
"bm13xx_crc16": 160.021,
"bm13xx_crc5": 26.347,
"difficulty_target": 342.74,
"hal_socket_exchange": 15917.646,
"power_policy": 0.488,
"scrypt_share_verification": 193904.781,
"share_verification": 582.904,
"stratum_accept_parse": 184.808,
"stratum_authorize_format": 324.428,
"stratum_configure_format": 504.974,
"stratum_configure_parse": 738.614,
"stratum_control_parse": 278.135,
"stratum_header": 3139.763,
"stratum_job_issue": 1898.936,
"stratum_notify_parse": 1010.965,
"stratum_socket_round_trip": 19381.315,
"stratum_submission": 271.733,
"stratum_subscribe_format": 267.703,
"stratum_subscription_parse": 435.592,
"target_matrix": 19.871
},
"bench_improvement_pct": -6.571618825769334,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5776,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "1d000e037bbbc37ba586245f04d988eeb20d2c4e",
"timestamp": "2026-10-19T02:49:25+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 242.157,
"bm1362_job_encoding": 286.811,
"bm1362_work_encoding": 236.946,
"bm1366_captured_report_poll": 1427.465,
"bm1366_report_decode": 93.29,
"bm1366_session_cycle": 408.666,
"bm1366_work_encoding": 338.106,
"bm13xx_crc16": 313.61,
"bm13xx_crc5": 44.221,
"difficulty_target": 1194.541,
"hal_socket_exchange": 37791.399,
"power_policy": 0.958,
"scrypt_share_verification": 322385.789,
"share_verification": 1420.128,
"stratum_accept_parse": 523.608,
"stratum_authorize_format": 787.622,
"stratum_configure_format": 2076.944,
"stratum_configure_parse": 1829.266,
"stratum_control_parse": 796.057,
"stratum_header": 5512.653,
"stratum_job_issue": 4009.455,
"stratum_notify_parse": 1744.167,
"stratum_socket_round_trip": 66408.86,
"stratum_submission": 736.476,
"stratum_subscribe_format": 767.041,
"stratum_subscription_parse": 1417.268,
"target_matrix": 46.073
},
"bench_improvement_pct": -5.355437076345111,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5802,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,38 +0,0 @@
{
"sha": "1d0c275a043d3067cc7d2d0d617c1b5de815b9bd",
"timestamp": "2026-10-17T04:01:28+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 165.354,
"bm1362_job_encoding": 200.286,
"bm1366_report_decode": 83.727,
"bm1366_session_cycle": 223.244,
"bm1366_work_encoding": 209.351,
"difficulty_target": 661.52,
"power_policy": 0.825,
"scrypt_share_verification": 270686.164,
"share_verification": 958.951,
"stratum_authorize_format": 683.429,
"stratum_configure_parse": 1641.642,
"stratum_control_parse": 604.253,
"stratum_header": 5196.406,
"stratum_job_issue": 4004.139,
"stratum_notify_parse": 1463.534,
"stratum_submission": 520.837,
"target_matrix": 30.431
},
"bench_improvement_pct": 12.990854943787838,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "23a67af7db1c59d48ed052d2f399f53852fba7fd",
"timestamp": "2026-10-17T06:22:39+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 118.466,
"bm1362_job_encoding": 141.095,
"bm1362_work_encoding": 140.218,
"bm1366_captured_report_poll": 619.37,
"bm1366_report_decode": 54.631,
"bm1366_session_cycle": 174.583,
"bm1366_work_encoding": 140.707,
"bm13xx_crc16": 154.111,
"bm13xx_crc5": 25.45,
"difficulty_target": 330.927,
"hal_socket_exchange": 16029.276,
"power_policy": 0.488,
"scrypt_share_verification": 193320.875,
"share_verification": 577.433,
"stratum_accept_parse": 181.167,
"stratum_authorize_format": 287.414,
"stratum_configure_format": 488.179,
"stratum_configure_parse": 703.635,
"stratum_control_parse": 263.262,
"stratum_header": 2946.961,
"stratum_job_issue": 1830.304,
"stratum_notify_parse": 743.751,
"stratum_socket_round_trip": 16392.885,
"stratum_submission": 270.776,
"stratum_subscribe_format": 259.584,
"stratum_subscription_parse": 404.322,
"target_matrix": 18.848
},
"bench_improvement_pct": -2.5965982435089954,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5776,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "361a6f45872bac472719eb1205440627734b9dc0",
"timestamp": "2026-10-19T02:42:52+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 232.262,
"bm1362_job_encoding": 268.042,
"bm1362_work_encoding": 293.119,
"bm1366_captured_report_poll": 1005.482,
"bm1366_report_decode": 107.082,
"bm1366_session_cycle": 342.536,
"bm1366_work_encoding": 318.703,
"bm13xx_crc16": 294.818,
"bm13xx_crc5": 43.289,
"difficulty_target": 909.418,
"hal_socket_exchange": 41358.24,
"power_policy": 0.916,
"scrypt_share_verification": 363389.156,
"share_verification": 1773.295,
"stratum_accept_parse": 543.03,
"stratum_authorize_format": 858.969,
"stratum_configure_format": 1298.086,
"stratum_configure_parse": 2120.089,
"stratum_control_parse": 607.363,
"stratum_header": 6954.921,
"stratum_job_issue": 5228.494,
"stratum_notify_parse": 2059.438,
"stratum_socket_round_trip": 45648.118,
"stratum_submission": 727.713,
"stratum_subscribe_format": 731.331,
"stratum_subscription_parse": 1136.976,
"target_matrix": 41.489
},
"bench_improvement_pct": -18.46436035258768,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5802,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "484f479b90eff4fcc7772d323ff4c9b6a4b93771",
"timestamp": "2026-11-12T22:58:16+00:00",
"metrics": {
"tests": 252,
"line_coverage_pct": 85.7,
"bench_coverage_pct": 11.0,
"bench_ns_per_op": {
"bm1362_commands": 275.944,
"bm1362_job_encoding": 312.568,
"bm1362_work_encoding": 326.845,
"bm1366_captured_report_poll": 1718.903,
"bm1366_report_decode": 135.625,
"bm1366_session_cycle": 378.843,
"bm1366_work_encoding": 325.481,
"bm13xx_crc16": 331.899,
"bm13xx_crc5": 62.62,
"difficulty_target": 861.822,
"hal_socket_exchange": 33430.247,
"power_policy": 1.164,
"scrypt_share_verification": 406989.328,
"share_verification": 1563.182,
"stratum_accept_parse": 666.681,
"stratum_authorize_format": 1155.103,
"stratum_configure_format": 1917.635,
"stratum_configure_parse": 2337.488,
"stratum_control_parse": 913.604,
"stratum_header": 8352.213,
"stratum_job_issue": 5823.769,
"stratum_notify_parse": 2406.618,
"stratum_socket_round_trip": 66469.58,
"stratum_submission": 865.538,
"stratum_subscribe_format": 1011.42,
"stratum_subscription_parse": 1294.617,
"target_matrix": 55.748
},
"bench_improvement_pct": null,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "Intel(R) Xeon(R) CPU E5-2620 v2 @ 2.10GHz",
"logical_cpus": 4
},
"lines_of_code": 20375,
"dependencies": 60,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,38 +0,0 @@
{
"sha": "5aab1e0131f1b86ef568c59e06a1d68b39a97dc7",
"timestamp": "2026-10-17T01:14:10+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.4,
"bench_coverage_pct": 35.2,
"bench_ns_per_op": {
"bm1362_commands": 181.12,
"bm1362_job_encoding": 212.353,
"bm1366_report_decode": 83.909,
"bm1366_session_cycle": 217.569,
"bm1366_work_encoding": 218.388,
"difficulty_target": 692.324,
"power_policy": 0.845,
"scrypt_share_verification": 298371.453,
"share_verification": 934.966,
"stratum_authorize_format": 783.436,
"stratum_configure_parse": 1568.098,
"stratum_control_parse": 852.454,
"stratum_header": 5480.384,
"stratum_job_issue": 3591.099,
"stratum_notify_parse": 1770.242,
"stratum_submission": 555.39,
"target_matrix": 34.08
},
"bench_improvement_pct": -1.2856187431122177,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5227,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,39 +0,0 @@
{
"sha": "5faeb774113d09d150ad8cfa5bee3951fae0d8e8",
"timestamp": "2026-10-17T04:02:08+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 118.16,
"bm1362_job_encoding": 140.788,
"bm1366_report_decode": 54.245,
"bm1366_session_cycle": 154.963,
"bm1366_work_encoding": 141.589,
"difficulty_target": 323.774,
"power_policy": 0.461,
"scrypt_share_verification": 186319.641,
"share_verification": 550.887,
"stratum_authorize_format": 294.061,
"stratum_configure_parse": 711.528,
"stratum_control_parse": 254.993,
"stratum_header": 2969.331,
"stratum_job_issue": 1825.709,
"stratum_notify_parse": 689.88,
"stratum_submission": 249.138,
"target_matrix": 19.153
},
"bench_improvement_pct": null,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "871a2cd3f782bbe4ca171fb89f4a9a546e07e0d7",
"timestamp": "2026-10-19T03:52:23+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 120.796,
"bm1362_job_encoding": 141.136,
"bm1362_work_encoding": 143.088,
"bm1366_captured_report_poll": 638.604,
"bm1366_report_decode": 54.562,
"bm1366_session_cycle": 174.175,
"bm1366_work_encoding": 144.601,
"bm13xx_crc16": 155.011,
"bm13xx_crc5": 25.634,
"difficulty_target": 333.155,
"hal_socket_exchange": 15028.565,
"power_policy": 0.478,
"scrypt_share_verification": 188387.836,
"share_verification": 576.683,
"stratum_accept_parse": 182.574,
"stratum_authorize_format": 298.237,
"stratum_configure_format": 565.741,
"stratum_configure_parse": 717.721,
"stratum_control_parse": 257.534,
"stratum_header": 2940.601,
"stratum_job_issue": 1793.692,
"stratum_notify_parse": 697.719,
"stratum_socket_round_trip": 15954.266,
"stratum_submission": 252.056,
"stratum_subscribe_format": 258.863,
"stratum_subscription_parse": 429.497,
"target_matrix": 18.526
},
"bench_improvement_pct": 0.9487568131159643,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5837,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,27 +0,0 @@
{
"sha": "a2d03658137b3426d3feb0311dc74640a2a4a9fd",
"timestamp": "2026-10-16T07:36:30+00:00",
"metrics": {
"tests": 30,
"line_coverage_pct": 86.5,
"bench_coverage_pct": 46.9,
"bench_ns_per_op": {
"bm1366_session_cycle": 153.229,
"bm1366_work_encoding": 160.908,
"power_policy": 0.616,
"bm1366_report_decode": 57.895,
"difficulty_target": 351.668,
"stratum_control_parse": 411.535,
"share_verification": 701.448,
"target_matrix": 20.303,
"stratum_header": 3184.797,
"stratum_notify_parse": 792.362,
"stratum_submission": 463.577
},
"bench_improvement_pct": null,
"lines_of_code": 2458,
"dependencies": 11,
"code_quality": "A",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "a4f499ce124412ddd34d42b8375c5625c6a64f3b",
"timestamp": "2026-10-17T15:28:32+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 120.203,
"bm1362_job_encoding": 142.7,
"bm1362_work_encoding": 142.153,
"bm1366_captured_report_poll": 649.73,
"bm1366_report_decode": 55.762,
"bm1366_session_cycle": 179.294,
"bm1366_work_encoding": 144.509,
"bm13xx_crc16": 158.162,
"bm13xx_crc5": 26.395,
"difficulty_target": 336.608,
"hal_socket_exchange": 15741.728,
"power_policy": 0.491,
"scrypt_share_verification": 198707.742,
"share_verification": 584.64,
"stratum_accept_parse": 182.362,
"stratum_authorize_format": 299.346,
"stratum_configure_format": 501.471,
"stratum_configure_parse": 708.574,
"stratum_control_parse": 260.388,
"stratum_header": 3092.729,
"stratum_job_issue": 1895.633,
"stratum_notify_parse": 709.715,
"stratum_socket_round_trip": 16433.906,
"stratum_submission": 246.741,
"stratum_subscribe_format": 253.29,
"stratum_subscription_parse": 415.463,
"target_matrix": 19.494
},
"bench_improvement_pct": 9.825072287666742,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5796,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "ae7745772ae51cc196a60bd433b3d933ed512eae",
"timestamp": "2026-10-19T05:01:58+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 280.556,
"bm1362_job_encoding": 331.654,
"bm1362_work_encoding": 279.539,
"bm1366_captured_report_poll": 1519.435,
"bm1366_report_decode": 133.258,
"bm1366_session_cycle": 447.576,
"bm1366_work_encoding": 269.042,
"bm13xx_crc16": 341.921,
"bm13xx_crc5": 55.941,
"difficulty_target": 1096.821,
"hal_socket_exchange": 46202.277,
"power_policy": 1.47,
"scrypt_share_verification": 497556.016,
"share_verification": 1543.566,
"stratum_accept_parse": 736.83,
"stratum_authorize_format": 920.035,
"stratum_configure_format": 2086.944,
"stratum_configure_parse": 2439.709,
"stratum_control_parse": 998.693,
"stratum_header": 8158.071,
"stratum_job_issue": 6180.409,
"stratum_notify_parse": 2500.056,
"stratum_socket_round_trip": 66973.135,
"stratum_submission": 1065.12,
"stratum_subscribe_format": 1295.934,
"stratum_subscription_parse": 1605.76,
"target_matrix": 88.817
},
"bench_improvement_pct": -26.37049020368169,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5837,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "b1eb641729e77c6451bfe646288d36dd4364aa7e",
"timestamp": "2026-10-16T19:19:28+00:00",
"metrics": {
"tests": 62,
"line_coverage_pct": 88.5,
"bench_coverage_pct": 35.5,
"bench_ns_per_op": {
"bm1366_report_decode": 80.406,
"bm1366_session_cycle": 229.356,
"bm1366_work_encoding": 205.691,
"difficulty_target": 669.365,
"power_policy": 0.849,
"scrypt_share_verification": 286639.148,
"share_verification": 882.469,
"stratum_authorize_format": 697.138,
"stratum_configure_parse": 1646.612,
"stratum_control_parse": 822.593,
"stratum_header": 5209.663,
"stratum_job_issue": 3602.652,
"stratum_notify_parse": 1521.427,
"stratum_submission": 568.883,
"target_matrix": 34.432
},
"bench_improvement_pct": 5.279824105907481,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 4914,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "b9686af9c8f80feaf6dc893699e4d975a59f5949",
"timestamp": "2026-10-17T10:17:58+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 174.547,
"bm1362_job_encoding": 214.201,
"bm1362_work_encoding": 236.065,
"bm1366_captured_report_poll": 986.53,
"bm1366_report_decode": 83.521,
"bm1366_session_cycle": 279.829,
"bm1366_work_encoding": 271.038,
"bm13xx_crc16": 290.546,
"bm13xx_crc5": 49.464,
"difficulty_target": 869.765,
"hal_socket_exchange": 35832.668,
"power_policy": 1.13,
"scrypt_share_verification": 290309.086,
"share_verification": 886.321,
"stratum_accept_parse": 426.084,
"stratum_authorize_format": 680.234,
"stratum_configure_format": 1204.431,
"stratum_configure_parse": 1749.496,
"stratum_control_parse": 562.863,
"stratum_header": 4986.07,
"stratum_job_issue": 3828.325,
"stratum_notify_parse": 1794.247,
"stratum_socket_round_trip": 46774.744,
"stratum_submission": 647.318,
"stratum_subscribe_format": 601.506,
"stratum_subscription_parse": 1172.352,
"target_matrix": 34.356
},
"bench_improvement_pct": -9.836890264091615,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5787,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "c13db2a5ba9b73ac1fa5b478b7a3032d1810b336",
"timestamp": "2026-10-19T03:40:55+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 224.556,
"bm1362_job_encoding": 300.77,
"bm1362_work_encoding": 246.604,
"bm1366_captured_report_poll": 1238.499,
"bm1366_report_decode": 119.342,
"bm1366_session_cycle": 274.465,
"bm1366_work_encoding": 266.664,
"bm13xx_crc16": 309.028,
"bm13xx_crc5": 52.466,
"difficulty_target": 973.075,
"hal_socket_exchange": 37957.504,
"power_policy": 1.147,
"scrypt_share_verification": 284277.391,
"share_verification": 1321.256,
"stratum_accept_parse": 596.537,
"stratum_authorize_format": 1332.566,
"stratum_configure_format": 2032.848,
"stratum_configure_parse": 2749.941,
"stratum_control_parse": 797.614,
"stratum_header": 6383.481,
"stratum_job_issue": 5409.785,
"stratum_notify_parse": 2303.943,
"stratum_socket_round_trip": 46976.996,
"stratum_submission": 797.677,
"stratum_subscribe_format": 750.893,
"stratum_subscription_parse": 917.124,
"target_matrix": 42.305
},
"bench_improvement_pct": -4.082790698433242,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5802,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "c7cda3064ec8e51072abd598f714dbee41436f44",
"timestamp": "2026-11-16T22:05:06+00:00",
"metrics": {
"tests": 252,
"line_coverage_pct": 85.7,
"bench_coverage_pct": 11.0,
"bench_ns_per_op": {
"bm1362_commands": 118.822,
"bm1362_job_encoding": 146.111,
"bm1362_work_encoding": 143.098,
"bm1366_captured_report_poll": 651.914,
"bm1366_report_decode": 54.195,
"bm1366_session_cycle": 178.176,
"bm1366_work_encoding": 140.373,
"bm13xx_crc16": 153.906,
"bm13xx_crc5": 25.409,
"difficulty_target": 330.048,
"hal_socket_exchange": 15816.499,
"power_policy": 0.478,
"scrypt_share_verification": 193545.438,
"share_verification": 554.416,
"stratum_accept_parse": 184.312,
"stratum_authorize_format": 288.78,
"stratum_configure_format": 497.344,
"stratum_configure_parse": 731.367,
"stratum_control_parse": 275.494,
"stratum_header": 2927.859,
"stratum_job_issue": 1931.006,
"stratum_notify_parse": 734.993,
"stratum_socket_round_trip": 16695.255,
"stratum_submission": 241.16,
"stratum_subscribe_format": 243.119,
"stratum_subscription_parse": 397.224,
"target_matrix": 18.798
},
"bench_improvement_pct": 0.01469655302288628,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 20375,
"dependencies": 60,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "cc14543ced1621d4565882a311773c48f5d3614c",
"timestamp": "2026-11-12T21:22:45+00:00",
"metrics": {
"tests": 250,
"line_coverage_pct": 85.6,
"bench_coverage_pct": 11.1,
"bench_ns_per_op": {
"bm1362_commands": 225.644,
"bm1362_job_encoding": 328.479,
"bm1362_work_encoding": 309.737,
"bm1366_captured_report_poll": 1359.428,
"bm1366_report_decode": 114.877,
"bm1366_session_cycle": 389.925,
"bm1366_work_encoding": 331.867,
"bm13xx_crc16": 290.487,
"bm13xx_crc5": 54.944,
"difficulty_target": 1124.235,
"hal_socket_exchange": 45278.473,
"power_policy": 1.052,
"scrypt_share_verification": 418213.531,
"share_verification": 1196.389,
"stratum_accept_parse": 657.239,
"stratum_authorize_format": 1235.067,
"stratum_configure_format": 1755.29,
"stratum_configure_parse": 2531.665,
"stratum_control_parse": 800.904,
"stratum_header": 7417.373,
"stratum_job_issue": 5545.003,
"stratum_notify_parse": 2787.602,
"stratum_socket_round_trip": 57270.365,
"stratum_submission": 827.388,
"stratum_subscribe_format": 908.918,
"stratum_subscription_parse": 1413.105,
"target_matrix": 52.823
},
"bench_improvement_pct": -37.70168914723892,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 20288,
"dependencies": 60,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,39 +0,0 @@
{
"sha": "e83ced0e20ca4de09cdf967d051da4a4c678a7b8",
"timestamp": "2026-10-17T04:04:54+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 224.772,
"bm1362_job_encoding": 223.29,
"bm1366_report_decode": 86.828,
"bm1366_session_cycle": 238.508,
"bm1366_work_encoding": 276.985,
"difficulty_target": 741.29,
"power_policy": 1.119,
"scrypt_share_verification": 323664.125,
"share_verification": 909.603,
"stratum_authorize_format": 805.021,
"stratum_configure_parse": 1718.245,
"stratum_control_parse": 709.261,
"stratum_header": 5112.093,
"stratum_job_issue": 3901.994,
"stratum_notify_parse": 1956.082,
"stratum_submission": 556.537,
"target_matrix": 32.949
},
"bench_improvement_pct": -13.93138021432414,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "e8faf398f5fa947cedf9f6ed1d96c4b06a2bc9fe",
"timestamp": "2026-10-17T09:20:34+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.3,
"bench_coverage_pct": 41.3,
"bench_ns_per_op": {
"bm1362_commands": 130.267,
"bm1362_job_encoding": 148.2,
"bm1362_work_encoding": 145.577,
"bm1366_captured_report_poll": 670.107,
"bm1366_report_decode": 57.707,
"bm1366_session_cycle": 182.859,
"bm1366_work_encoding": 148.095,
"bm13xx_crc16": 162.08,
"bm13xx_crc5": 26.493,
"difficulty_target": 350.947,
"hal_socket_exchange": 15814.126,
"power_policy": 0.503,
"scrypt_share_verification": 201815.781,
"share_verification": 606.034,
"stratum_accept_parse": 198.899,
"stratum_authorize_format": 469.782,
"stratum_configure_format": 606.131,
"stratum_configure_parse": 754.196,
"stratum_control_parse": 276.155,
"stratum_header": 3225.103,
"stratum_job_issue": 2011.455,
"stratum_notify_parse": 772.011,
"stratum_socket_round_trip": 21484.808,
"stratum_submission": 474.468,
"stratum_subscribe_format": 285.806,
"stratum_subscription_parse": 611.025,
"target_matrix": 24.21
},
"bench_improvement_pct": -7.99990807179019,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 7 8745H w/ Radeon 780M Graphics",
"logical_cpus": 4
},
"lines_of_code": 5787,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,49 +0,0 @@
{
"sha": "e928140351830bac139efb98820e53804636c893",
"timestamp": "2026-10-21T12:04:09+00:00",
"metrics": {
"tests": 73,
"line_coverage_pct": 86.4,
"bench_coverage_pct": 41.2,
"bench_ns_per_op": {
"bm1362_commands": 179.018,
"bm1362_job_encoding": 205.43,
"bm1362_work_encoding": 227.761,
"bm1366_captured_report_poll": 987.287,
"bm1366_report_decode": 104.075,
"bm1366_session_cycle": 291.804,
"bm1366_work_encoding": 240.474,
"bm13xx_crc16": 321.653,
"bm13xx_crc5": 46.539,
"difficulty_target": 896.713,
"hal_socket_exchange": 34825.955,
"power_policy": 0.833,
"scrypt_share_verification": 300374.305,
"share_verification": 889.826,
"stratum_accept_parse": 460.427,
"stratum_authorize_format": 838.222,
"stratum_configure_format": 1193.101,
"stratum_configure_parse": 1507.419,
"stratum_control_parse": 595.072,
"stratum_header": 4761.147,
"stratum_job_issue": 4159.136,
"stratum_notify_parse": 1926.673,
"stratum_socket_round_trip": 50607.73,
"stratum_submission": 548.007,
"stratum_subscribe_format": 596.867,
"stratum_subscription_parse": 886.226,
"target_matrix": 32.376
},
"bench_improvement_pct": 32.8319410335087,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5841,
"dependencies": 11,
"code_quality": "A",
"quality_scope": "main CI passed cargo fmt and warnings-denied Clippy on all targets",
"license": "MIT"
}
}
@@ -1,38 +0,0 @@
{
"sha": "ea8030b707605cc7f974773438aab1a4f369b2ad",
"timestamp": "2026-10-17T01:17:31+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.2,
"bench_coverage_pct": 34.9,
"bench_ns_per_op": {
"bm1362_commands": 164.352,
"bm1362_job_encoding": 201.856,
"bm1366_report_decode": 108.608,
"bm1366_session_cycle": 301.841,
"bm1366_work_encoding": 280.799,
"difficulty_target": 951.712,
"power_policy": 1.058,
"scrypt_share_verification": 347436.078,
"share_verification": 920.142,
"stratum_authorize_format": 670.238,
"stratum_configure_parse": 1618.133,
"stratum_control_parse": 675.35,
"stratum_header": 4941.007,
"stratum_job_issue": 5048.704,
"stratum_notify_parse": 1751.053,
"stratum_submission": 759.693,
"target_matrix": 32.171
},
"bench_improvement_pct": -11.111256562965927,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5249,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "ebea5f5cfd994118b7fa5b5870863df7bb3ede3a",
"timestamp": "2026-10-16T19:15:47+00:00",
"metrics": {
"tests": 62,
"line_coverage_pct": 88.5,
"bench_coverage_pct": 35.5,
"bench_ns_per_op": {
"bm1366_report_decode": 105.816,
"bm1366_session_cycle": 248.387,
"bm1366_work_encoding": 225.861,
"difficulty_target": 696.309,
"power_policy": 0.838,
"scrypt_share_verification": 269455.297,
"share_verification": 881.432,
"stratum_authorize_format": 740.798,
"stratum_configure_parse": 2156.62,
"stratum_control_parse": 754.595,
"stratum_header": 5139.92,
"stratum_job_issue": 3880.848,
"stratum_notify_parse": 2049.311,
"stratum_submission": 564.143,
"target_matrix": 31.667
},
"bench_improvement_pct": null,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 4914,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "f1b4780e2c29545f999a32d082d53d981cde1eab",
"timestamp": "2026-10-17T01:10:07+00:00",
"metrics": {
"tests": 68,
"line_coverage_pct": 87.4,
"bench_coverage_pct": 32.9,
"bench_ns_per_op": {
"bm1366_report_decode": 85.369,
"bm1366_session_cycle": 217.528,
"bm1366_work_encoding": 211.19,
"difficulty_target": 699.086,
"power_policy": 0.833,
"scrypt_share_verification": 289038.242,
"share_verification": 1156.075,
"stratum_authorize_format": 704.473,
"stratum_configure_parse": 1625.25,
"stratum_control_parse": 597.014,
"stratum_header": 5390.022,
"stratum_job_issue": 3546.33,
"stratum_notify_parse": 2066.816,
"stratum_submission": 627.814,
"target_matrix": 32.316
},
"bench_improvement_pct": -2.9414495847373345,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5227,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
@@ -1,36 +0,0 @@
{
"sha": "f6889940c3bc8f5f2d85ee45d992f485e2f00df9",
"timestamp": "2026-10-17T01:06:27+00:00",
"metrics": {
"tests": 62,
"line_coverage_pct": 86.7,
"bench_coverage_pct": 34.7,
"bench_ns_per_op": {
"bm1366_report_decode": 80.39,
"bm1366_session_cycle": 217.507,
"bm1366_work_encoding": 226.831,
"difficulty_target": 722.424,
"power_policy": 0.816,
"scrypt_share_verification": 268871.328,
"share_verification": 877.36,
"stratum_authorize_format": 720.309,
"stratum_configure_parse": 1798.745,
"stratum_control_parse": 608.061,
"stratum_header": 5195.553,
"stratum_job_issue": 4198.027,
"stratum_notify_parse": 1548.651,
"stratum_submission": 637.805,
"target_matrix": 32.238
},
"bench_improvement_pct": -0.8416320684715105,
"bench_host": {
"architecture": "x86_64",
"cpu_model": "AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx",
"logical_cpus": 8
},
"lines_of_code": 5000,
"dependencies": 11,
"code_quality": "B",
"license": "MIT"
}
}
-1103
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="102" height="20" role="img" aria-label="CI main: last completed attempt fail (run 13252)"><title>CI main: last completed attempt fail (run 13252)</title><rect width="102" height="20" rx="3" fill="#555"/><path d="M39 0h60a3 3 0 0 1 3 3v14a3 3 0 0 1-3 3H39z" fill="#d1242f"/><text x="20" y="14" fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">CI</text><text x="70" y="14" fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">fail</text></svg>

Before

Width:  |  Height:  |  Size: 533 B

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

Before

Width:  |  Height:  |  Size: 531 B

+19
View File
@@ -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}
}
]
}
+618
View File
@@ -0,0 +1,618 @@
{
"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/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": []
}
+589
View File
@@ -0,0 +1,589 @@
// SPDX-License-Identifier: MIT
//! Process wiring: start the API and UI servers and publish the hardware snapshot.
//!
//! The binary and the tests use the same function, so the wiring that CI exercises is the wiring
//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover
//! ephemeral ports instead of guessing them.
use crate::detect::{
run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget,
SensorTopology,
};
use crate::fanmap::{FanMap, MapThresholds, SweepConfig};
use crate::fanmap_store::ensure_map;
use crate::fault::FaultPolicy;
use crate::hal_wire::{HalClient, HalError};
use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus};
use crate::profiles::{ProfileDb, ProfileError};
use crate::runtime::MinerRuntime;
use crate::tuning::{PidConfig, TuningTarget};
use crate::web;
use std::fmt;
use std::io;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Duration;
/// Bound servers and their worker threads.
pub struct Servers {
pub api: Option<SocketAddr>,
pub web: Option<SocketAddr>,
handles: Vec<JoinHandle<()>>,
}
impl Servers {
/// Addresses actually bound, which matters when port 0 was requested.
pub fn addresses(&self) -> (Option<SocketAddr>, Option<SocketAddr>) {
(self.api, self.web)
}
/// Wait for the workers. Only useful in tests; the binary runs until it is killed.
pub fn join(self) {
for handle in self.handles {
let _ = handle.join();
}
}
}
/// Bind and start the cgminer-style API and the web UI, each when an address is given.
pub fn start(
status: Arc<MiningStatus>,
api: Option<SocketAddr>,
web_bind: Option<SocketAddr>,
) -> io::Result<Servers> {
let api_listener = match api {
Some(address) => Some(bind_local(address)?),
None => None,
};
let api_address = api_listener
.as_ref()
.map(|listener| listener.local_addr())
.transpose()?;
let web_listener = match web_bind {
Some(address) => Some(TcpListener::bind(address)?),
None => None,
};
let web_address = web_listener
.as_ref()
.map(|listener| listener.local_addr())
.transpose()?;
let mut handles = Vec::new();
if let Some(listener) = api_listener {
let snapshot = Arc::clone(&status);
handles.push(std::thread::spawn(move || {
if let Err(error) = serve(listener, snapshot) {
eprintln!("management API stopped: {error}");
}
}));
}
if let Some(listener) = web_listener {
let snapshot = Arc::clone(&status);
handles.push(std::thread::spawn(move || {
if let Err(error) = web::serve_listener(listener, snapshot) {
eprintln!("web UI stopped: {error}");
}
}));
}
Ok(Servers {
api: api_address,
web: web_address,
handles,
})
}
/// Build the API snapshot from the live runtime.
pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot {
let plan = runtime.plan();
HardwareSnapshot {
plan: plan.clone(),
active_chains: runtime.active_chains(),
stopped: runtime.stop_reason().map(|reason| match reason {
crate::fault::StopReason::Temperature => "temperature",
crate::fault::StopReason::NoChainsLeft => "no chains left",
}),
frequency_mhz: runtime.operating_point().frequency_mhz,
target: target.to_owned(),
}
}
/// Everything a boot needs besides the backend.
#[derive(Clone, Debug, PartialEq)]
pub struct BootConfig {
pub profile_db_json: String,
pub chain_ports: Vec<u8>,
pub sensor: SensorTopology,
pub budget: ProbeBudget,
pub fan_zones: Vec<FanZone>,
pub target: TuningTarget,
pub pid: PidConfig,
pub ceiling_mc: i32,
pub fault_policy: FaultPolicy,
}
/// Why boot did not reach a running runtime.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BootError<E> {
Profile(ProfileError),
Detection(DetectionFailure<E>),
/// The board backend could not be reached or refused an operation.
Backend(E),
}
impl<E: fmt::Debug> fmt::Display for BootError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Profile(error) => write!(f, "profile database rejected: {error:?}"),
Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"),
Self::Backend(error) => write!(f, "hardware backend failed: {error:?}"),
}
}
}
impl<E: fmt::Debug> std::error::Error for BootError<E> {}
/// Operator target in the form the API and UI report.
pub fn target_label(target: &TuningTarget) -> String {
match *target {
TuningTarget::PowerW(watts) => format!("power:{watts:.0}"),
TuningTarget::HashrateThs(rate) => format!("hashrate:{rate:.0}"),
TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"),
TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"),
}
}
/// Detect, decide, and publish: the sequence a family image runs at start-up.
pub fn boot<B: DetectionBackend>(
backend: &mut B,
config: &BootConfig,
status: &MiningStatus,
) -> Result<MinerRuntime, BootError<B::Error>> {
let db = ProfileDb::from_json(&config.profile_db_json).map_err(BootError::Profile)?;
let request = DetectionRequest {
chain_ports: &config.chain_ports,
budget: config.budget,
sensor: config.sensor,
fan_zones: config.fan_zones.clone(),
};
let plan = run_detection(backend, &db, &request).map_err(BootError::Detection)?;
let runtime = MinerRuntime::new(
plan,
config.fault_policy,
config.target,
config.pid,
config.ceiling_mc,
);
status.set_hardware(snapshot(&runtime, &target_label(&config.target)));
Ok(runtime)
}
/// A boot over the real local HAL contract, including the one-time fan sweep.
pub struct HalBoot<'a> {
pub config: &'a BootConfig,
pub sweep: SweepConfig,
pub thresholds: MapThresholds,
pub map_path: &'a Path,
}
/// Connect the board backend, detect, map the fans once, and publish.
///
/// This is the path an image takes on real hardware; the fakes in the tests speak the same HAL
/// protocol, so the wiring is exercised rather than assumed.
pub fn boot_from_hal(
socket: &Path,
settings: &HalBoot<'_>,
status: &MiningStatus,
) -> Result<(MinerRuntime, FanMap), BootError<HalError>> {
let mut client = HalClient::connect(socket).map_err(BootError::Backend)?;
let zone_count = settings.sweep.zones;
let map = if zone_count == 0 {
FanMap::default()
} else {
ensure_map(
&mut client,
&settings.sweep,
settings.thresholds,
settings.map_path,
|millis| std::thread::sleep(std::time::Duration::from_millis(u64::from(millis))),
)
.map_err(|error| match error {
crate::fanmap_store::StoreError::Sweep(crate::fanmap::SweepError::Backend(error)) => {
BootError::Backend(error)
}
crate::fanmap_store::StoreError::Sweep(_) => {
BootError::Backend(HalError::Protocol("fan sweep configuration rejected"))
}
crate::fanmap_store::StoreError::Io(message) => {
BootError::Backend(HalError::Protocol(message))
}
})?
};
let config = BootConfig {
fan_zones: map.assignments.clone(),
..settings.config.clone()
};
let runtime = boot(&mut client, &config, status)?;
Ok((runtime, map))
}
/// Read one HTTP response body from a bound server, for health checks and tests.
pub fn http_get(address: SocketAddr, path: &str) -> io::Result<String> {
use std::io::{Read, Write};
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2))?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())?;
let mut reply = String::new();
stream.read_to_string(&mut reply)?;
Ok(reply)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::{
ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint,
};
use crate::detect::{ProbeOutcome, PsuCapability};
use crate::fanmap::{MapThresholds, SweepConfig};
use crate::fault::FaultPolicy;
use crate::tuning::{PidConfig, TuningTarget};
use std::io::{Read, Write};
fn runtime() -> MinerRuntime {
MinerRuntime::new(
HardwarePlan {
profile: "s19jpro-bm1362-pic".into(),
chip: ChipModel::Bm1362,
chains: vec![ChainReport {
index: 0,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom: EepromState::Absent,
response_per_mille: Some(950),
}],
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
operating_point: OperatingPoint {
voltage_mv: 1200,
frequency_mhz: 300,
confirmed: false,
},
psu: "APW12".into(),
fan_zones: vec![FanZone {
fan: 0,
zones: vec![0],
}],
},
FaultPolicy::default(),
TuningTarget::PowerW(2_400.0),
PidConfig::default(),
95_000,
)
}
#[test]
fn both_servers_serve_the_published_snapshot() {
let status = Arc::new(MiningStatus::new());
status.set_hardware(snapshot(&runtime(), "power:2400"));
let servers = start(
Arc::clone(&status),
Some("127.0.0.1:0".parse().unwrap()),
Some("127.0.0.1:0".parse().unwrap()),
)
.expect("start");
let (api, web) = servers.addresses();
let api = api.expect("api address");
let web = web.expect("web address");
let page = http_get(web, "/api/hardware").expect("web");
assert!(page.contains("s19jpro-bm1362-pic"));
assert!(page.contains("power:2400"));
let mut client =
TcpStream::connect_timeout(&api, Duration::from_secs(2)).expect("api connect");
client
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("timeout");
client.write_all(b"summary").expect("api write");
let mut summary = String::new();
client.read_to_string(&mut summary).expect("api read");
assert!(summary.contains("SUMMARY"));
}
#[test]
fn servers_are_optional() {
let status = Arc::new(MiningStatus::new());
let servers = start(status, None, None).expect("start");
assert_eq!(servers.addresses(), (None, None));
}
#[test]
fn the_snapshot_reports_runtime_state_not_boot_defaults() {
let mut runtime = runtime();
runtime.tick(&crate::runtime::Tick {
power_w: Some(1_000.0),
hashrate_ths: None,
hottest_mc: Some(60_000),
ambient_mc: None,
dt_s: 1.0,
});
let snapshot = snapshot(&runtime, "power:2400");
assert_eq!(snapshot.target, "power:2400");
assert_eq!(snapshot.active_chains, vec![0]);
assert!(snapshot.frequency_mhz > 300);
assert!(snapshot.stopped.is_none());
}
struct BootBackend {
outcome: ProbeOutcome,
psu: Option<PsuCapability>,
}
impl DetectionBackend for BootBackend {
type Error = ();
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
Ok(self.outcome)
}
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
Ok(EepromState::Absent)
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
Ok(self.psu.clone())
}
}
const DB: &str = r#"{"schema":1,"profiles":[{"name":"s19jpro-bm1362-pic",
"chip":"bm1362","sensor":"pic","chains":3,
"envelope":{"v_min_mv":1100,"v_max_mv":1500,"f_min_mhz":300,"f_max_mhz":700}}]}"#;
fn boot_config() -> BootConfig {
BootConfig {
profile_db_json: DB.into(),
chain_ports: vec![0, 1, 2],
sensor: SensorTopology::Pic,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target: TuningTarget::PowerW(2_400.0),
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: FaultPolicy::default(),
}
}
fn psu() -> PsuCapability {
PsuCapability {
name: "APW12".into(),
envelope: Envelope {
v_min_mv: 1200,
v_max_mv: 1600,
f_min_mhz: 0,
f_max_mhz: 1_000,
},
max_dc_watts: 3_600,
}
}
#[test]
fn boot_detects_and_publishes() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
psu: Some(psu()),
};
let status = MiningStatus::new();
let runtime = boot(&mut backend, &boot_config(), &status).expect("boot");
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
let document = status.hardware_document();
assert_eq!(document["available"], true);
assert_eq!(document["target"], "power:2400");
assert_eq!(document["psu"], "APW12");
}
#[test]
fn boot_refuses_an_unknown_chip() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Silent,
psu: Some(psu()),
};
let status = MiningStatus::new();
assert!(matches!(
boot(&mut backend, &boot_config(), &status),
Err(BootError::Detection(DetectionFailure::Refused(_)))
));
assert_eq!(status.hardware_document()["available"], false);
}
#[test]
fn boot_refuses_a_bad_profile_database() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
psu: Some(psu()),
};
let mut config = boot_config();
config.profile_db_json = "{\"schema\": 9}".into();
assert!(matches!(
boot(&mut backend, &config, &MiningStatus::new()),
Err(BootError::Profile(_))
));
}
#[test]
fn boot_refuses_a_missing_psu() {
let mut backend = BootBackend {
outcome: ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
psu: None,
};
assert!(matches!(
boot(&mut backend, &boot_config(), &MiningStatus::new()),
Err(BootError::Detection(DetectionFailure::Refused(_)))
));
}
#[test]
fn target_labels_are_stable() {
assert_eq!(target_label(&TuningTarget::PowerW(3_000.0)), "power:3000");
assert_eq!(
target_label(&TuningTarget::HashrateThs(200.0)),
"hashrate:200"
);
assert_eq!(
target_label(&TuningTarget::AmbientC { margin_mc: 20_000 }),
"ambient:20000"
);
assert_eq!(
target_label(&TuningTarget::MaxFan { max_pwm: 100 }),
"fan:100"
);
}
fn hal_server(socket: std::path::PathBuf) -> std::thread::JoinHandle<()> {
use std::io::{Read, Write};
use std::os::unix::net::UnixListener;
let listener = UnixListener::bind(&socket).expect("bind hal");
std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
loop {
let mut header = [0_u8; 16];
if stream.read_exact(&mut header).is_err() {
return;
}
let opcode = header[5];
let sequence = header[8..12].to_vec();
let length =
u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && stream.read_exact(&mut payload).is_err() {
return;
}
let body: Vec<u8> = match opcode {
// CAPABILITIES: chain probe, EEPROM, PSU identity.
7 => {
let mut body = vec![0_u8];
body.extend_from_slice(&7_u32.to_le_bytes());
body
}
// PROBE_CHAIN: identified, bm1362, 126 chips.
8 => vec![0, 0, 1, 126, 0],
// READ_EEPROM: absent.
9 => vec![0, 1],
// IDENTIFY_PSU: APW12 with its envelope.
10 => {
let name = b"APW12";
let mut body = vec![0_u8, name.len() as u8];
body.extend_from_slice(name);
for word in [1200_u16, 1600, 0, 1000, 3600] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
_ => vec![1],
};
let mut out = [0_u8; 16];
out[..4].copy_from_slice(b"ALKH");
out[4] = 1;
out[5] = opcode;
out[6..8].copy_from_slice(&1_u16.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
if stream.write_all(&out).is_err() || stream.write_all(&body).is_err() {
return;
}
}
})
}
#[test]
fn boot_over_the_hal_socket_detects_and_publishes() {
let base = std::env::temp_dir().join(format!("alkane-hal-{}", std::process::id()));
let socket = base.with_extension("sock");
let map_path = base.with_extension("map.json");
let _ = std::fs::remove_file(&socket);
let server = hal_server(socket.clone());
let status = MiningStatus::new();
let config = boot_config();
let settings = HalBoot {
config: &config,
sweep: SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: MapThresholds::default(),
map_path: &map_path,
};
let (runtime, map) = boot_from_hal(&socket, &settings, &status).expect("boot over hal");
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
assert!(map.assignments.is_empty());
let document = status.hardware_document();
assert_eq!(document["available"], true);
assert_eq!(document["psu"], "APW12");
assert_eq!(document["chip"], "bm1362");
let _ = std::fs::remove_file(&socket);
let _ = server.join();
}
#[test]
fn boot_over_a_missing_socket_is_a_backend_error() {
let socket =
std::env::temp_dir().join(format!("alkane-missing-{}.sock", std::process::id()));
let status = MiningStatus::new();
let config = boot_config();
let settings = HalBoot {
config: &config,
sweep: SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: MapThresholds::default(),
map_path: &socket,
};
assert!(matches!(
boot_from_hal(&socket, &settings, &status),
Err(BootError::Backend(_))
));
}
}
+21
View File
@@ -0,0 +1,21 @@
// 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()}));
}
+68
View File
@@ -0,0 +1,68 @@
// 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}");
}
}
+232
View File
@@ -0,0 +1,232 @@
// SPDX-License-Identifier: MIT
//! BM1362 frame encoding from captured command and job traffic.
//!
//! These pure encoders do not initialize a chain. PLL fields, voltage, and
//! model-specific operating points still require silicon-backed validation.
use crate::bm13xx::{crc16, crc5, reverse_words};
pub const JOB_BYTES: usize = 88;
pub const CHIP_ADDRESS_STEP: u8 = 2;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ModelGeometry {
chips_per_chain: u8,
ticket_mask: u8,
}
pub const S19J_PRO: ModelGeometry = ModelGeometry {
chips_per_chain: 126,
ticket_mask: 0x7f,
};
pub const S19J: ModelGeometry = ModelGeometry {
chips_per_chain: 108,
ticket_mask: 0x7f,
};
pub const S19_88: ModelGeometry = ModelGeometry {
chips_per_chain: 88,
ticket_mask: 0x3f,
};
impl ModelGeometry {
pub const fn new(chips_per_chain: u8, ticket_mask: u8) -> Option<Self> {
if chips_per_chain == 0 || chips_per_chain > 128 {
return None;
}
Some(Self {
chips_per_chain,
ticket_mask,
})
}
pub const fn chips_per_chain(self) -> u8 {
self.chips_per_chain
}
pub const fn ticket_mask(self) -> u8 {
self.ticket_mask
}
/// Addresses for an observed two-address-step enumeration walk.
pub fn chip_addresses(self) -> impl Iterator<Item = u8> {
(0..self.chips_per_chain).map(|index| index * CHIP_ADDRESS_STEP)
}
}
fn short_command(code: u8, address: u8, register: u8) -> [u8; 7] {
let mut frame = [0x55, 0xaa, code, 0x05, address, register, 0];
frame[6] = crc5(&frame[2..6]);
frame
}
fn long_command(code: u8, address: u8, register: u8, value: u32) -> [u8; 11] {
let mut frame = [0_u8; 11];
frame[..6].copy_from_slice(&[0x55, 0xaa, code, 0x09, address, register]);
frame[6..10].copy_from_slice(&value.to_be_bytes());
frame[10] = crc5(&frame[2..10]);
frame
}
pub fn chain_inactive() -> [u8; 7] {
short_command(0x53, 0, 0)
}
pub fn set_chip_address(address: u8) -> [u8; 7] {
short_command(0x40, address, 0)
}
pub fn read_register(address: u8, register: u8) -> [u8; 7] {
short_command(0x42, address, register)
}
pub fn read_register_all(register: u8) -> [u8; 7] {
short_command(0x52, 0, register)
}
pub fn write_register(address: u8, register: u8, value: u32) -> [u8; 11] {
long_command(0x41, address, register, value)
}
pub fn write_register_all(register: u8, value: u32) -> [u8; 11] {
long_command(0x51, 0, register, value)
}
/// Raw header fields in BM1362 wire order. The caller owns work-ID allocation
/// and must supply roots and hashes in the order established by its capture.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Job {
pub work_id: u8,
pub num_midstates: u8,
pub start_nonce: u32,
pub nbits: u32,
pub ntime: u32,
pub merkle_root: [u8; 32],
pub previous_hash: [u8; 32],
pub version: u32,
}
/// Encode the 88-byte SEND_JOB form with the true-length tag observed on wire.
pub fn encode_job(job: &Job) -> [u8; JOB_BYTES] {
let mut frame = [0_u8; JOB_BYTES];
frame[..6].copy_from_slice(&[0x55, 0xaa, 0x21, 0x56, job.work_id, job.num_midstates]);
frame[6..10].copy_from_slice(&job.start_nonce.to_le_bytes());
frame[10..14].copy_from_slice(&job.nbits.to_le_bytes());
frame[14..18].copy_from_slice(&job.ntime.to_le_bytes());
frame[18..50].copy_from_slice(&job.merkle_root);
frame[50..82].copy_from_slice(&job.previous_hash);
frame[82..86].copy_from_slice(&job.version.to_le_bytes());
let checksum = crc16(&frame[2..86]);
frame[86..88].copy_from_slice(&checksum.to_be_bytes());
frame
}
/// Encode one nonce-zero pool header in the observed raw-header job layout.
/// This covers work delivery; chain initialization still needs board evidence.
pub fn encode_work(header: &[u8; 80], work_id: u8) -> Option<[u8; JOB_BYTES]> {
if header[76..80] != [0; 4] || work_id & 7 != 0 {
return None;
}
Some(encode_job(&Job {
work_id,
num_midstates: 1,
start_nonce: 0,
nbits: u32::from_le_bytes(header[72..76].try_into().expect("nbits")),
ntime: u32::from_le_bytes(header[68..72].try_into().expect("ntime")),
merkle_root: reverse_words(&header[36..68]),
previous_hash: reverse_words(&header[4..36]),
version: u32::from_le_bytes(header[..4].try_into().expect("version")),
}))
}
/// BT8D for a 25 MHz input clock with BCLK_SEL=0. A model must still choose
/// the actual target baud and confirm switching on silicon.
pub fn bt8d_for_baud(baud: u32) -> Option<u8> {
if baud == 0 || baud > 3_125_000 {
return None;
}
let divider = 25_000_000_u64 / (8 * u64::from(baud));
u8::try_from(divider - 1).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captured_command_frames() {
assert_eq!(chain_inactive(), [0x55, 0xaa, 0x53, 5, 0, 0, 3]);
assert_eq!(set_chip_address(0), [0x55, 0xaa, 0x40, 5, 0, 0, 0x1c]);
assert_eq!(set_chip_address(8), [0x55, 0xaa, 0x40, 5, 8, 0, 7]);
assert_eq!(read_register_all(0), [0x55, 0xaa, 0x52, 5, 0, 0, 0x0a]);
assert_eq!(
read_register(0x40, 0x1c),
[0x55, 0xaa, 0x42, 5, 0x40, 0x1c, 0x0b]
);
assert_eq!(
write_register_all(0x80, 0),
[0x55, 0xaa, 0x51, 9, 0, 0x80, 0, 0, 0, 0, 0x1c]
);
assert_eq!(
write_register(0x40, 0x18, 0x7a31),
[0x55, 0xaa, 0x41, 9, 0x40, 0x18, 0, 0, 0x7a, 0x31, 0x11]
);
}
#[test]
fn model_address_limits() {
assert_eq!(ModelGeometry::new(0, 0), None);
assert_eq!(ModelGeometry::new(129, 0), None);
assert_eq!(
ModelGeometry::new(128, 0).unwrap().chip_addresses().last(),
Some(0xfe)
);
assert_eq!(S19J_PRO.chip_addresses().last(), Some(0xfa));
assert_eq!(S19J.chip_addresses().last(), Some(0xd6));
assert_eq!(S19_88.chip_addresses().last(), Some(0xae));
}
#[test]
fn job_frame_layout() {
let mut merkle_root = [0_u8; 32];
let mut previous_hash = [0_u8; 32];
for index in 0..32 {
merkle_root[index] = 0xa0 + index as u8;
previous_hash[index] = 0x10 + index as u8;
}
let frame = encode_job(&Job {
work_id: 8,
num_midstates: 1,
start_nonce: 0,
nbits: 0x1a1f_2c34,
ntime: 0x5e9b_3cd4,
merkle_root,
previous_hash,
version: 0x2000_0000,
});
assert_eq!(
&frame[..18],
&[
0x55, 0xaa, 0x21, 0x56, 8, 1, 0, 0, 0, 0, 0x34, 0x2c, 0x1f, 0x1a, 0xd4, 0x3c, 0x9b,
0x5e
]
);
assert_eq!(&frame[18..50], &merkle_root);
assert_eq!(&frame[50..82], &previous_hash);
assert_eq!(&frame[82..86], &[0, 0, 0, 0x20]);
assert_eq!(&frame[86..88], &[0xc2, 0xbd]);
assert_eq!(
u16::from_be_bytes([frame[86], frame[87]]),
crc16(&frame[2..86])
);
}
#[test]
fn baud_dividers() {
assert_eq!(bt8d_for_baud(0), None);
assert_eq!(bt8d_for_baud(3_000_000), Some(0));
assert_eq!(bt8d_for_baud(115_200), Some(26));
assert_eq!(bt8d_for_baud(1), None);
assert_eq!(bt8d_for_baud(3_125_001), None);
assert_eq!(bt8d_for_baud(u32::MAX), None);
}
}
+120
View File
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: MIT
//! BM1366 work and response framing. Nonces only come from a device or replay.
pub const WORK_BYTES: usize = 88;
pub const REPORT_BYTES: usize = 11;
pub use crate::bm13xx::crc16;
use crate::bm13xx::{crc5, reverse_words};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NonceReport {
pub nonce: u32,
pub work_id: u8,
pub version_field: u16,
pub chip_address: u8,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReportError {
Length,
Preamble,
RegisterResponse,
Checksum,
}
/// Encode a nonce-zero Bitcoin header for the observed 88-byte SEND_JOB form.
/// The low three work-ID bits are reserved by the BM1366 response format.
pub fn encode_work(header: &[u8; 80], work_id: u8) -> Option<[u8; WORK_BYTES]> {
if header[76..80] != [0; 4] || work_id & 7 != 0 {
return None;
}
let mut frame = [0_u8; WORK_BYTES];
frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]);
frame[4] = work_id;
// The captured 88-byte on-die-midstate job uses one midstate.
frame[5] = 1;
frame[10..14].copy_from_slice(&header[72..76]);
frame[14..18].copy_from_slice(&header[68..72]);
frame[18..50].copy_from_slice(&reverse_words(&header[36..68]));
frame[50..82].copy_from_slice(&reverse_words(&header[4..36]));
frame[82..86].copy_from_slice(&header[..4]);
let checksum = crc16(&frame[2..86]);
frame[86..88].copy_from_slice(&checksum.to_be_bytes());
Some(frame)
}
/// Parse an observed nonce report; register replies must use a separate path.
pub fn decode_nonce_report(frame: &[u8]) -> Result<NonceReport, ReportError> {
if frame.len() != REPORT_BYTES {
return Err(ReportError::Length);
}
if frame[..2] != [0xaa, 0x55] {
return Err(ReportError::Preamble);
}
if frame[10] & 0x80 == 0 {
return Err(ReportError::RegisterResponse);
}
if crc5(&frame[2..]) != 0 {
return Err(ReportError::Checksum);
}
Ok(NonceReport {
nonce: u32::from_le_bytes(frame[2..6].try_into().expect("four-byte nonce")),
chip_address: frame[6],
work_id: frame[7] & 0xf8,
version_field: u16::from_be_bytes(frame[8..10].try_into().expect("version field")),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crc16_reference_vector() {
assert_eq!(crc16(b"123456789"), 0x29b1);
}
#[test]
fn captured_work_and_response() {
let header: [u8; 80] = hex_header();
let frame = encode_work(&header, 0x18).unwrap();
assert_eq!(&frame[..5], &[0x55, 0xaa, 0x21, 0x54, 0x18]);
assert_eq!(frame[5], 1);
assert_eq!(
crc16(&frame[2..86]),
u16::from_be_bytes([frame[86], frame[87]])
);
assert_eq!(&frame[10..14], &header[72..76]);
assert_eq!(&frame[82..86], &header[..4]);
assert!(encode_work(&header, 0x19).is_none());
let mut with_nonce = header;
with_nonce[76] = 1;
assert!(encode_work(&with_nonce, 0x18).is_none());
let report = [
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
];
let parsed = decode_nonce_report(&report).unwrap();
assert_eq!(parsed.nonce, 0xedad_ff38);
assert_eq!(parsed.work_id, 0x18);
assert_eq!(parsed.version_field, 0x04b3);
let mut corrupt = report;
corrupt[4] ^= 1;
assert_eq!(decode_nonce_report(&corrupt), Err(ReportError::Checksum));
}
fn hex_header() -> [u8; 80] {
let input = concat!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
"b4213a43ae1052ebd44443068fe178e2c61ca4994846fd133addb04aab2b382c5",
"b4c74c1012e6a8f06021700000000"
);
let mut header = [0_u8; 80];
for (index, bytes) in input.as_bytes().chunks_exact(2).enumerate() {
let pair = std::str::from_utf8(bytes).unwrap();
header[index] = u8::from_str_radix(pair, 16).unwrap();
}
header
}
}
+203
View File
@@ -0,0 +1,203 @@
// SPDX-License-Identifier: MIT
//! BM1370 wire frames observed on an S21 Pro. This module does not control power.
use crate::bm13xx::{crc16, crc5};
pub use crate::bm1362::Job;
pub const JOB_BYTES: usize = 88;
pub const REPORT_BYTES: usize = 11;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NonceReport {
pub nonce: u32,
pub byte6: u8,
pub byte7: u8,
pub byte8: u8,
pub byte9: u8,
/// Raw trailer: bit 7 marks a nonce response; bits 4:0 carry CRC5.
/// No chip identity is inferred from this byte.
pub trailer: u8,
}
impl NonceReport {
/// Work ID observed in the Braiins S21 Pro capture. Chip and version
/// attribution remain unknown, and this has no accepted-share proof.
pub fn observed_work_id(&self) -> u8 {
(self.byte7 & 0xf0) >> 1
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReportError {
Length,
Preamble,
RegisterResponse,
Checksum,
}
/// Encode only the job shape observed in the S21 Pro capture. `Job` fields
/// are in wire order; this does not validate a pool header or start a chain.
pub fn encode_job(job: &Job) -> Option<[u8; JOB_BYTES]> {
if job.work_id & 7 != 0 || job.num_midstates != 1 || job.start_nonce != 0 {
return None;
}
let mut frame = crate::bm1362::encode_job(job);
frame[3] = 0x36;
let checksum = crc16(&frame[2..86]);
frame[86..88].copy_from_slice(&checksum.to_be_bytes());
Some(frame)
}
/// Keep the five trailing bytes raw. The work-ID expression is correlated with
/// same-UART jobs in one capture; chip and version mapping remain unverified.
/// The marker bit distinguishes nonce reports from register replies.
pub fn decode_nonce_report(frame: &[u8]) -> Result<NonceReport, ReportError> {
if frame.len() != REPORT_BYTES {
return Err(ReportError::Length);
}
if frame[..2] != [0xaa, 0x55] {
return Err(ReportError::Preamble);
}
if frame[10] & 0x80 == 0 {
return Err(ReportError::RegisterResponse);
}
if crc5(&frame[2..]) != 0 {
return Err(ReportError::Checksum);
}
Ok(NonceReport {
nonce: u32::from_le_bytes(frame[2..6].try_into().expect("four-byte nonce")),
byte6: frame[6],
byte7: frame[7],
byte8: frame[8],
byte9: frame[9],
trailer: frame[10],
})
}
#[cfg(test)]
mod tests {
use super::*;
// firmware-analysis/prong-b/s21-192/c2-steady.strace, SHA-256
// c0aac1222e05e95bdcbd1de5a8ee244a581256e8f28e3dadf5300df6110229c7.
const CAPTURED_JOB: &str = concat!(
"55aa21366001000000008f060217834f276af0f09aafc588165b7fbfc56f8f09a55d3d0de5",
"798bd87460278af180c4696fc200000000000000008af701003acc10cdebe5bc3c90f095e5",
"03c6b7de69ca8b5d00000020e769"
);
fn captured_bytes<const N: usize>(hex: &str) -> [u8; N] {
assert_eq!(hex.len(), N * 2);
let mut bytes = [0; N];
for (index, pair) in hex.as_bytes().chunks_exact(2).enumerate() {
bytes[index] = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap();
}
bytes
}
fn with_valid_crc(mut frame: [u8; REPORT_BYTES]) -> [u8; REPORT_BYTES] {
for checksum in 0..32 {
frame[10] = (frame[10] & 0xe0) | checksum;
if crc5(&frame[2..]) == 0 {
return frame;
}
}
panic!("no valid CRC5 trailer");
}
#[test]
fn live_job_matches_all_88_bytes() {
let captured = captured_bytes::<JOB_BYTES>(CAPTURED_JOB);
let mut merkle_root = [0; 32];
merkle_root.copy_from_slice(&captured[18..50]);
let mut previous_hash = [0; 32];
previous_hash.copy_from_slice(&captured[50..82]);
let job = Job {
work_id: captured[4],
num_midstates: captured[5],
start_nonce: u32::from_le_bytes(captured[6..10].try_into().unwrap()),
nbits: u32::from_le_bytes(captured[10..14].try_into().unwrap()),
ntime: u32::from_le_bytes(captured[14..18].try_into().unwrap()),
merkle_root,
previous_hash,
version: u32::from_le_bytes(captured[82..86].try_into().unwrap()),
};
assert_eq!(encode_job(&job), Some(captured));
let mut invalid = job;
invalid.work_id |= 1;
assert_eq!(encode_job(&invalid), None);
invalid = job;
invalid.num_midstates = 2;
assert_eq!(encode_job(&invalid), None);
invalid = job;
invalid.start_nonce = 1;
assert_eq!(encode_job(&invalid), None);
assert_eq!(
crc16(&captured[2..86]),
u16::from_be_bytes([captured[86], captured[87]])
);
}
#[test]
fn live_nonce_reports_preserve_raw_tags() {
for hex in [
"aa555804a92a041e133e86",
"aa55771def23001c16fc82",
"aa5574480ae6021417b492",
] {
let frame = captured_bytes::<REPORT_BYTES>(hex);
let report = decode_nonce_report(&frame).unwrap();
assert_eq!(
report.nonce,
u32::from_le_bytes(frame[2..6].try_into().unwrap())
);
assert_eq!(report.byte6, frame[6]);
assert_eq!(report.byte7, frame[7]);
assert_eq!(report.byte8, frame[8]);
assert_eq!(report.byte9, frame[9]);
assert_eq!(report.trailer, frame[10]);
}
}
#[test]
fn observed_work_id_matches_same_uart_job() {
// c2-steady.strace lines 1287 and 1352: job byte 4 is 0x10.
let frame = captured_bytes::<REPORT_BYTES>("aa554a3488c70022013291");
let report = decode_nonce_report(&frame).unwrap();
assert_eq!(report.observed_work_id(), 0x10);
assert_eq!(report.byte7, 0x22);
}
#[test]
fn invalid_report_fails_closed() {
let mut frame = captured_bytes::<REPORT_BYTES>("aa555804a92a041e133e86");
assert_eq!(decode_nonce_report(&frame[..10]), Err(ReportError::Length));
frame[0] = 0;
assert_eq!(decode_nonce_report(&frame), Err(ReportError::Preamble));
frame[0] = 0xaa;
frame[10] &= 0x60;
frame = with_valid_crc(frame);
assert_eq!(crc5(&frame[2..]), 0);
assert_eq!(
decode_nonce_report(&frame),
Err(ReportError::RegisterResponse)
);
frame[10] |= 0x80;
frame = with_valid_crc(frame);
frame[4] ^= 1;
assert_eq!(decode_nonce_report(&frame), Err(ReportError::Checksum));
}
#[test]
fn trailer_low_bits_are_checksum_not_chip_identity() {
let original = captured_bytes::<REPORT_BYTES>("aa555804a92a041e133e86");
let mut changed_nonce = original;
changed_nonce[2] ^= 1;
changed_nonce = with_valid_crc(changed_nonce);
assert_eq!(crc5(&changed_nonce[2..]), 0);
assert_ne!(changed_nonce[10] & 0x1f, original[10] & 0x1f);
assert_eq!(changed_nonce[10] & 0xe0, original[10] & 0xe0);
assert!(decode_nonce_report(&changed_nonce).is_ok());
}
}
+66
View File
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: MIT
//! Shared BM13xx wire checksums. This module never generates mining nonces.
/// Reverse the eight 32-bit header words for the observed SEND_JOB layout.
pub(crate) fn reverse_words(input: &[u8]) -> [u8; 32] {
let mut output = [0_u8; 32];
for index in 0..8 {
output[index * 4..index * 4 + 4].copy_from_slice(&input[(7 - index) * 4..(8 - index) * 4]);
}
output
}
/// CRC5 used by command and nonce-report frames, initial value 0x1f.
pub fn crc5(bytes: &[u8]) -> u8 {
let mut state = 0x1f_u8;
for &byte in bytes {
for bit in (0..8).rev() {
let feedback = ((state >> 4) ^ (byte >> bit)) & 1;
state = ((state << 1) | feedback) & 0x1f;
state ^= feedback << 2;
}
}
state
}
/// CRC16-CCITT-FALSE used by 88-byte SEND_JOB frames.
pub fn crc16(bytes: &[u8]) -> u16 {
let mut state = 0xffff_u16;
for &byte in bytes {
state ^= u16::from(byte) << 8;
for _ in 0..8 {
state = if state & 0x8000 == 0 {
state << 1
} else {
(state << 1) ^ 0x1021
};
}
}
state
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captured_command_checksums() {
let vectors: &[(&[u8], u8)] = &[
(&[0x53, 0x05, 0, 0], 0x03),
(&[0x40, 0x05, 0, 0], 0x1c),
(&[0x52, 0x05, 0, 0], 0x0a),
(&[0x40, 0x05, 8, 0], 0x07),
(&[0x42, 0x05, 0x40, 0x1c], 0x0b),
(&[0x51, 0x09, 0, 0x80, 0, 0, 0, 0], 0x1c),
(&[0x41, 0x09, 0x40, 0x18, 0, 0, 0x7a, 0x31], 0x11),
];
for &(body, expected) in vectors {
assert_eq!(crc5(body), expected);
}
}
#[test]
fn standard_crc16_check() {
assert_eq!(crc16(b"123456789"), 0x29b1);
}
}
+364
View File
@@ -0,0 +1,364 @@
// SPDX-License-Identifier: MIT
//! Schema-driven dashboard for the on-box UI.
//!
//! The sidebar, the tab strip and every settings control come from
//! `schema/alkane-bb.json` through `flare-ui` and `wschema`; this module is the
//! host boundary the crates expect: it owns the stored rows, applies a
//! submitted form only after `wschema` validates it, and keeps the JSON API as
//! the interface of record.
//!
//! Everything here is pure except `load` and `save`, which touch one file.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use maud::Markup;
use serde_json::{Map, Value};
use flare_ui::assets::PageAssets;
use flare_ui::nav::{self, AllowAll, AppSet, CapSet, NavContext, VisibleNav};
use flare_ui::url::Routes;
use flare_ui::render::{self, View};
use flare_ui::shell::{self, Active};
use flare_ui::tokens;
use wschema::effective::{self, Effective};
use wschema::model::{Document, Surface};
use wschema::validate::{Op, Rows};
/// The schema document is the single source of the UI.
pub const SCHEMA: &str = include_str!("../schema/alkane-bb.json");
/// Capabilities this board reports, which decide what the sidebar shows.
pub fn board_caps() -> CapSet {
CapSet::new(["hashboard", "psu", "fan-map", "cgminer-api"])
}
/// The dashboard: an effective schema plus the stored rows.
pub struct Dashboard {
effective: Result<Effective, String>,
rows: Rows,
path: PathBuf,
}
impl Dashboard {
/// Load the schema and the stored settings, defaulting absent rows to the
/// schema's own defaults.
pub fn load(path: impl AsRef<Path>) -> Dashboard {
let path = path.as_ref().to_path_buf();
let effective = Document::from_json(SCHEMA)
.map_err(|error| error.to_string())
.and_then(|doc| {
effective::merge(&doc, &[]).map_err(|errors| {
errors
.iter()
.map(|error| error.msg.clone())
.collect::<Vec<_>>()
.join("; ")
})
});
let mut rows = Rows::new();
if let Ok(text) = fs::read_to_string(&path) {
if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(&text) {
for (key, value) in map {
rows.insert(key, value);
}
}
}
Dashboard {
effective,
rows,
path,
}
}
pub fn schema(&self) -> Result<&Effective, String> {
self.effective.as_ref().map_err(|error| error.clone())
}
pub fn rows(&self) -> &Rows {
&self.rows
}
/// The visible navigation for this board and viewer.
pub fn nav(&self) -> Result<VisibleNav, String> {
let effective = self.effective.as_ref().map_err(|error| error.clone())?;
let caps = board_caps();
let apps = AppSet::default();
let routes = Routes::console();
let ctx = NavContext {
surface: Surface::Web,
principal: &AllowAll,
caps: &caps,
apps: &apps,
routes: &routes,
};
Ok(nav::visible(&effective.doc.menus, &ctx))
}
/// Stylesheets the shell needs, served from the crate's embedded assets.
pub fn assets() -> PageAssets {
PageAssets {
styles: vec![
"/assets/tokens.css".to_string(),
"/assets/components.css".to_string(),
"/assets/theme.css".to_string(),
],
scripts: Vec::new(),
streams: Vec::new(),
}
}
/// The three stylesheets, for the host to serve.
pub fn stylesheets() -> [(&'static str, &'static str); 3] {
[
("tokens.css", tokens::TOKENS_CSS),
("components.css", tokens::COMPONENTS_CSS),
("theme.css", tokens::THEME_CSS),
]
}
/// Render one page: the shell around the settings card of the tab.
///
/// `section` is the navigation section (`settings`), `tab` the tab slug
/// (`tuning`), and the settings card shows the group named by the tab.
///
/// `errors` carries per-path messages from a rejected submission, so the
/// same render can show what went wrong.
pub fn page(&self, section: &str, tab: &str, errors: &BTreeMap<String, String>) -> Markup {
let effective = match self.effective.as_ref() {
Ok(effective) => effective,
Err(error) => {
return maud::html! {
main class="bf-main" {
p class="bf-field-error bf-text-body" role="alert" { "Schema did not load: " (error) }
}
}
}
};
let nav = self.nav().unwrap_or_default();
let view = View {
eff: effective,
rows: &self.rows,
errors,
surface: Surface::Web,
can_write: true,
};
let title = effective
.doc
.menus
.iter()
.find(|menu| menu.slug == tab && menu.id.starts_with(&format!("{section}/")))
.map(|menu| menu.title.clone())
.unwrap_or_else(|| section.to_string());
let card = render::card(&title, tab, &view);
let body = maud::html! {
section class="bf-card" {
h1 class="bf-text-title" { (title) }
(card)
}
};
shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body)
}
/// Apply a submitted form body (`application/x-www-form-urlencoded`).
///
/// Returns the per-path failures when the schema rejects the batch, and
/// persists nothing in that case. Unknown keys are ignored: they are not in
/// the schema, so they cannot be written.
pub fn submit(&mut self, body: &str) -> Result<(), BTreeMap<String, String>> {
let effective = match self.effective.as_ref() {
Ok(effective) => effective,
Err(error) => {
let mut failures = BTreeMap::new();
failures.insert(String::new(), error.clone());
return Err(failures);
}
};
let ops = self.parse_ops(effective, body);
let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None);
if !failures.is_empty() {
return Err(failures);
}
for op in &ops {
if let Op::Set { path, value } = op {
self.rows.insert(path.clone(), value.clone());
}
}
let map: Map<String, Value> = self
.rows
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
if let Some(parent) = self.path.parent() {
let _ = fs::create_dir_all(parent);
}
// Persist only after validation passed; a failed write leaves the rows
// changed in memory but never on disk, which the API reports.
let _ = fs::write(&self.path, text);
Ok(())
}
/// Turn a form body into schema ops, coercing each value to its declared kind.
fn parse_ops(&self, effective: &Effective, body: &str) -> Vec<Op> {
let mut ops = Vec::new();
for pair in body.split('&') {
if pair.is_empty() {
continue;
}
let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
let key = percent_decode(raw_key);
let raw = percent_decode(raw_value);
let setting = match effective.setting(&key) {
Some(setting) => setting,
None => continue,
};
let value = coerce(setting.kind.token(), &raw);
ops.push(Op::Set {
path: setting.path.clone(),
value,
});
}
ops
}
}
fn percent_decode(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'+' => {
out.push(b' ');
index += 1;
}
b'%' if index + 2 < bytes.len() => {
let high = (bytes[index + 1] as char).to_digit(16);
let low = (bytes[index + 2] as char).to_digit(16);
match (high, low) {
(Some(high), Some(low)) => {
out.push((high * 16 + low) as u8);
index += 3;
}
_ => {
out.push(bytes[index]);
index += 1;
}
}
}
byte => {
out.push(byte);
index += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn coerce(kind: &str, raw: &str) -> Value {
match kind {
"int" | "int_set" => raw
.trim()
.parse::<i64>()
.map(Value::from)
.unwrap_or_else(|_| Value::String(raw.to_string())),
"bool" => Value::Bool(matches!(raw, "true" | "on" | "1")),
_ => Value::String(raw.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_path(name: &str) -> PathBuf {
let mut path = std::env::temp_dir();
path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id()));
let _ = fs::remove_file(&path);
path
}
#[test]
fn the_schema_loads_and_yields_the_three_sections() {
let dash = Dashboard::load(temp_path("load"));
let effective = dash.schema().expect("schema loads");
assert_eq!(effective.doc.menus.len(), 17);
let nav = dash.nav().expect("nav builds");
assert_eq!(nav.sections.len(), 3);
assert_eq!(nav.sections[1].slug, "mining");
assert_eq!(nav.sections[1].tabs.len(), 4);
}
#[test]
fn every_scaffolded_setting_is_in_the_schema() {
let dash = Dashboard::load(temp_path("settings"));
let effective = dash.schema().expect("schema loads");
for path in [
"tuning.mode",
"tuning.power_w",
"tuning.ceiling_mc",
"tuning.pid.kp_milli",
"tuning.pid.deadband_milli",
"fans.zone_count",
"fans.pwm_min",
"detect.chain_ports",
"detect.probe_budget",
"profiles.db",
"system.name",
] {
assert!(effective.setting(path).is_some(), "{path} is missing from the schema");
}
assert_eq!(effective.doc.settings.len(), 20);
}
#[test]
fn a_page_renders_its_settings_with_inputs() {
let dash = Dashboard::load(temp_path("page"));
let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string();
assert!(html.contains("bf-sidebar"), "the unified sidebar is missing");
assert!(html.contains("bf-tabs"), "the tab strip is missing");
assert!(html.contains("Tuning target"), "a settings label is missing");
assert!(html.contains("tuning.power_w"), "the field path is missing");
assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing");
}
#[test]
fn a_valid_submission_is_persisted_and_reloaded() {
let path = temp_path("submit");
let mut dash = Dashboard::load(&path);
dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form");
assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500)));
let stored = fs::read_to_string(&path).expect("settings file written");
assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}");
let reloaded = Dashboard::load(&path);
assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro")));
let _ = fs::remove_file(&path);
}
#[test]
fn an_out_of_range_value_is_rejected_and_nothing_is_written() {
let path = temp_path("reject");
let mut dash = Dashboard::load(&path);
let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected");
assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}");
assert!(!path.exists(), "a rejected submission must not be persisted");
assert_eq!(dash.rows().get("tuning.power_w"), None);
}
#[test]
fn unknown_form_keys_are_ignored() {
let path = temp_path("unknown");
let mut dash = Dashboard::load(&path);
dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies");
assert_eq!(dash.rows().get("not.a.setting"), None);
assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650)));
let _ = fs::remove_file(&path);
}
#[test]
fn form_values_are_percent_decoded() {
assert_eq!(percent_decode("a+b%2Fc"), "a b/c");
}
}
+761
View File
@@ -0,0 +1,761 @@
// SPDX-License-Identifier: MIT
//! Hardware detection model.
//!
//! The detection core decides what is physically attached to a control board and whether that
//! combination is safe to run. It never talks to a chain directly; backends report what they
//! probed, and this module turns that into a `HardwarePlan` the miner can execute.
//!
//! Identification deliberately does not require a hashboard EEPROM. The EEPROM, when present and
//! valid, confirms a board revision; a chain probe alone is enough to select a chip profile.
/// Chip families the detection core can name. `Unknown` is a real answer, not a placeholder.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChipModel {
Bm1362,
Bm1366,
Bm1368,
Bm1370,
Bm1398,
Unknown,
}
impl ChipModel {
/// Stable wire/API name for this chip family.
pub fn name(self) -> &'static str {
match self {
Self::Bm1362 => "bm1362",
Self::Bm1366 => "bm1366",
Self::Bm1368 => "bm1368",
Self::Bm1370 => "bm1370",
Self::Bm1398 => "bm1398",
Self::Unknown => "unknown",
}
}
}
/// How a chain reports temperature. PIC boards proxy telemetry through the power MCU.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SensorTopology {
Pic,
NoPic,
Unknown,
}
/// State of a hashboard EEPROM. Absence is normal and must never block detection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EepromState {
Present { model: String },
Absent,
Invalid,
}
/// What a backend observed on one physical chain.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChainReport {
pub index: u8,
pub chip: ChipModel,
pub chips_found: u16,
pub eeprom: EepromState,
/// Nonce responses per mille of dispatched work, when the backend could measure it.
pub response_per_mille: Option<u16>,
}
impl ChainReport {
pub fn is_identified(&self) -> bool {
self.chip != ChipModel::Unknown && self.chips_found > 0
}
}
/// Safe operating envelope for one hashboard/chip profile, from the profile database.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Envelope {
pub v_min_mv: u16,
pub v_max_mv: u16,
pub f_min_mhz: u16,
pub f_max_mhz: u16,
}
impl Envelope {
/// Voltage that pairs with a frequency across this envelope.
///
/// Voltage follows frequency linearly between the profile's floor and ceiling and is clamped
/// outside it. Boards do not run at a fixed voltage across their frequency range, so reporting
/// one voltage while the frequency moves would describe a machine that does not exist.
pub fn voltage_for(self, frequency_mhz: u16) -> u16 {
if frequency_mhz <= self.f_min_mhz {
return self.v_min_mv;
}
if frequency_mhz >= self.f_max_mhz {
return self.v_max_mv;
}
let span_f = u32::from(self.f_max_mhz - self.f_min_mhz);
let span_v = u32::from(self.v_max_mv - self.v_min_mv);
let offset = u32::from(frequency_mhz - self.f_min_mhz);
let voltage = u32::from(self.v_min_mv) + (span_v * offset) / span_f;
voltage.min(u32::from(u16::MAX)) as u16
}
pub fn intersect(self, other: Envelope) -> Option<Envelope> {
let v_min_mv = self.v_min_mv.max(other.v_min_mv);
let v_max_mv = self.v_max_mv.min(other.v_max_mv);
let f_min_mhz = self.f_min_mhz.max(other.f_min_mhz);
let f_max_mhz = self.f_max_mhz.min(other.f_max_mhz);
if v_min_mv > v_max_mv || f_min_mhz > f_max_mhz {
return None;
}
Some(Envelope {
v_min_mv,
v_max_mv,
f_min_mhz,
f_max_mhz,
})
}
}
/// A hashboard profile from the database.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BoardProfile {
pub name: String,
pub chip: ChipModel,
pub sensor: SensorTopology,
pub chains: u8,
pub envelope: Envelope,
}
/// What the PSU reports about itself and what it can deliver.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PsuCapability {
pub name: String,
pub envelope: Envelope,
pub max_dc_watts: u16,
}
/// Which fans cool which thermal zones, learned by active probing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FanZone {
pub fan: u8,
pub zones: Vec<u8>,
}
/// Why detection refused a combination.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DetectionError {
NoChains,
UnknownChip,
ChipProfileMismatch,
PsuUnidentified,
EnvelopeEmpty,
}
/// Operating point chosen for the machine.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OperatingPoint {
pub voltage_mv: u16,
pub frequency_mhz: u16,
/// True when the profile was confirmed by an EEPROM or a full chain identification.
pub confirmed: bool,
}
/// The result of detection: everything the miner needs and nothing it has to guess.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HardwarePlan {
pub profile: String,
pub chip: ChipModel,
pub chains: Vec<ChainReport>,
pub envelope: Envelope,
pub operating_point: OperatingPoint,
pub psu: String,
pub fan_zones: Vec<FanZone>,
}
impl HardwarePlan {
/// Chains that identified but reported no nonces, or fewer than expected chips.
pub fn degraded_chains(&self, expected: u16) -> Vec<u8> {
self.chains
.iter()
.filter(|chain| {
chain.chips_found < expected
|| chain.response_per_mille.is_some_and(|ratio| ratio == 0)
})
.map(|chain| chain.index)
.collect()
}
}
/// Turn observations into a plan, or refuse.
///
/// Refusal is a feature: an unverified or out-of-envelope combination must not mine silently.
pub fn plan(
chains: &[ChainReport],
profile: &BoardProfile,
psu: Option<&PsuCapability>,
fan_zones: Vec<FanZone>,
) -> Result<HardwarePlan, DetectionError> {
if chains.is_empty() {
return Err(DetectionError::NoChains);
}
if chains.iter().all(|chain| chain.chip == ChipModel::Unknown) {
return Err(DetectionError::UnknownChip);
}
if chains
.iter()
.filter(|chain| chain.is_identified())
.any(|chain| chain.chip != profile.chip)
{
return Err(DetectionError::ChipProfileMismatch);
}
let psu = psu.ok_or(DetectionError::PsuUnidentified)?;
let envelope = profile
.envelope
.intersect(psu.envelope)
.ok_or(DetectionError::EnvelopeEmpty)?;
let confirmed = chains
.iter()
.any(|chain| matches!(chain.eeprom, EepromState::Present { .. }))
&& chains.iter().all(ChainReport::is_identified);
let operating_point = if confirmed {
OperatingPoint {
voltage_mv: envelope.v_max_mv.min(profile.envelope.v_max_mv),
frequency_mhz: envelope.f_max_mhz.min(profile.envelope.f_max_mhz),
confirmed: true,
}
} else {
// Unverified hardware runs at the conservative floor of the usable envelope.
OperatingPoint {
voltage_mv: envelope.v_min_mv,
frequency_mhz: envelope.f_min_mhz,
confirmed: false,
}
};
Ok(HardwarePlan {
profile: profile.name.clone(),
chip: profile.chip,
chains: chains.to_vec(),
envelope,
operating_point,
psu: psu.name.clone(),
fan_zones,
})
}
/// Outcome of one chip-identification attempt on a chain.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProbeOutcome {
/// Chips answered: the model and how many responded.
Identified { chip: ChipModel, chips: u16 },
/// The port is electrically silent (no signal at all).
Silent,
/// Bytes arrived but did not frame as a chip response: wrong baud, noise, or a dead TX.
Garbled,
}
/// Backend contract for identification.
///
/// Framing, baud switching and electrical detail stay in the SDK image for that family; the OS
/// only decides how many attempts to spend and what the results mean.
pub trait DetectionBackend {
type Error;
/// Attempt one identification on `chain`. `attempt` lets the backend cycle its candidate
/// interface/baud set deterministically. A transport failure is an error, never `Silent`.
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error>;
/// Read the hashboard EEPROM, or report that it is absent or unreadable.
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error>;
/// Identify the PSU, if this backend can. `None` means "cannot tell", which refuses later.
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error>;
}
/// How many identification attempts to spend per chain before declaring it unidentified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProbeBudget {
pub attempts: u8,
}
impl Default for ProbeBudget {
fn default() -> Self {
Self { attempts: 4 }
}
}
/// Probe one chain until it identifies or the budget is spent.
///
/// A chain that never identifies is reported as `ChipModel::Unknown` with zero chips rather than
/// being dropped, so the plan can refuse explicitly and the API can show why.
pub fn probe_chain<B: DetectionBackend>(
backend: &mut B,
chain: u8,
budget: ProbeBudget,
) -> Result<ChainReport, B::Error> {
let mut outcome = ProbeOutcome::Silent;
for attempt in 0..budget.attempts.max(1) {
outcome = backend.probe(chain, attempt)?;
if matches!(outcome, ProbeOutcome::Identified { .. }) {
break;
}
}
let (chip, chips_found) = match outcome {
ProbeOutcome::Identified { chip, chips } => (chip, chips),
_ => (ChipModel::Unknown, 0),
};
Ok(ChainReport {
index: chain,
chip,
chips_found,
eeprom: backend.eeprom(chain)?,
response_per_mille: None,
})
}
/// Probe every declared chain port.
pub fn detect_chains<B: DetectionBackend>(
backend: &mut B,
chains: &[u8],
budget: ProbeBudget,
) -> Result<Vec<ChainReport>, B::Error> {
let mut reports = Vec::with_capacity(chains.len());
for &chain in chains {
reports.push(probe_chain(backend, chain, budget)?);
}
Ok(reports)
}
/// Everything the caller knows before probing: which ports exist, how hard to try, and how the
/// hashboards report temperature.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DetectionRequest<'a> {
pub chain_ports: &'a [u8],
pub budget: ProbeBudget,
pub sensor: SensorTopology,
pub fan_zones: Vec<FanZone>,
}
/// Why a detection run did not produce a plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DetectionFailure<E> {
Backend(E),
Refused(DetectionError),
NoProfile,
}
/// Detect, select a profile, and decide whether the machine may run.
///
/// The profile is selected by chip, sensor wiring and the number of physical chain ports, so a
/// machine with a dead chain still matches its profile and runs degraded instead of being
/// reclassified as a different model.
pub fn run_detection<B: DetectionBackend>(
backend: &mut B,
db: &crate::profiles::ProfileDb,
request: &DetectionRequest<'_>,
) -> Result<HardwarePlan, DetectionFailure<B::Error>> {
let reports = detect_chains(backend, request.chain_ports, request.budget)
.map_err(DetectionFailure::Backend)?;
let chip = reports
.iter()
.find(|report| report.is_identified())
.map(|report| report.chip)
.ok_or(DetectionFailure::Refused(DetectionError::UnknownChip))?;
let chains = u8::try_from(request.chain_ports.len()).unwrap_or(u8::MAX);
let profile = db
.find(chip, chains, request.sensor)
.ok_or(DetectionFailure::NoProfile)?;
let psu = backend.identify_psu().map_err(DetectionFailure::Backend)?;
plan(&reports, profile, psu.as_ref(), request.fan_zones.clone())
.map_err(DetectionFailure::Refused)
}
#[cfg(test)]
mod tests {
use super::*;
fn profile() -> BoardProfile {
BoardProfile {
name: "s19jpro-bm1362".into(),
chip: ChipModel::Bm1362,
sensor: SensorTopology::Pic,
chains: 3,
envelope: Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
},
}
}
fn psu() -> PsuCapability {
PsuCapability {
name: "APW12".into(),
envelope: Envelope {
v_min_mv: 1200,
v_max_mv: 1600,
f_min_mhz: 0,
f_max_mhz: 1000,
},
max_dc_watts: 3600,
}
}
fn chain(index: u8, eeprom: EepromState) -> ChainReport {
ChainReport {
index,
chip: ChipModel::Bm1362,
chips_found: 126,
eeprom,
response_per_mille: Some(980),
}
}
#[test]
fn confirmed_plan_uses_verified_ceiling() {
let chains = [chain(
0,
EepromState::Present {
model: "BHB42601".into(),
},
)];
let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan");
assert!(plan.operating_point.confirmed);
assert_eq!(plan.operating_point.voltage_mv, 1500);
assert_eq!(plan.operating_point.frequency_mhz, 700);
assert_eq!(plan.envelope.v_min_mv, 1200);
}
#[test]
fn absent_eeprom_still_yields_a_conservative_plan() {
let chains = [chain(0, EepromState::Absent)];
let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan");
assert!(!plan.operating_point.confirmed);
assert_eq!(plan.operating_point.voltage_mv, plan.envelope.v_min_mv);
assert_eq!(plan.operating_point.frequency_mhz, plan.envelope.f_min_mhz);
}
#[test]
fn unknown_chip_refuses() {
let mut chains = [chain(0, EepromState::Absent)];
chains[0].chip = ChipModel::Unknown;
assert_eq!(
plan(&chains, &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::UnknownChip)
);
}
#[test]
fn wrong_chip_refuses() {
let mut chains = [chain(0, EepromState::Absent)];
chains[0].chip = ChipModel::Bm1366;
assert_eq!(
plan(&chains, &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::ChipProfileMismatch)
);
}
#[test]
fn missing_psu_refuses() {
let chains = [chain(0, EepromState::Absent)];
assert_eq!(
plan(&chains, &profile(), None, Vec::new()),
Err(DetectionError::PsuUnidentified)
);
}
#[test]
fn incompatible_psu_refuses() {
let chains = [chain(0, EepromState::Absent)];
let weak = PsuCapability {
name: "APW3".into(),
envelope: Envelope {
v_min_mv: 700,
v_max_mv: 1090,
f_min_mhz: 0,
f_max_mhz: 1000,
},
max_dc_watts: 1600,
};
assert_eq!(
plan(&chains, &profile(), Some(&weak), Vec::new()),
Err(DetectionError::EnvelopeEmpty)
);
}
#[test]
fn empty_chain_set_refuses() {
assert_eq!(
plan(&[], &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::NoChains)
);
}
#[test]
fn degraded_chains_are_reported_not_fatal() {
let mut silent = chain(1, EepromState::Absent);
silent.response_per_mille = Some(0);
let chains = [chain(0, EepromState::Absent), silent];
let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan");
assert_eq!(plan.degraded_chains(126), vec![1]);
}
#[test]
fn fan_zones_are_carried_into_the_plan() {
let chains = [chain(0, EepromState::Absent)];
let zones = vec![FanZone {
fan: 0,
zones: vec![0, 1],
}];
let plan = plan(&chains, &profile(), Some(&psu()), zones.clone()).expect("plan");
assert_eq!(plan.fan_zones, zones);
}
struct ScriptedProbe {
plan: std::collections::VecDeque<ProbeOutcome>,
eeprom: EepromState,
calls: usize,
fail_at: u8,
psu: Option<PsuCapability>,
}
impl ScriptedProbe {
fn new(plan: &[ProbeOutcome], eeprom: EepromState) -> Self {
Self {
plan: plan.iter().copied().collect(),
eeprom,
calls: 0,
fail_at: u8::MAX,
psu: Some(psu()),
}
}
}
impl DetectionBackend for ScriptedProbe {
type Error = ();
fn probe(&mut self, _chain: u8, attempt: u8) -> Result<ProbeOutcome, ()> {
self.calls += 1;
if attempt == self.fail_at {
return Err(());
}
Ok(self.plan.pop_front().unwrap_or(ProbeOutcome::Silent))
}
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
Ok(self.eeprom.clone())
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
Ok(self.psu.clone())
}
}
#[test]
fn probe_retries_until_the_chain_identifies() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Silent,
ProbeOutcome::Garbled,
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
],
EepromState::Absent,
);
let report = probe_chain(&mut backend, 0, ProbeBudget { attempts: 4 }).expect("probe");
assert_eq!(backend.calls, 3);
assert_eq!(report.chip, ChipModel::Bm1362);
assert_eq!(report.chips_found, 126);
assert!(report.is_identified());
}
#[test]
fn probe_exhaustion_is_reported_not_hidden() {
let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent);
let report = probe_chain(&mut backend, 1, ProbeBudget { attempts: 4 }).expect("probe");
assert_eq!(backend.calls, 4);
assert_eq!(report.chip, ChipModel::Unknown);
assert_eq!(report.chips_found, 0);
assert!(!report.is_identified());
}
#[test]
fn probe_keeps_the_eeprom_state_even_when_unidentified() {
let mut backend = ScriptedProbe::new(
&[ProbeOutcome::Garbled; 2],
EepromState::Present {
model: "BHB42601".into(),
},
);
let report = probe_chain(&mut backend, 2, ProbeBudget { attempts: 2 }).expect("probe");
assert_eq!(report.chip, ChipModel::Unknown);
assert_eq!(
report.eeprom,
EepromState::Present {
model: "BHB42601".into()
}
);
}
#[test]
fn detection_covers_every_declared_chain_port() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
],
EepromState::Absent,
);
let reports =
detect_chains(&mut backend, &[0, 1, 2], ProbeBudget::default()).expect("detect");
assert_eq!(reports.len(), 3);
assert_eq!(
reports.iter().map(|r| r.index).collect::<Vec<_>>(),
vec![0, 1, 2]
);
assert!(reports.iter().all(ChainReport::is_identified));
}
#[test]
fn transport_failure_is_not_reported_as_a_silent_port() {
let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent);
backend.fail_at = 1;
assert_eq!(
probe_chain(&mut backend, 0, ProbeBudget::default()),
Err(())
);
assert_eq!(backend.calls, 2);
}
#[test]
fn unidentified_chain_makes_the_plan_refuse() {
let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent);
let reports = detect_chains(&mut backend, &[0], ProbeBudget::default()).expect("detect");
assert_eq!(
plan(&reports, &profile(), Some(&psu()), Vec::new()),
Err(DetectionError::UnknownChip)
);
}
fn db() -> crate::profiles::ProfileDb {
crate::profiles::ProfileDb::new(vec![profile()]).expect("db")
}
#[test]
fn run_detection_emits_a_plan_end_to_end() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
],
EepromState::Absent,
);
let request = DetectionRequest {
chain_ports: &[0, 1, 2],
budget: ProbeBudget::default(),
sensor: SensorTopology::Pic,
fan_zones: vec![FanZone {
fan: 0,
zones: vec![0],
}],
};
let plan = run_detection(&mut backend, &db(), &request).expect("plan");
assert_eq!(plan.chains.len(), 3);
assert_eq!(plan.psu, "APW12");
assert!(!plan.operating_point.confirmed);
assert_eq!(plan.operating_point.voltage_mv, 1200);
}
#[test]
fn run_detection_refuses_when_no_profile_matches() {
let mut backend = ScriptedProbe::new(
&[ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
}],
EepromState::Absent,
);
let request = DetectionRequest {
chain_ports: &[0],
budget: ProbeBudget::default(),
sensor: SensorTopology::Pic,
fan_zones: Vec::new(),
};
assert_eq!(
run_detection(&mut backend, &db(), &request),
Err(DetectionFailure::NoProfile)
);
}
#[test]
fn run_detection_runs_degraded_with_a_dead_chain() {
let mut backend = ScriptedProbe::new(
&[
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Identified {
chip: ChipModel::Bm1362,
chips: 126,
},
ProbeOutcome::Silent,
ProbeOutcome::Silent,
ProbeOutcome::Silent,
ProbeOutcome::Silent,
],
EepromState::Absent,
);
let request = DetectionRequest {
chain_ports: &[0, 1, 2],
budget: ProbeBudget::default(),
sensor: SensorTopology::Pic,
fan_zones: Vec::new(),
};
let plan = run_detection(&mut backend, &db(), &request).expect("plan");
assert_eq!(plan.degraded_chains(126), vec![2]);
}
#[test]
fn voltage_follows_frequency_and_clamps_outside_the_envelope() {
let envelope = Envelope {
v_min_mv: 1100,
v_max_mv: 1500,
f_min_mhz: 300,
f_max_mhz: 700,
};
assert_eq!(envelope.voltage_for(200), 1100);
assert_eq!(envelope.voltage_for(300), 1100);
assert_eq!(envelope.voltage_for(500), 1300);
assert_eq!(envelope.voltage_for(700), 1500);
assert_eq!(envelope.voltage_for(900), 1500);
}
#[test]
fn a_single_frequency_envelope_reports_its_floor() {
let envelope = Envelope {
v_min_mv: 1200,
v_max_mv: 1400,
f_min_mhz: 500,
f_max_mhz: 500,
};
assert_eq!(envelope.voltage_for(500), 1200);
assert_eq!(envelope.voltage_for(600), 1400);
}
}
+120
View File
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: MIT
//! Exact Bitcoin Stratum share target conversion; no floating point or nonce search.
use serde_json::Number;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DifficultyError {
Invalid,
OutOfRange,
}
/// A positive decimal difficulty represented exactly as numerator/denominator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PoolDifficulty {
numerator: u64,
denominator: u64,
}
impl PoolDifficulty {
pub fn from_json_number(number: &Number) -> Result<Self, DifficultyError> {
let text = number.as_str();
if text.len() > 128 || text.starts_with('-') {
return Err(DifficultyError::OutOfRange);
}
let (mantissa, exponent) = match text.split_once(['e', 'E']) {
Some((base, exponent)) => (
base,
exponent
.parse::<i32>()
.map_err(|_| DifficultyError::OutOfRange)?,
),
None => (text, 0),
};
let mut digits = Vec::with_capacity(mantissa.len());
let mut fractional = 0_i32;
let mut after_dot = false;
for byte in mantissa.bytes() {
match byte {
b'.' if !after_dot => after_dot = true,
b'0'..=b'9' => {
digits.push(byte - b'0');
if after_dot {
fractional += 1;
}
}
_ => return Err(DifficultyError::Invalid),
}
}
let first = digits
.iter()
.position(|digit| *digit != 0)
.ok_or(DifficultyError::Invalid)?;
let last = digits
.iter()
.rposition(|digit| *digit != 0)
.expect("nonzero digit");
let trailing = (digits.len() - last - 1) as i32;
let mut numerator = 0_u64;
for digit in &digits[first..=last] {
numerator = numerator
.checked_mul(10)
.and_then(|value| value.checked_add(u64::from(*digit)))
.ok_or(DifficultyError::OutOfRange)?;
}
let shift = exponent
.checked_sub(fractional)
.and_then(|value| value.checked_add(trailing))
.ok_or(DifficultyError::OutOfRange)?;
if !(-19..=19).contains(&shift) {
return Err(DifficultyError::OutOfRange);
}
let mut denominator = 1_u64;
if shift >= 0 {
for _ in 0..shift {
numerator = numerator
.checked_mul(10)
.ok_or(DifficultyError::OutOfRange)?;
}
} else {
for _ in 0..-shift {
denominator = denominator
.checked_mul(10)
.ok_or(DifficultyError::OutOfRange)?;
}
}
Ok(Self {
numerator,
denominator,
})
}
/// floor((0xFFFF << 208) / difficulty), capped at the 256-bit maximum.
/// The 320-bit intermediate permits all supported decimal denominators.
pub fn target_le(self) -> [u8; 32] {
let mut product = [0_u8; 40];
let mut carry = 0_u128;
for (index, byte) in product.iter_mut().enumerate() {
let diff_one_byte = if index == 26 || index == 27 { 0xff } else { 0 };
let value = (diff_one_byte as u128) * u128::from(self.denominator) + carry;
*byte = value as u8;
carry = value >> 8;
}
debug_assert_eq!(carry, 0);
let mut quotient = [0_u8; 40];
let mut remainder = 0_u128;
for index in (0..320).rev() {
let bit = (product[index / 8] >> (index % 8)) & 1;
remainder = (remainder << 1) | u128::from(bit);
if remainder >= u128::from(self.numerator) {
remainder -= u128::from(self.numerator);
quotient[index / 8] |= 1 << (index % 8);
}
}
if quotient[32..].iter().any(|byte| *byte != 0) {
return [0xff; 32];
}
quotient[..32].try_into().expect("256-bit quotient")
}
}
+469
View File
@@ -0,0 +1,469 @@
// SPDX-License-Identifier: MIT
//! Active fan-to-thermal-zone mapping.
//!
//! Antminer chassis wire fans to zones in a way that is not reported by the hardware: a fan may
//! cool one hashboard heavily and another barely, and the front/back, top/bottom labels are
//! physical. The mapping is learned by stepping one fan at a time and watching which zone's
//! temperature responds, which is why this module takes measurements rather than configuration.
use crate::detect::FanZone;
/// One sensor reading taken while a fan was held at a given duty.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ZoneReading {
pub zone: u8,
pub temp_mc: i32,
}
/// One measurement step: a fan duty and the temperatures observed during it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProbeSample {
pub fan: u8,
pub pwm: u8,
pub readings: Vec<ZoneReading>,
}
/// Thresholds that decide when a response is real.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MapThresholds {
/// Minimum cooling (millidegrees) between the low and high duty to count as a response.
pub min_drop_mc: i32,
/// Minimum margin over the next-best fan, in parts per thousand of the best response.
pub min_margin_per_mille: u16,
}
impl Default for MapThresholds {
fn default() -> Self {
Self {
min_drop_mc: 500,
min_margin_per_mille: 250,
}
}
}
/// The learned mapping.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct FanMap {
pub assignments: Vec<FanZone>,
/// Zones whose response was ambiguous and were therefore left unassigned.
pub unresolved: Vec<u8>,
/// Per assigned zone, the margin over the runner-up in parts per thousand.
pub confidence_per_mille: Vec<u16>,
}
impl FanMap {
/// Zones a fan was confidently assigned to.
pub fn zones_for(&self, fan: u8) -> Vec<u8> {
self.assignments
.iter()
.find(|assignment| assignment.fan == fan)
.map(|assignment| assignment.zones.clone())
.unwrap_or_default()
}
}
/// Response per (fan, zone): positive means the zone cooled when that fan sped up.
fn responses(samples: &[ProbeSample], zones: &[u8]) -> Vec<(u8, Vec<(u8, i32)>)> {
let mut fans: Vec<u8> = samples.iter().map(|sample| sample.fan).collect();
fans.sort_unstable();
fans.dedup();
let mut out = Vec::new();
for fan in fans {
let fan_samples: Vec<&ProbeSample> =
samples.iter().filter(|sample| sample.fan == fan).collect();
let min_pwm = fan_samples.iter().map(|sample| sample.pwm).min();
let max_pwm = fan_samples.iter().map(|sample| sample.pwm).max();
let (Some(low), Some(high)) = (min_pwm, max_pwm) else {
continue;
};
if low == high {
continue;
}
let mut per_zone = Vec::with_capacity(zones.len());
for &zone in zones {
let mean_at = |pwm: u8| -> Option<i32> {
let values: Vec<i32> = fan_samples
.iter()
.filter(|sample| sample.pwm == pwm)
.flat_map(|sample| {
sample
.readings
.iter()
.filter(|reading| reading.zone == zone)
.map(|reading| reading.temp_mc)
})
.collect();
if values.is_empty() {
return None;
}
let sum: i64 = values.iter().map(|value| *value as i64).sum();
Some((sum / values.len() as i64) as i32)
};
// Duty goes up, temperature should come down: response = warm-run minus fast-run.
if let (Some(slow_temp), Some(fast_temp)) = (mean_at(low), mean_at(high)) {
per_zone.push((zone, slow_temp - fast_temp));
}
}
out.push((fan, per_zone));
}
out
}
/// Learn which fans cool which zones from a stepped measurement run.
///
/// Every zone goes to the fan with the strongest cooling response, provided that response clears
/// `min_drop_mc` and beats the runner-up by `min_margin_per_mille`. Anything weaker stays
/// unresolved instead of being guessed, so a noisy run cannot invent a fan map.
pub fn map_fans(samples: &[ProbeSample], zones: &[u8], thresholds: MapThresholds) -> FanMap {
let responses = responses(samples, zones);
let mut map = FanMap::default();
for &zone in zones {
let mut ranked: Vec<(i32, u8)> = responses
.iter()
.filter_map(|(fan, per_zone)| {
per_zone
.iter()
.find(|(candidate, _)| *candidate == zone)
.map(|(_, drop)| (*drop, *fan))
})
.collect();
ranked.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.0));
let Some(&(best_drop, best_fan)) = ranked.first() else {
map.unresolved.push(zone);
continue;
};
let runner_up = ranked.get(1).map(|(drop, _)| *drop).unwrap_or(0);
let margin = best_drop - runner_up.max(0);
let margin_per_mille = if best_drop > 0 {
((margin as i64 * 1000) / best_drop as i64) as u16
} else {
0
};
if best_drop < thresholds.min_drop_mc || margin_per_mille < thresholds.min_margin_per_mille
{
map.unresolved.push(zone);
continue;
}
match map
.assignments
.iter_mut()
.find(|assignment| assignment.fan == best_fan)
{
Some(assignment) => assignment.zones.push(zone),
None => map.assignments.push(FanZone {
fan: best_fan,
zones: vec![zone],
}),
}
map.confidence_per_mille.push(margin_per_mille);
}
map
}
/// Safe limits for a fan-mapping sweep.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SweepConfig {
pub fans: u8,
pub zones: u8,
/// Lowest duty used during probing. Never zero: the boards must keep airflow.
pub low_pwm: u8,
pub high_pwm: u8,
/// Readings taken per (fan, duty) step; the mapper averages them.
pub repeats: u8,
/// Time to wait after a duty change before reading temperatures.
pub settle_ms: u32,
}
impl Default for SweepConfig {
fn default() -> Self {
Self {
fans: 4,
zones: 3,
low_pwm: 40,
high_pwm: 100,
repeats: 2,
settle_ms: 20_000,
}
}
}
/// Minimum duty a sweep may use. Airflow is never removed to make a measurement.
pub const MIN_PROBE_PWM: u8 = 20;
/// Why a sweep did not run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SweepError<E> {
Backend(E),
InvalidConfig(&'static str),
}
/// The two backend actions a sweep needs.
pub trait FanProbe {
type Error;
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error>;
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error>;
}
/// Step every fan between the low and high duty and record what the zones do.
///
/// One fan is moved at a time while the others hold their previous duty, so the response belongs
/// to that fan. The run ends with every fan back at `high_pwm`: leaving a fan low after probing
/// would be a thermal hazard for whatever runs next.
pub fn sweep<B: FanProbe, S: FnMut(u32)>(
backend: &mut B,
config: &SweepConfig,
mut settle: S,
) -> Result<Vec<ProbeSample>, SweepError<B::Error>> {
if config.fans == 0 {
return Err(SweepError::InvalidConfig("no fans to sweep"));
}
if config.zones == 0 {
return Err(SweepError::InvalidConfig("no zones to read"));
}
if config.low_pwm < MIN_PROBE_PWM {
return Err(SweepError::InvalidConfig(
"probe duty below the safe minimum",
));
}
if config.high_pwm > 100 {
return Err(SweepError::InvalidConfig("probe duty above 100 percent"));
}
if config.low_pwm >= config.high_pwm {
return Err(SweepError::InvalidConfig("probe duty range is empty"));
}
if config.repeats == 0 {
return Err(SweepError::InvalidConfig("no readings requested"));
}
let mut samples = Vec::new();
for fan in 0..config.fans {
for pwm in [config.low_pwm, config.high_pwm] {
backend.set_fan(fan, pwm).map_err(SweepError::Backend)?;
settle(config.settle_ms);
for _ in 0..config.repeats {
let mut readings = Vec::with_capacity(config.zones as usize);
for zone in 0..config.zones {
readings.push(ZoneReading {
zone,
temp_mc: backend.read_zone(zone).map_err(SweepError::Backend)?,
});
}
samples.push(ProbeSample { fan, pwm, readings });
}
}
}
for fan in 0..config.fans {
backend
.set_fan(fan, config.high_pwm)
.map_err(SweepError::Backend)?;
}
Ok(samples)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(fan: u8, pwm: u8, zone_temps: &[(u8, i32)]) -> ProbeSample {
ProbeSample {
fan,
pwm,
readings: zone_temps
.iter()
.map(|(zone, temp)| ZoneReading {
zone: *zone,
temp_mc: *temp,
})
.collect(),
}
}
#[test]
fn each_zone_is_assigned_to_the_fan_that_cools_it() {
let samples = vec![
sample(0, 30, &[(0, 70_000), (1, 60_000)]),
sample(0, 100, &[(0, 50_000), (1, 59_000)]),
sample(1, 30, &[(0, 69_000), (1, 60_000)]),
sample(1, 100, &[(0, 68_000), (1, 40_000)]),
];
let map = map_fans(&samples, &[0, 1], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
assert_eq!(map.zones_for(1), vec![1]);
assert!(map.unresolved.is_empty());
}
#[test]
fn ambiguity_leaves_a_zone_unresolved() {
let samples = vec![
sample(0, 30, &[(0, 70_000)]),
sample(0, 100, &[(0, 60_000)]),
sample(1, 30, &[(0, 70_500)]),
sample(1, 100, &[(0, 60_500)]),
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert!(map.assignments.is_empty());
assert_eq!(map.unresolved, vec![0]);
}
#[test]
fn a_fan_that_does_not_change_temperature_is_not_assigned() {
let samples = vec![
sample(0, 30, &[(0, 60_000)]),
sample(0, 100, &[(0, 59_900)]),
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert!(map.assignments.is_empty());
assert_eq!(map.unresolved, vec![0]);
}
#[test]
fn a_fan_without_duty_range_is_skipped() {
let samples = vec![sample(0, 50, &[(0, 60_000)]), sample(0, 50, &[(0, 60_000)])];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert!(map.assignments.is_empty());
assert_eq!(map.unresolved, vec![0]);
}
#[test]
fn one_fan_can_own_several_zones() {
let samples = vec![
sample(0, 30, &[(0, 70_000), (1, 71_000), (2, 55_000)]),
sample(0, 100, &[(0, 55_000), (1, 56_000), (2, 54_000)]),
sample(1, 30, &[(0, 70_000), (1, 71_000), (2, 54_000)]),
sample(1, 100, &[(0, 69_000), (1, 70_000), (2, 50_000)]),
];
let map = map_fans(&samples, &[0, 1, 2], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0, 1]);
assert_eq!(map.zones_for(1), vec![2]);
}
struct ThermalMock {
duty: Vec<u8>,
owners: Vec<(u8, u8)>,
fail: bool,
}
impl ThermalMock {
fn new(owners: &[(u8, u8)]) -> Self {
let fans = owners.iter().map(|(fan, _)| *fan).max().unwrap_or(0) + 1;
Self {
duty: vec![100; fans as usize],
owners: owners.to_vec(),
fail: false,
}
}
}
impl FanProbe for ThermalMock {
type Error = &'static str;
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> {
if self.fail {
return Err("fan bus down");
}
self.duty[fan as usize] = pwm;
Ok(())
}
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error> {
if self.fail {
return Err("sensor bus down");
}
let owner = self
.owners
.iter()
.find(|(_, candidate)| *candidate == zone)
.map(|(fan, _)| *fan)
.expect("zone has an owner");
let cooled = self.duty[owner as usize] >= 100;
Ok(if cooled { 50_000 } else { 70_000 })
}
}
#[test]
fn sweep_then_map_resolves_each_zone() {
let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]);
let config = SweepConfig {
fans: 2,
zones: 2,
low_pwm: 40,
high_pwm: 100,
repeats: 2,
settle_ms: 0,
};
let samples = sweep(&mut backend, &config, |_| {}).expect("sweep");
assert_eq!(samples.len(), 2 * 2 * 2);
let map = map_fans(&samples, &[0, 1], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
assert_eq!(map.zones_for(1), vec![1]);
assert!(map.unresolved.is_empty());
}
#[test]
fn sweep_restores_every_fan_to_high_duty() {
let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]);
let config = SweepConfig {
fans: 2,
zones: 2,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
};
sweep(&mut backend, &config, |_| {}).expect("sweep");
assert_eq!(backend.duty, vec![100, 100]);
}
#[test]
fn sweep_refuses_an_unsafe_duty() {
let mut backend = ThermalMock::new(&[(0, 0)]);
let config = SweepConfig {
fans: 1,
zones: 1,
low_pwm: 10,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
};
assert_eq!(
sweep(&mut backend, &config, |_| {}),
Err(SweepError::InvalidConfig(
"probe duty below the safe minimum"
))
);
}
#[test]
fn sweep_refuses_an_empty_range_and_zero_reads() {
let mut backend = ThermalMock::new(&[(0, 0)]);
let flat = SweepConfig {
fans: 1,
zones: 1,
low_pwm: 60,
high_pwm: 60,
repeats: 1,
settle_ms: 0,
};
assert!(matches!(
sweep(&mut backend, &flat, |_| {}),
Err(SweepError::InvalidConfig(_))
));
let no_reads = SweepConfig { repeats: 0, ..flat };
assert!(matches!(
sweep(&mut backend, &no_reads, |_| {}),
Err(SweepError::InvalidConfig(_))
));
}
#[test]
fn sweep_propagates_backend_failures() {
let mut backend = ThermalMock::new(&[(0, 0)]);
backend.fail = true;
let config = SweepConfig::default();
assert_eq!(
sweep(&mut backend, &config, |_| {}),
Err(SweepError::Backend("fan bus down"))
);
}
}
+318
View File
@@ -0,0 +1,318 @@
// SPDX-License-Identifier: MIT
//! Persisting the learned fan map.
//!
//! Mapping fans means heating and cooling the machine deliberately, so it is done once, stored, and
//! reused until the fan or sensor set changes. A stored map that does not match the current set is
//! ignored rather than trusted: silently applying a map learned on four fans to a machine with two
//! would mis-control thermals.
use crate::detect::FanZone;
use crate::fanmap::{map_fans, sweep, FanMap, FanProbe, MapThresholds, SweepConfig, SweepError};
use serde_json::{json, Value};
use std::fs;
use std::io;
use std::path::Path;
/// A stored map together with the hardware it was learned on.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredMap {
pub fans: u8,
pub zones: u8,
pub assignments: Vec<FanZone>,
pub unresolved: Vec<u8>,
}
impl StoredMap {
pub fn from_map(map: &FanMap, fans: u8, zones: u8) -> Self {
Self {
fans,
zones,
assignments: map.assignments.clone(),
unresolved: map.unresolved.clone(),
}
}
pub fn to_map(&self) -> FanMap {
FanMap {
assignments: self.assignments.clone(),
unresolved: self.unresolved.clone(),
confidence_per_mille: vec![0; self.assignments.len()],
}
}
/// True when this map was learned on the same fan and zone counts.
pub fn matches(&self, fans: u8, zones: u8) -> bool {
self.fans == fans && self.zones == zones
}
pub fn to_json(&self) -> String {
json!({
"schema": 1,
"fans": self.fans,
"zones": self.zones,
"assignments": self.assignments.iter().map(|zone| json!({
"fan": zone.fan,
"zones": zone.zones,
})).collect::<Vec<_>>(),
"unresolved": self.unresolved,
})
.to_string()
}
pub fn from_json(text: &str) -> Option<Self> {
let root: Value = serde_json::from_str(text).ok()?;
if root.get("schema")?.as_u64()? != 1 {
return None;
}
let fans = u8::try_from(root.get("fans")?.as_u64()?).ok()?;
let zones = u8::try_from(root.get("zones")?.as_u64()?).ok()?;
let assignments = root
.get("assignments")?
.as_array()?
.iter()
.map(|entry| {
Some(FanZone {
fan: u8::try_from(entry.get("fan")?.as_u64()?).ok()?,
zones: entry
.get("zones")?
.as_array()?
.iter()
.map(|zone| u8::try_from(zone.as_u64()?).ok())
.collect::<Option<Vec<u8>>>()?,
})
})
.collect::<Option<Vec<FanZone>>>()?;
let unresolved = root
.get("unresolved")?
.as_array()?
.iter()
.map(|zone| u8::try_from(zone.as_u64()?).ok())
.collect::<Option<Vec<u8>>>()?;
Some(Self {
fans,
zones,
assignments,
unresolved,
})
}
}
/// Why mapping did not produce a stored map.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StoreError<E> {
Sweep(SweepError<E>),
Io(&'static str),
}
/// Read a stored map, if one exists and parses.
pub fn load(path: &Path) -> Option<StoredMap> {
let text = fs::read_to_string(path).ok()?;
StoredMap::from_json(&text)
}
/// Write a map, creating the parent directory when needed.
pub fn save(path: &Path, stored: &StoredMap) -> io::Result<()> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)?;
}
}
fs::write(path, stored.to_json())
}
/// Return the stored map when it matches this machine, otherwise sweep, map, and store the result.
pub fn ensure_map<B: FanProbe, S: FnMut(u32)>(
backend: &mut B,
config: &SweepConfig,
thresholds: MapThresholds,
path: &Path,
settle: S,
) -> Result<FanMap, StoreError<B::Error>> {
if let Some(stored) = load(path) {
if stored.matches(config.fans, config.zones) {
return Ok(stored.to_map());
}
}
let zones: Vec<u8> = (0..config.zones).collect();
let samples = sweep(backend, config, settle).map_err(StoreError::Sweep)?;
let map = map_fans(&samples, &zones, thresholds);
let stored = StoredMap::from_map(&map, config.fans, config.zones);
save(path, &stored).map_err(|_| StoreError::Io("cannot write the fan map"))?;
Ok(map)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::{ProbeSample, ZoneReading};
struct CountingBackend {
duty: Vec<u8>,
owners: Vec<(u8, u8)>,
calls: usize,
}
impl FanProbe for CountingBackend {
type Error = ();
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), ()> {
self.calls += 1;
self.duty[fan as usize] = pwm;
Ok(())
}
fn read_zone(&mut self, zone: u8) -> Result<i32, ()> {
// Zones without an explicit owner follow fan 0, which keeps the mock usable when a
// test asks for more zones than the fixture declares.
let owner = self
.owners
.iter()
.find(|(_, candidate)| *candidate == zone)
.map(|(fan, _)| *fan)
.unwrap_or(0);
Ok(if self.duty[owner as usize] >= 100 {
50_000
} else {
70_000
})
}
}
fn backend() -> CountingBackend {
CountingBackend {
duty: vec![100, 100],
owners: vec![(0, 0), (1, 1)],
calls: 0,
}
}
fn config(zones: u8) -> SweepConfig {
SweepConfig {
fans: 2,
zones,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
}
}
fn path(name: &str) -> std::path::PathBuf {
let mut dir = std::env::temp_dir();
dir.push(format!("alkane-fanmap-{}-{name}.json", std::process::id()));
dir
}
#[test]
fn a_stored_map_round_trips() {
let map = FanMap {
assignments: vec![FanZone {
fan: 0,
zones: vec![0, 1],
}],
unresolved: vec![2],
confidence_per_mille: vec![900],
};
let stored = StoredMap::from_map(&map, 4, 3);
let text = stored.to_json();
assert_eq!(StoredMap::from_json(&text).expect("parse"), stored);
let back = stored.to_map();
assert_eq!(back.assignments, map.assignments);
assert_eq!(back.unresolved, map.unresolved);
}
#[test]
fn corrupt_or_foreign_json_is_ignored() {
assert!(StoredMap::from_json("not json").is_none());
assert!(StoredMap::from_json(r#"{"schema":2}"#).is_none());
assert!(StoredMap::from_json(r#"{"schema":1,"fans":2}"#).is_none());
}
#[test]
fn a_matching_map_is_reused_without_sweeping() {
let file = path("reuse");
let first = ensure_map(
&mut backend(),
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("first");
assert_eq!(first.zones_for(0), vec![0]);
let mut reuse = backend();
let second = ensure_map(
&mut reuse,
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("second");
assert_eq!(second.zones_for(0), vec![0]);
assert_eq!(reuse.calls, 0, "a stored map must not cause another sweep");
let _ = std::fs::remove_file(&file);
}
#[test]
fn a_changed_sensor_set_forces_a_new_sweep() {
let file = path("changed");
ensure_map(
&mut backend(),
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("first");
let mut fresh = backend();
let map = ensure_map(
&mut fresh,
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("second");
assert_eq!(map.zones_for(1), vec![1]);
// The stored file describes two zones; asking for three must not reuse it.
let mut three = CountingBackend {
duty: vec![100, 100],
owners: vec![(0, 0), (1, 1)],
calls: 0,
};
let _ = ensure_map(
&mut three,
&config(3),
MapThresholds::default(),
&file,
|_| {},
);
assert!(three.calls > 0);
let _ = std::fs::remove_file(&file);
}
#[test]
fn samples_from_a_sweep_still_map_correctly() {
let samples = vec![
ProbeSample {
fan: 0,
pwm: 40,
readings: vec![ZoneReading {
zone: 0,
temp_mc: 70_000,
}],
},
ProbeSample {
fan: 0,
pwm: 100,
readings: vec![ZoneReading {
zone: 0,
temp_mc: 50_000,
}],
},
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
}
}
+332
View File
@@ -0,0 +1,332 @@
// SPDX-License-Identifier: MIT
//! Fault-tolerance supervisor.
//!
//! The goal is to keep hashing with as many dead chips or chains as possible. Faults therefore
//! escalate in steps (retry, disable chip, disable chain) and only irreversible conditions stop the
//! machine. This module owns that ladder; it does not talk to hardware and it does not choose
//! thermal limits, which come from the profile envelope.
/// A single health observation from the mining loop.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FaultEvent {
/// A chain accepted work and reported nonces for it.
NoncesReported { chain: u8, per_mille: u16 },
/// A chain returned an error for a frame, reset or work dispatch.
ChainError { chain: u8 },
/// A chain produced nothing for a full observation window.
ChainSilent { chain: u8 },
/// One chip on a chain failed its identification or stopped responding.
ChipFault { chain: u8, chip: u16 },
/// A temperature reading left the profile envelope.
TemperatureFault { zone: u8 },
}
/// What the caller should do next.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FaultAction {
/// Keep hashing; nothing changed.
None,
/// Retry the chain before treating the fault as permanent.
Retry { chain: u8 },
/// Keep the machine running without this chain.
DisableChain { chain: u8 },
/// Keep the machine running without this chip.
DisableChip { chain: u8, chip: u16 },
/// Stop hashing entirely; the reason is carried for the API.
Stop { reason: StopReason },
}
/// Why the machine stopped.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StopReason {
Temperature,
NoChainsLeft,
}
/// Thresholds for escalation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FaultPolicy {
/// Consecutive errors tolerated before the chain is disabled (retries included).
pub retries: u8,
/// Nonce-response ratio below which a chain is considered stalled.
pub min_response_per_mille: u16,
/// Consecutive weak windows before a stalled chain is disabled.
pub weak_windows: u8,
}
impl Default for FaultPolicy {
fn default() -> Self {
Self {
retries: 2,
min_response_per_mille: 100,
weak_windows: 3,
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct ChainHealth {
chain: u8,
errors: u8,
weak: u8,
disabled: bool,
}
/// Escalation state for one machine.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FaultSupervisor {
policy: FaultPolicy,
chains: Vec<ChainHealth>,
stopped: Option<StopReason>,
}
impl FaultSupervisor {
pub fn new(chains: &[u8], policy: FaultPolicy) -> Self {
Self {
policy,
chains: chains
.iter()
.map(|&chain| ChainHealth {
chain,
..ChainHealth::default()
})
.collect(),
stopped: None,
}
}
pub fn is_stopped(&self) -> bool {
self.stopped.is_some()
}
pub fn stop_reason(&self) -> Option<StopReason> {
self.stopped
}
/// Chains the miner may still dispatch work to.
pub fn active_chains(&self) -> Vec<u8> {
self.chains
.iter()
.filter(|health| !health.disabled)
.map(|health| health.chain)
.collect()
}
/// Apply one observation and return the escalation step it implies.
pub fn observe(&mut self, event: FaultEvent) -> FaultAction {
if self.stopped.is_some() {
return FaultAction::None;
}
match event {
FaultEvent::NoncesReported { chain, per_mille } => {
let min_response = self.policy.min_response_per_mille;
let weak_windows = self.policy.weak_windows;
let Some(health) = self.health_mut(chain) else {
return FaultAction::None;
};
health.errors = 0;
if per_mille >= min_response {
health.weak = 0;
return FaultAction::None;
}
health.weak = health.weak.saturating_add(1);
if health.weak >= weak_windows {
health.disabled = true;
self.maybe_stop(chain)
} else {
FaultAction::None
}
}
FaultEvent::ChainError { chain } | FaultEvent::ChainSilent { chain } => {
let policy = self.policy;
let Some(health) = self.health_mut(chain) else {
return FaultAction::None;
};
if health.disabled {
return FaultAction::None;
}
health.errors = health.errors.saturating_add(1);
if health.errors > policy.retries {
health.disabled = true;
self.maybe_stop(chain)
} else {
FaultAction::Retry { chain }
}
}
FaultEvent::ChipFault { chain, chip } => FaultAction::DisableChip { chain, chip },
FaultEvent::TemperatureFault { .. } => {
self.stopped = Some(StopReason::Temperature);
FaultAction::Stop {
reason: StopReason::Temperature,
}
}
}
}
fn health_mut(&mut self, chain: u8) -> Option<&mut ChainHealth> {
self.chains.iter_mut().find(|health| health.chain == chain)
}
fn maybe_stop(&mut self, chain: u8) -> FaultAction {
if self.chains.iter().all(|health| health.disabled) {
self.stopped = Some(StopReason::NoChainsLeft);
return FaultAction::Stop {
reason: StopReason::NoChainsLeft,
};
}
FaultAction::DisableChain { chain }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn supervisor() -> FaultSupervisor {
FaultSupervisor::new(&[0, 1, 2], FaultPolicy::default())
}
#[test]
fn transient_errors_retry_then_disable_the_chain() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 1 }),
FaultAction::Retry { chain: 1 }
);
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 1 }),
FaultAction::Retry { chain: 1 }
);
assert_eq!(
faults.observe(FaultEvent::ChainSilent { chain: 1 }),
FaultAction::DisableChain { chain: 1 }
);
assert_eq!(faults.active_chains(), vec![0, 2]);
}
#[test]
fn healthy_nonces_reset_the_error_count() {
let mut faults = supervisor();
faults.observe(FaultEvent::ChainError { chain: 0 });
faults.observe(FaultEvent::ChainError { chain: 0 });
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 900
}),
FaultAction::None
);
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 0 }),
FaultAction::Retry { chain: 0 }
);
}
#[test]
fn a_stalled_chain_is_disabled_after_repeated_weak_windows() {
let mut faults = supervisor();
for _ in 0..2 {
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 2,
per_mille: 10
}),
FaultAction::None
);
}
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 2,
per_mille: 10
}),
FaultAction::DisableChain { chain: 2 }
);
assert_eq!(faults.active_chains(), vec![0, 1]);
}
#[test]
fn one_good_window_clears_weak_history() {
let mut faults = supervisor();
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 900,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10,
});
assert_eq!(
faults.observe(FaultEvent::NoncesReported {
chain: 0,
per_mille: 10
}),
FaultAction::DisableChain { chain: 0 }
);
}
#[test]
fn a_chip_fault_disables_only_that_chip() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::ChipFault { chain: 1, chip: 42 }),
FaultAction::DisableChip { chain: 1, chip: 42 }
);
assert_eq!(faults.active_chains(), vec![0, 1, 2]);
}
#[test]
fn temperature_fault_stops_the_machine() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::TemperatureFault { zone: 2 }),
FaultAction::Stop {
reason: StopReason::Temperature
}
);
assert!(faults.is_stopped());
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 0 }),
FaultAction::None
);
}
#[test]
fn losing_every_chain_stops_instead_of_hanging() {
let mut faults = FaultSupervisor::new(
&[0],
FaultPolicy {
retries: 0,
..FaultPolicy::default()
},
);
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 0 }),
FaultAction::Stop {
reason: StopReason::NoChainsLeft
}
);
assert_eq!(faults.active_chains(), Vec::<u8>::new());
}
#[test]
fn unknown_chains_are_ignored() {
let mut faults = supervisor();
assert_eq!(
faults.observe(FaultEvent::ChainError { chain: 9 }),
FaultAction::None
);
assert_eq!(faults.active_chains(), vec![0, 1, 2]);
}
}
+218
View File
@@ -0,0 +1,218 @@
// SPDX-License-Identifier: MIT
//! HAL conformance checks.
//!
//! A family backend is only useful if it answers the contract the OS expects. This module walks the
//! contract in order and reports each check separately, so a backend author sees exactly which
//! opcode is missing or wrong instead of a single opaque failure.
//!
//! Every check uses a fresh connection: a backend that desynchronises one exchange must not make
//! the following checks meaningless.
use crate::hal_wire::{HalClient, CAP_CHAIN_PROBE, CAP_FREQUENCY, CAP_POWER, CAP_PSU_IDENTITY};
use crate::HardwareBackend;
use std::path::Path;
/// One check and its outcome.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Check {
pub name: &'static str,
pub passed: bool,
pub detail: String,
}
impl Check {
fn pass(name: &'static str, detail: impl Into<String>) -> Self {
Self {
name,
passed: true,
detail: detail.into(),
}
}
fn fail(name: &'static str, detail: impl Into<String>) -> Self {
Self {
name,
passed: false,
detail: detail.into(),
}
}
}
/// Run the contract checks against a backend socket.
pub fn run(socket: &Path) -> Vec<Check> {
vec![
check_capabilities(socket),
check_probe(socket),
check_eeprom(socket),
check_psu(socket),
check_frequency_and_temperature(socket),
check_power(socket),
check_fan(socket),
]
}
fn connect(socket: &Path) -> Result<HalClient, String> {
HalClient::connect(socket).map_err(|error| format!("{error:?}"))
}
fn check_capabilities(socket: &Path) -> Check {
const NAME: &str = "capabilities";
match connect(socket)
.and_then(|mut client| client.capabilities().map_err(|error| format!("{error:?}")))
{
Ok(mask) if mask & CAP_CHAIN_PROBE == 0 => {
Check::fail(NAME, format!("mask {mask:#x} lacks chain probing"))
}
Ok(mask) => Check::pass(NAME, format!("mask {mask:#x}")),
Err(error) => Check::fail(NAME, error),
}
}
fn check_probe(socket: &Path) -> Check {
const NAME: &str = "probe chain 0";
match connect(socket) {
Ok(mut client) => match client.probe_chain(0, 0) {
Ok(outcome) => Check::pass(NAME, format!("{outcome:?}")),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_eeprom(socket: &Path) -> Check {
const NAME: &str = "read EEPROM chain 0";
match connect(socket) {
Ok(mut client) => match client.read_eeprom(0) {
Ok(state) => Check::pass(NAME, format!("{state:?}")),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_psu(socket: &Path) -> Check {
const NAME: &str = "identify PSU";
match connect(socket) {
Ok(mut client) => match client.capabilities() {
Ok(mask) if mask & CAP_PSU_IDENTITY == 0 => {
Check::fail(NAME, "backend does not advertise PSU identity")
}
Ok(_) => match client.identify_psu() {
Ok(psu) if psu.envelope.v_min_mv <= psu.envelope.v_max_mv => {
Check::pass(NAME, format!("{} {} mV", psu.name, psu.envelope.v_max_mv))
}
Ok(psu) => Check::fail(NAME, format!("inverted envelope from {}", psu.name)),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_frequency_and_temperature(socket: &Path) -> Check {
const NAME: &str = "frequency and temperature";
match connect(socket) {
Ok(mut client) => {
let caps = match client.capabilities() {
Ok(mask) => mask,
Err(error) => return Check::fail(NAME, format!("{error:?}")),
};
if caps & CAP_FREQUENCY == 0 {
return Check::fail(NAME, "backend does not advertise frequency control");
}
if let Err(error) = client.set_chain_frequency(0, 500) {
return Check::fail(NAME, format!("set frequency: {error:?}"));
}
match client.read_temperature_mc(0) {
Ok(value) if (-40_000..=150_000).contains(&value) => {
Check::pass(NAME, format!("500 MHz, {} mC", value))
}
Ok(value) => Check::fail(NAME, format!("implausible temperature {value} mC")),
Err(error) => Check::fail(NAME, format!("read temperature: {error:?}")),
}
}
Err(error) => Check::fail(NAME, error),
}
}
fn check_power(socket: &Path) -> Check {
const NAME: &str = "read power";
match connect(socket) {
Ok(mut client) => match client.capabilities() {
Ok(mask) if mask & CAP_POWER == 0 => {
Check::fail(NAME, "backend does not advertise power telemetry")
}
Ok(_) => {
// Ask for a known operating point first: a backend that always reports 0 W would
// otherwise pass a range check while being useless to a power-target loop.
if let Err(error) = client.set_chain_frequency(0, 500) {
return Check::fail(NAME, format!("set frequency: {error:?}"));
}
std::thread::sleep(std::time::Duration::from_millis(50));
match client.read_power_w() {
Ok(0) => Check::fail(NAME, "reports 0 W at 500 MHz"),
Ok(watts) if watts <= 10_000 => {
Check::pass(NAME, format!("{watts} W at 500 MHz"))
}
Ok(watts) => Check::fail(NAME, format!("implausible power {watts} W")),
Err(error) => Check::fail(NAME, format!("{error:?}")),
}
}
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
fn check_fan(socket: &Path) -> Check {
const NAME: &str = "fan target";
match connect(socket) {
Ok(mut client) => match client.set_fan_target(0, 100) {
Ok(()) => Check::pass(NAME, "100 percent accepted"),
Err(error) => Check::fail(NAME, format!("{error:?}")),
},
Err(error) => Check::fail(NAME, error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hal_sim::{serve, SimConfig};
fn socket(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("alkane-conf-{}-{name}.sock", std::process::id()))
}
#[test]
fn the_reference_server_passes_every_check() {
let path = socket("ok");
let server_path = path.clone();
let server = std::thread::spawn(move || {
let _ = serve(&server_path, SimConfig::default());
});
// The reference server binds inside serve(); wait for the socket to exist.
for _ in 0..100 {
if path.exists() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
let checks = run(&path);
let failed: Vec<&Check> = checks.iter().filter(|check| !check.passed).collect();
assert!(failed.is_empty(), "reference server failed: {failed:?}");
assert_eq!(checks.len(), 7);
let _ = std::fs::remove_file(&path);
// The server thread is left to exit when the socket disappears.
drop(server);
}
#[test]
fn an_unreachable_socket_fails_every_check() {
let path = socket("missing");
let checks = run(&path);
assert_eq!(checks.len(), 7);
assert!(checks.iter().all(|check| !check.passed));
}
}
+255
View File
@@ -0,0 +1,255 @@
// SPDX-License-Identifier: MIT
//! Reference HAL server.
//!
//! Speaks the same ALKH contract a family backend serves on a real board, but answers from a fixed
//! description of a machine. Two uses: it lets the whole OS path run on any development machine, and
//! it shows a backend author exactly what each opcode must return.
use std::io::{self, Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
const MAGIC: [u8; 4] = *b"ALKH";
const VERSION: u8 = 1;
const RESPONSE: u16 = 1;
const HEADER_LEN: usize = 16;
const SEND_FRAME: u8 = 1;
const RECEIVE_FRAME: u8 = 2;
const SET_CHAIN_RESET: u8 = 3;
const SET_FAN_TARGET: u8 = 4;
const READ_TEMPERATURE: u8 = 5;
const SET_PSU_ENABLED: u8 = 6;
const CAPABILITIES: u8 = 7;
const PROBE_CHAIN: u8 = 8;
const READ_EEPROM: u8 = 9;
const IDENTIFY_PSU: u8 = 10;
const SET_CHAIN_FREQUENCY: u8 = 11;
const READ_POWER: u8 = 12;
const CAP_ALL: u32 = (1 << 5) - 1;
/// What the simulated machine looks like.
#[derive(Clone, Debug)]
pub struct SimConfig {
/// Chains that identify. Chains beyond this answer silent.
pub chains: u8,
/// Chips reported per chain.
pub chips: u16,
/// Chip identifier on the wire (1 = bm1362).
pub chip: u8,
/// Report a working EEPROM instead of an absent one.
pub eeprom: bool,
/// PSU name and envelope, or `None` to fail identification.
pub psu: Option<(String, u16, u16, u16, u16, u16)>,
/// Fans on the simulated chassis; zones are distributed over them.
pub fans: u8,
}
impl Default for SimConfig {
fn default() -> Self {
Self {
chains: 3,
chips: 126,
chip: 1,
eeprom: false,
psu: Some(("APW12".into(), 1200, 1600, 0, 1000, 3600)),
fans: 2,
}
}
}
struct State {
config: SimConfig,
frequency_mhz: u16,
/// Duty per fan, so a zone can respond to the fan that actually cools it.
fan_pwm: [u8; 4],
}
impl State {
/// Which fan cools a zone. Zones are distributed over the fans round-robin.
fn owner(&self, zone: u8) -> usize {
let fans = usize::from(self.config.fans.max(1));
usize::from(zone) % fans
}
}
/// Serve one socket path until the program exits.
pub fn serve(path: &Path, config: SimConfig) -> io::Result<()> {
let _ = std::fs::remove_file(path);
let listener = UnixListener::bind(path)?;
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let mut state = State {
config: config.clone(),
frequency_mhz: 0,
fan_pwm: [100; 4],
};
let _ = serve_connection(stream, &mut state);
}
Ok(())
}
fn serve_connection(mut stream: UnixStream, state: &mut State) -> io::Result<()> {
loop {
let mut header = [0_u8; HEADER_LEN];
if stream.read_exact(&mut header).is_err() {
return Ok(());
}
if header[..4] != MAGIC {
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad HAL magic"));
}
let opcode = header[5];
let sequence = header[8..12].to_vec();
let length = u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && stream.read_exact(&mut payload).is_err() {
return Ok(());
}
let body = respond(opcode, &payload, state);
let mut out = [0_u8; HEADER_LEN];
out[..4].copy_from_slice(&MAGIC);
out[4] = VERSION;
out[5] = opcode;
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
stream.write_all(&out)?;
stream.write_all(&body)?;
stream.flush()?;
}
}
fn respond(opcode: u8, payload: &[u8], state: &mut State) -> Vec<u8> {
match opcode {
CAPABILITIES => {
let mut body = vec![0_u8];
body.extend_from_slice(&CAP_ALL.to_le_bytes());
body
}
PROBE_CHAIN => {
let chain = payload.first().copied().unwrap_or(0);
if chain >= state.config.chains {
return vec![0, 1, 0, 0, 0]; // silent
}
let chips = state.config.chips.to_le_bytes();
vec![0, 0, state.config.chip, chips[0], chips[1]]
}
READ_EEPROM => {
if state.config.eeprom {
let mut body = vec![0_u8, 0];
body.extend_from_slice(b"BHB42601");
body
} else {
vec![0, 1]
}
}
IDENTIFY_PSU => match &state.config.psu {
Some((name, v_min, v_max, f_min, f_max, watts)) => {
let mut body = vec![0_u8, name.len() as u8];
body.extend_from_slice(name.as_bytes());
for word in [*v_min, *v_max, *f_min, *f_max, *watts] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
None => vec![1],
},
SET_CHAIN_FREQUENCY => {
if let Some(mhz) = payload.get(1..3) {
state.frequency_mhz = u16::from_le_bytes([mhz[0], mhz[1]]);
}
vec![0]
}
SET_FAN_TARGET => {
let fan = usize::from(payload.first().copied().unwrap_or(0)).min(3);
state.fan_pwm[fan] = payload.get(1).copied().unwrap_or(0);
vec![0]
}
READ_TEMPERATURE => {
// Temperature rises with frequency so the tuner has something to regulate, and falls
// when the fan that owns the zone is fast so the fan sweep can learn the mapping.
let zone = payload.first().copied().unwrap_or(0);
let rise = i32::from(state.frequency_mhz) * 20;
let airflow = if state.fan_pwm[state.owner(zone)] >= 100 {
0
} else {
20_000
};
let mut body = vec![0_u8];
body.extend_from_slice(&(45_000 + rise + airflow).to_le_bytes());
body
}
READ_POWER => {
// Four watts per MHz, so a power target has something to regulate.
let watts = u16::try_from(u32::from(state.frequency_mhz) * 4).unwrap_or(u16::MAX);
let mut body = vec![0_u8];
body.extend_from_slice(&watts.to_le_bytes());
body
}
SET_CHAIN_RESET | SET_PSU_ENABLED => vec![0],
SEND_FRAME => vec![0],
RECEIVE_FRAME => {
// No nonce traffic in the reference backend.
let count: u16 = 0;
let mut body = vec![0_u8];
body.extend_from_slice(&count.to_le_bytes());
body
}
_ => vec![1],
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::FanProbe;
use crate::hal_wire::HalClient;
use crate::HardwareBackend;
#[test]
fn a_client_can_detect_against_the_reference_server() {
let path = std::env::temp_dir().join(format!("alkane-sim-hal-{}.sock", std::process::id()));
// Bind before spawning so the client cannot race the socket into existence.
let listener = UnixListener::bind(&path).expect("bind");
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
let mut state = State {
config: SimConfig::default(),
frequency_mhz: 0,
fan_pwm: [100; 4],
};
let _ = serve_connection(stream, &mut state);
});
let mut client = HalClient::connect(&path).expect("connect");
assert_eq!(client.capabilities().expect("caps"), CAP_ALL);
match client.probe_chain(0, 0).expect("probe") {
crate::detect::ProbeOutcome::Identified { chip, chips } => {
assert_eq!(chip, crate::detect::ChipModel::Bm1362);
assert_eq!(chips, 126);
}
other => panic!("unexpected probe: {other:?}"),
}
assert_eq!(
client.read_eeprom(0).expect("eeprom"),
crate::detect::EepromState::Absent
);
let psu = client.identify_psu().expect("psu");
assert_eq!(psu.name, "APW12");
client.set_chain_frequency(0, 512).expect("freq");
assert_eq!(client.read_power_w().expect("power"), 512 * 4);
// Zone 1 is owned by fan 1: slowing fan 1 must heat zone 1 and not zone 0.
let baseline_0 = client.read_temperature_mc(0).expect("temp");
let baseline_1 = client.read_temperature_mc(1).expect("temp");
client.set_fan(1, 40).expect("fan");
assert_eq!(client.read_temperature_mc(0).expect("temp"), baseline_0);
assert!(client.read_temperature_mc(1).expect("temp") > baseline_1);
assert_eq!(
client.read_temperature_mc(0).expect("temp"),
45_000 + 512 * 20
);
drop(client);
let _ = std::fs::remove_file(&path);
server.join().expect("server");
}
}
+691
View File
@@ -0,0 +1,691 @@
// SPDX-License-Identifier: MIT
//! Versioned local wire contract between Alkane OS and an SDK hardware backend.
use crate::detect::{
ChipModel, DetectionBackend, EepromState, Envelope, ProbeOutcome, PsuCapability,
};
use crate::HardwareBackend;
use std::fmt;
use std::io::{self, Read, Write};
use std::net::Shutdown;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::time::{Duration, Instant};
const MAGIC: [u8; 4] = *b"ALKH";
const VERSION: u8 = 1;
const RESPONSE: u16 = 1;
const HEADER_LEN: usize = 16;
const MAX_PAYLOAD: usize = 4096;
const IO_TIMEOUT: Duration = Duration::from_secs(2);
const SEND_FRAME: u8 = 1;
const RECEIVE_FRAME: u8 = 2;
const SET_CHAIN_RESET: u8 = 3;
const SET_FAN_TARGET: u8 = 4;
const READ_TEMPERATURE: u8 = 5;
const SET_PSU_ENABLED: u8 = 6;
const CAPABILITIES: u8 = 7;
const PROBE_CHAIN: u8 = 8;
const READ_EEPROM: u8 = 9;
const IDENTIFY_PSU: u8 = 10;
const SET_CHAIN_FREQUENCY: u8 = 11;
const READ_POWER: u8 = 12;
/// Backend feature bits reported by `CAPABILITIES`.
pub const CAP_CHAIN_PROBE: u32 = 1 << 0;
pub const CAP_EEPROM: u32 = 1 << 1;
pub const CAP_PSU_IDENTITY: u32 = 1 << 2;
pub const CAP_FREQUENCY: u32 = 1 << 3;
pub const CAP_POWER: u32 = 1 << 4;
const PROBE_IDENTIFIED: u8 = 0;
const PROBE_SILENT: u8 = 1;
const PROBE_GARBLED: u8 = 2;
const EEPROM_PRESENT: u8 = 0;
const EEPROM_ABSENT: u8 = 1;
const EEPROM_INVALID: u8 = 2;
#[cfg(not(target_os = "linux"))]
compile_error!("Alkane HAL sockets require Linux");
#[cfg(target_os = "linux")]
mod sys {
pub use std::ffi::{c_char as CChar, c_int as CInt, c_void as CVoid};
pub type SaFamily = u16;
pub type SocklenT = u32;
pub const AF_UNIX: CInt = 1;
pub const SOCK_STREAM: CInt = 1;
pub const SOCK_NONBLOCK: CInt = 0x800;
pub const SOCK_CLOEXEC: CInt = 0x80000;
pub const SOL_SOCKET: CInt = 1;
pub const SO_ERROR: CInt = 4;
pub const POLLOUT: i16 = 4;
pub const EAGAIN: CInt = 11;
pub const EISCONN: CInt = 106;
pub const EINPROGRESS: CInt = 115;
#[repr(C)]
pub struct SockaddrUn {
pub sun_family: SaFamily,
pub sun_path: [CChar; 108],
}
#[repr(C)]
pub struct PollFd {
pub fd: CInt,
pub events: i16,
pub revents: i16,
}
extern "C" {
pub fn socket(domain: CInt, socket_type: CInt, protocol: CInt) -> CInt;
pub fn connect(fd: CInt, address: *const CVoid, length: SocklenT) -> CInt;
pub fn poll(fds: *mut PollFd, count: usize, timeout_ms: CInt) -> CInt;
pub fn getsockopt(
fd: CInt,
level: CInt,
name: CInt,
value: *mut CVoid,
length: *mut SocklenT,
) -> CInt;
}
}
#[derive(Debug)]
pub enum HalError {
Io(io::Error),
Protocol(&'static str),
Device(u8),
FrameTooLong,
InvalidFanPercent,
}
impl fmt::Display for HalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => write!(f, "HAL I/O: {error}"),
Self::Protocol(message) => write!(f, "HAL protocol: {message}"),
Self::Device(code) => write!(f, "HAL device error: {code}"),
Self::FrameTooLong => f.write_str("HAL frame exceeds the wire limit"),
Self::InvalidFanPercent => f.write_str("HAL fan target exceeds 100 percent"),
}
}
}
impl std::error::Error for HalError {}
impl From<io::Error> for HalError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
/// Local client for the privileged board backend supplied by the SDK image.
pub struct HalClient {
stream: UnixStream,
sequence: u32,
poisoned: bool,
}
impl HalClient {
fn poison(&mut self) {
self.poisoned = true;
let _ = self.stream.shutdown(Shutdown::Both);
}
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?;
Self::from_stream(stream)
}
pub fn from_stream(stream: UnixStream) -> Result<Self, HalError> {
stream.set_read_timeout(Some(IO_TIMEOUT))?;
stream.set_write_timeout(Some(IO_TIMEOUT))?;
Ok(Self {
stream,
sequence: 0,
poisoned: false,
})
}
fn exchange(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
if self.poisoned {
return Err(HalError::Protocol("connection is unusable"));
}
if payload.len() > MAX_PAYLOAD {
return Err(HalError::FrameTooLong);
}
let result = self.exchange_inner(opcode, payload);
if let Err(ref error) = result {
if !matches!(error, HalError::Device(_)) {
self.poison();
// A backend power lease must expire on disconnect. Reusing a
// desynchronized stream could silently discard an off request.
}
}
result
}
fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
let deadline = Instant::now() + IO_TIMEOUT;
self.sequence = self.sequence.wrapping_add(1);
let sequence = self.sequence;
let mut header = [0_u8; HEADER_LEN];
header[..4].copy_from_slice(&MAGIC);
header[4] = VERSION;
header[5] = opcode;
header[8..12].copy_from_slice(&sequence.to_le_bytes());
header[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
write_all_until(&mut self.stream, &header, deadline)?;
write_all_until(&mut self.stream, payload, deadline)?;
read_exact_until(&mut self.stream, &mut header, deadline)?;
if header[..4] != MAGIC || header[4] != VERSION || header[5] != opcode {
return Err(HalError::Protocol("response identity mismatch"));
}
if u16::from_le_bytes([header[6], header[7]]) != RESPONSE {
return Err(HalError::Protocol("response flag missing"));
}
if u32::from_le_bytes(header[8..12].try_into().unwrap()) != sequence {
return Err(HalError::Protocol("response sequence mismatch"));
}
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
if !(1..=MAX_PAYLOAD).contains(&length) {
return Err(HalError::Protocol("invalid response length"));
}
let mut body = vec![0_u8; length];
read_exact_until(&mut self.stream, &mut body, deadline)?;
if body[0] != 0 {
if !matches!(body[0], 1..=3) || body.len() != 1 {
return Err(HalError::Protocol("invalid error response"));
}
return Err(HalError::Device(body[0]));
}
Ok(body[1..].to_vec())
}
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
if !self.exchange(opcode, payload)?.is_empty() {
self.poison();
return Err(HalError::Protocol("unexpected response data"));
}
Ok(())
}
}
fn timeout_error() -> io::Error {
io::Error::new(io::ErrorKind::TimedOut, "HAL operation timed out")
}
fn remaining(deadline: Instant) -> io::Result<Duration> {
deadline
.checked_duration_since(Instant::now())
.filter(|duration| !duration.is_zero())
.ok_or_else(timeout_error)
}
fn write_all_until(stream: &mut UnixStream, mut data: &[u8], deadline: Instant) -> io::Result<()> {
while !data.is_empty() {
stream.set_write_timeout(Some(remaining(deadline)?))?;
match stream.write(data) {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"HAL socket closed",
))
}
Ok(count) => data = &data[count..],
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
}
Ok(())
}
fn read_exact_until(
stream: &mut UnixStream,
mut data: &mut [u8],
deadline: Instant,
) -> io::Result<()> {
while !data.is_empty() {
stream.set_read_timeout(Some(remaining(deadline)?))?;
match stream.read(data) {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"HAL socket closed",
))
}
Ok(count) => data = &mut data[count..],
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
}
Ok(())
}
fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
let bytes = path.as_os_str().as_bytes();
let max_path =
std::mem::size_of::<sys::SockaddrUn>() - std::mem::offset_of!(sys::SockaddrUn, sun_path);
if bytes.is_empty() || bytes.len() >= max_path || bytes.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid HAL socket path",
));
}
let raw = unsafe {
sys::socket(
sys::AF_UNIX,
sys::SOCK_STREAM | sys::SOCK_NONBLOCK | sys::SOCK_CLOEXEC,
0,
)
};
if raw < 0 {
return Err(io::Error::last_os_error());
}
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
let mut address: sys::SockaddrUn = unsafe { std::mem::zeroed() };
address.sun_family = sys::AF_UNIX as sys::SaFamily;
for (destination, source) in address.sun_path.iter_mut().zip(bytes) {
*destination = *source as sys::CChar;
}
let length =
(std::mem::offset_of!(sys::SockaddrUn, sun_path) + bytes.len() + 1) as sys::SocklenT;
loop {
let result = unsafe {
sys::connect(
fd.as_raw_fd(),
&address as *const _ as *const sys::CVoid,
length,
)
};
if result == 0 {
break;
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(sys::EISCONN) {
break;
}
if !matches!(
error.raw_os_error(),
Some(sys::EINPROGRESS) | Some(sys::EAGAIN)
) {
return Err(error);
}
let mut poll_fd = sys::PollFd {
fd: fd.as_raw_fd(),
events: sys::POLLOUT,
revents: 0,
};
let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32;
let polled = unsafe { sys::poll(&mut poll_fd, 1, wait.max(1)) };
if polled < 0 {
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted {
continue;
}
return Err(error);
}
if polled == 0 {
return Err(timeout_error());
}
let mut socket_error: sys::CInt = 0;
let mut socket_error_len = std::mem::size_of_val(&socket_error) as sys::SocklenT;
if unsafe {
sys::getsockopt(
fd.as_raw_fd(),
sys::SOL_SOCKET,
sys::SO_ERROR,
&mut socket_error as *mut _ as *mut sys::CVoid,
&mut socket_error_len,
)
} < 0
{
return Err(io::Error::last_os_error());
}
if socket_error != 0 {
return Err(io::Error::from_raw_os_error(socket_error));
}
if error.raw_os_error() == Some(sys::EINPROGRESS) {
break;
}
}
let stream = UnixStream::from(fd);
stream.set_nonblocking(false)?;
Ok(stream)
}
impl HalClient {
/// Feature mask advertised by the backend. Old backends reject the opcode, which surfaces as
/// a protocol error rather than a silent zero.
pub fn capabilities(&mut self) -> Result<u32, HalError> {
let body = self.exchange(CAPABILITIES, &[])?;
let bytes: [u8; 4] = body
.try_into()
.map_err(|_| HalError::Protocol("invalid capability response"))?;
Ok(u32::from_le_bytes(bytes))
}
fn require(&mut self, capability: u32) -> Result<(), HalError> {
if self.capabilities()? & capability == 0 {
return Err(HalError::Protocol("backend lacks a detection capability"));
}
Ok(())
}
pub fn probe_chain(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, HalError> {
self.require(CAP_CHAIN_PROBE)?;
let body = self.exchange(PROBE_CHAIN, &[chain, attempt])?;
if body.len() != 4 {
self.poison();
return Err(HalError::Protocol("invalid probe response"));
}
let chips = u16::from_le_bytes([body[2], body[3]]);
match body[0] {
PROBE_IDENTIFIED => match chip_from_wire(body[1]) {
Some(chip) => Ok(ProbeOutcome::Identified { chip, chips }),
None => {
self.poison();
Err(HalError::Protocol("unknown chip identifier"))
}
},
PROBE_SILENT => Ok(ProbeOutcome::Silent),
PROBE_GARBLED => Ok(ProbeOutcome::Garbled),
_ => {
self.poison();
Err(HalError::Protocol("invalid probe outcome"))
}
}
}
pub fn read_eeprom(&mut self, chain: u8) -> Result<EepromState, HalError> {
self.require(CAP_EEPROM)?;
let body = self.exchange(READ_EEPROM, &[chain])?;
match body.first().copied() {
Some(EEPROM_ABSENT) if body.len() == 1 => Ok(EepromState::Absent),
Some(EEPROM_INVALID) if body.len() == 1 => Ok(EepromState::Invalid),
Some(EEPROM_PRESENT) if body.len() > 1 => {
let model = std::str::from_utf8(&body[1..])
.map_err(|_| HalError::Protocol("invalid EEPROM model text"))?;
Ok(EepromState::Present {
model: model.to_owned(),
})
}
_ => {
self.poison();
Err(HalError::Protocol("invalid EEPROM response"))
}
}
}
/// Apply a chain frequency in MHz. The backend owns the PLL write; the OS owns the decision.
pub fn set_chain_frequency(&mut self, chain: u8, mhz: u16) -> Result<(), HalError> {
self.require(CAP_FREQUENCY)?;
let mut payload = [0_u8; 3];
payload[0] = chain;
payload[1..].copy_from_slice(&mhz.to_le_bytes());
self.empty_reply(SET_CHAIN_FREQUENCY, &payload)
}
/// Measured DC input power in watts, when the board can read its PSU.
pub fn read_power_w(&mut self) -> Result<u16, HalError> {
self.require(CAP_POWER)?;
let body = self.exchange(READ_POWER, &[])?;
if body.len() != 2 {
self.poison();
return Err(HalError::Protocol("invalid power response"));
}
Ok(u16::from_le_bytes([body[0], body[1]]))
}
pub fn identify_psu(&mut self) -> Result<PsuCapability, HalError> {
self.require(CAP_PSU_IDENTITY)?;
let body = self.exchange(IDENTIFY_PSU, &[])?;
let name_len = *body
.first()
.ok_or(HalError::Protocol("empty PSU response"))? as usize;
if body.len() != name_len + 1 + 10 {
self.poison();
return Err(HalError::Protocol("invalid PSU response"));
}
let name = std::str::from_utf8(&body[1..1 + name_len])
.map_err(|_| HalError::Protocol("invalid PSU name"))?
.to_owned();
let at = 1 + name_len;
let word = |offset: usize| u16::from_le_bytes([body[at + offset], body[at + offset + 1]]);
Ok(PsuCapability {
name,
envelope: Envelope {
v_min_mv: word(0),
v_max_mv: word(2),
f_min_mhz: word(4),
f_max_mhz: word(6),
},
max_dc_watts: word(8),
})
}
}
impl DetectionBackend for HalClient {
type Error = HalError;
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error> {
self.probe_chain(chain, attempt)
}
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error> {
self.read_eeprom(chain)
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error> {
self.identify_psu().map(Some)
}
}
impl crate::fanmap::FanProbe for HalClient {
type Error = HalError;
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> {
self.set_fan_target(fan, pwm)
}
fn read_zone(&mut self, zone: u8) -> Result<i32, Self::Error> {
self.read_temperature_mc(zone)
}
}
fn chip_from_wire(value: u8) -> Option<ChipModel> {
match value {
1 => Some(ChipModel::Bm1362),
2 => Some(ChipModel::Bm1366),
3 => Some(ChipModel::Bm1368),
4 => Some(ChipModel::Bm1370),
5 => Some(ChipModel::Bm1398),
_ => None,
}
}
impl HardwareBackend for HalClient {
type Error = HalError;
fn send_frame(&mut self, chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
if frame.len() > MAX_PAYLOAD - 3 {
return Err(HalError::FrameTooLong);
}
let mut body = Vec::with_capacity(frame.len() + 3);
body.push(chain);
body.extend_from_slice(&(frame.len() as u16).to_le_bytes());
body.extend_from_slice(frame);
self.empty_reply(SEND_FRAME, &body)
}
fn receive_frame(&mut self, chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
if frame.len() > MAX_PAYLOAD - 3 {
return Err(HalError::FrameTooLong);
}
let mut request = [0_u8; 3];
request[0] = chain;
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
let body = self.exchange(RECEIVE_FRAME, &request)?;
if body.len() < 2 {
self.poison();
return Err(HalError::Protocol("missing receive length"));
}
let count = u16::from_le_bytes([body[0], body[1]]) as usize;
if count > frame.len() || body.len() != count + 2 {
self.poison();
return Err(HalError::Protocol("invalid received frame size"));
}
frame[..count].copy_from_slice(&body[2..]);
Ok(count)
}
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error> {
self.empty_reply(SET_CHAIN_RESET, &[chain, u8::from(asserted)])
}
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error> {
if percent > 100 {
return Err(HalError::InvalidFanPercent);
}
self.empty_reply(SET_FAN_TARGET, &[fan, percent])
}
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error> {
let body = self.exchange(READ_TEMPERATURE, &[sensor])?;
let bytes: [u8; 4] = match body.try_into() {
Ok(bytes) => bytes,
Err(_) => {
self.poison();
return Err(HalError::Protocol("invalid temperature response"));
}
};
Ok(i32::from_le_bytes(bytes))
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
let result = self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]);
if !enabled && result.is_err() {
self.poison();
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::FanProbe;
use std::os::unix::net::UnixStream;
fn mock_backend(mut server: UnixStream) {
loop {
let mut header = [0_u8; 16];
if server.read_exact(&mut header).is_err() {
return;
}
let opcode = header[5];
let sequence = [header[8], header[9], header[10], header[11]];
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && server.read_exact(&mut payload).is_err() {
return;
}
let body: Vec<u8> = match opcode {
CAPABILITIES => {
let mut body = vec![0_u8];
body.extend_from_slice(
&(CAP_CHAIN_PROBE
| CAP_EEPROM
| CAP_PSU_IDENTITY
| CAP_FREQUENCY
| CAP_POWER)
.to_le_bytes(),
);
body
}
PROBE_CHAIN => vec![0, PROBE_IDENTIFIED, 1, 126, 0],
READ_EEPROM => {
let mut body = vec![0, EEPROM_PRESENT];
body.extend_from_slice(b"BHB42601");
body
}
IDENTIFY_PSU => {
let name = b"APW12";
let mut body = vec![0_u8];
body.push(name.len() as u8);
body.extend_from_slice(name);
for word in [1200_u16, 1600, 0, 1000, 3600] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
SET_FAN_TARGET | SET_CHAIN_FREQUENCY => vec![0],
READ_POWER => {
let mut body = vec![0_u8];
body.extend_from_slice(&0_u16.to_le_bytes());
body
}
READ_TEMPERATURE => {
let mut body = vec![0_u8];
body.extend_from_slice(&42_000_i32.to_le_bytes());
body
}
_ => vec![1],
};
let mut out = [0_u8; 16];
out[..4].copy_from_slice(&MAGIC);
out[4] = VERSION;
out[5] = opcode;
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
if server.write_all(&out).is_err() || server.write_all(&body).is_err() {
return;
}
}
}
#[test]
fn detection_verbs_round_trip_over_the_wire() {
let (client_stream, server_stream) = UnixStream::pair().expect("socket pair");
let server = std::thread::spawn(move || mock_backend(server_stream));
let mut client = HalClient::from_stream(client_stream).expect("client");
assert_eq!(
client.capabilities().expect("capabilities"),
CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY | CAP_POWER
);
match client.probe_chain(0, 0).expect("probe") {
ProbeOutcome::Identified { chip, chips } => {
assert_eq!(chip, ChipModel::Bm1362);
assert_eq!(chips, 126);
}
other => panic!("unexpected probe outcome: {other:?}"),
}
assert_eq!(
client.read_eeprom(0).expect("eeprom"),
EepromState::Present {
model: "BHB42601".into()
}
);
let psu = client.identify_psu().expect("psu");
assert_eq!(psu.name, "APW12");
assert_eq!(psu.envelope.v_min_mv, 1200);
assert_eq!(psu.envelope.v_max_mv, 1600);
assert_eq!(psu.max_dc_watts, 3600);
client.set_chain_frequency(2, 512).expect("set frequency");
client.set_fan(1, 60).expect("set fan");
assert_eq!(client.read_zone(2).expect("read zone"), 42_000);
drop(client);
server.join().expect("server thread");
}
}
+259
View File
@@ -0,0 +1,259 @@
//! Board independent policy and hardware interfaces for Alkane OS.
//!
//! An entry in the target matrix is a development obligation, not a claim that
//! the pairing already mines. Hardware backends are supplied by SDK images.
pub mod app;
pub mod bm1362;
pub mod bm1366;
pub mod bm1370;
pub mod bm13xx;
pub mod detect;
pub mod dashboard;
pub mod difficulty;
pub mod fanmap;
pub mod fanmap_store;
pub mod fault;
pub mod hal_conformance;
pub mod hal_sim;
pub mod hal_wire;
pub mod management;
pub mod miner;
pub mod pow;
pub mod profiles;
pub mod runtime;
pub mod scrypt_pow;
pub mod split;
pub mod stratum_client;
pub mod stratum_link;
pub mod stratum_session;
pub mod stratum_submit;
pub mod stratum_v1;
pub mod stratum_v2;
pub mod stratum_v2_session;
pub mod stratum_wire;
pub mod stratum_work;
pub mod tuning;
pub mod ui;
pub mod web;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vendor {
Bitmain,
Whatsminer,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Algorithm {
Sha256,
Scrypt,
Equihash,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ControlBoard {
pub id: &'static str,
pub vendor: Vendor,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HashChip {
pub id: &'static str,
pub vendor: Vendor,
pub algorithm: Algorithm,
}
pub const CONTROL_BOARDS: [ControlBoard; 7] = [
ControlBoard {
id: "am335x-bb",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "zynq-7010",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "cv1835",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "a113d",
vendor: Vendor::Bitmain,
},
ControlBoard {
id: "allwinner-h3",
vendor: Vendor::Whatsminer,
},
ControlBoard {
id: "allwinner-h6",
vendor: Vendor::Whatsminer,
},
ControlBoard {
id: "allwinner-h616",
vendor: Vendor::Whatsminer,
},
];
pub const HASH_CHIPS: [HashChip; 17] = [
HashChip {
id: "BM1384",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1387",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1360",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1362",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1366",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1368",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1370",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1396",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1397",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1398",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "BM1489",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Scrypt,
},
HashChip {
id: "BM1491",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Scrypt,
},
HashChip {
id: "BM1746",
vendor: Vendor::Bitmain,
algorithm: Algorithm::Equihash,
},
HashChip {
id: "KF1950",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "ID-1968",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "ID-1980",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
HashChip {
id: "ID-1990",
vendor: Vendor::Whatsminer,
algorithm: Algorithm::Sha256,
},
];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Target {
pub control: ControlBoard,
pub chip: HashChip,
}
impl Target {
pub fn new(control: ControlBoard, chip: HashChip) -> Option<Self> {
(control.vendor == chip.vendor).then_some(Self { control, chip })
}
}
/// Every same-vendor theoretical pairing is in scope for Alkane OS.
pub fn target_matrix() -> impl Iterator<Item = Target> {
CONTROL_BOARDS.into_iter().flat_map(|control| {
HASH_CHIPS
.into_iter()
.filter_map(move |chip| Target::new(control, chip))
})
}
/// Hardware operations implemented by a board backend in the SDK image.
/// The methods deliberately expose no assumed UART, FPGA or Bitmicro layout.
pub trait HardwareBackend {
type Error;
fn send_frame(&mut self, chain: u8, frame: &[u8]) -> Result<(), Self::Error>;
fn receive_frame(&mut self, chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error>;
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error>;
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error>;
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error>;
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error>;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PowerDecision {
Hold,
Stop,
}
/// A safe starting policy: no hashing while temperature is unknown or unsafe.
/// Board-specific thresholds will come from measured, revision-specific data.
pub fn power_decision(temperature_mc: Option<i32>, max_mc: i32) -> PowerDecision {
match temperature_mc {
Some(value) if value < max_mc => PowerDecision::Hold,
_ => PowerDecision::Stop,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_theoretical_same_vendor_targets_are_included() {
let targets: Vec<_> = target_matrix().collect();
assert_eq!(targets.len(), 4 * 13 + 3 * 4);
assert!(targets.iter().all(|t| t.control.vendor == t.chip.vendor));
for control in CONTROL_BOARDS {
for chip in HASH_CHIPS {
assert_eq!(
targets.contains(&Target { control, chip }),
control.vendor == chip.vendor
);
}
}
}
#[test]
fn unknown_or_hot_sensor_stops_power() {
assert_eq!(power_decision(None, 80_000), PowerDecision::Stop);
assert_eq!(power_decision(Some(80_000), 80_000), PowerDecision::Stop);
assert_eq!(power_decision(Some(79_999), 80_000), PowerDecision::Hold);
}
}

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