Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c23ce847d | ||
|
|
6a466a611f | ||
|
|
1300d7e372 | ||
|
|
66e4f3d47a | ||
|
|
37028cc3eb | ||
|
|
0e6fd9269b | ||
|
|
3d63bbb3eb | ||
|
|
5d8f14c992 | ||
|
|
6f87f48dca |
@@ -5,6 +5,10 @@ on:
|
||||
workflows: [main-release-gate, next-build]
|
||||
types: [completed]
|
||||
|
||||
concurrency:
|
||||
group: alkane-os-completed-ci-badge
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-ci
|
||||
|
||||
@@ -3,4 +3,5 @@
|
||||
- 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.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Alkane OS
|
||||
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-os/actions)
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-os/actions)
|
||||

|
||||

|
||||

|
||||
@@ -10,102 +10,58 @@
|
||||

|
||||

|
||||
|
||||
Portable mining, tuning, and management logic for Alkane control boards. The
|
||||
source is MIT licensed. `alkane-sdk` owns the board images and supplies the
|
||||
hardware backend at build time. This repository has no on-board web frontend;
|
||||
the intended management surfaces are SSH, cgminer-compatible port 4028, and a
|
||||
minimal API.
|
||||
Mining and tuning core for Alkane control boards. The SDK builds board images
|
||||
and supplies the hardware backend. Management is planned over SSH, a
|
||||
cgminer-compatible port 4028, and a minimal API; no web frontend runs on the
|
||||
board.
|
||||
|
||||
## Status
|
||||
|
||||
This is an early mining core and release tooling, not a complete daemon. A
|
||||
target in the matrix is an obligation to implement and validate, not a claim
|
||||
of support. All 64 theoretical same-vendor controller/chip pairings are in
|
||||
scope: 52 Bitmain and 12 WhatsMiner. For pairings a stock image rejects, the
|
||||
simulator must record the first genuine rejection gate and Alkane OS must mine.
|
||||
No live board is required by CI. Bench devices supply captures and independent
|
||||
validation of the simulator.
|
||||
The CLI lists target obligations with `alkane-os --list-targets`. It can also
|
||||
mine through the SDK simulator HAL and a Stratum V1 pool. No production board
|
||||
backend or network management API is installed.
|
||||
|
||||
The current executable lists target obligations (`alkane-os --list-targets`)
|
||||
and its version. It does not start a miner or a network service. The library
|
||||
now includes a versioned local Unix-socket client for the SDK hardware
|
||||
backend, with bounded frames, two-second I/O timeouts, and fail-closed
|
||||
response validation. The matching SDK server framing library exists, but no
|
||||
board adapter is installed in an image yet.
|
||||
The library can also verify an ASIC-reported SHA-256d share against an exact
|
||||
pool target, including BM13xx version rolling. Host probes check captured
|
||||
BM1362 and BM1366 nonces through the SDK's C/Python HAL replay server. From
|
||||
this repository, run `cargo run --example simulator_replay_probe -- SOCKET_PATH
|
||||
BM1362` or use `BM1366` after starting the corresponding SDK server. This
|
||||
checks shared work/report framing and share validation for those two chips;
|
||||
it does not initialize a physical chip chain.
|
||||
The first BM1366 mining session sequences fan, temperature, PSU, reset,
|
||||
work submission, and nonce polling through the HAL. It rejects stale work IDs,
|
||||
malformed reports, and hashes above the caller's pool target. A sensor fault
|
||||
requests PSU shutdown. A transport fault closes the HAL socket; the backend
|
||||
must end its power lease on disconnect and have an independent hardware
|
||||
watchdog. No production board backend meets that gate yet. The caller must
|
||||
provide a board-validated temperature limit.
|
||||
The library now formats verified shares as Stratum V1 `mining.submit` requests.
|
||||
For negotiated BIP310 version rolling, it includes the sixth version-bits
|
||||
parameter and rejects ASIC versions that the current pool mask cannot
|
||||
represent. The pool transport bounds newline frames and uses absolute socket
|
||||
deadlines. It can negotiate BIP310 extensions, subscribe, and authorize a
|
||||
worker over a live TCP connection while retaining early notifications in wire
|
||||
order. It has loopback tests; no live pool acceptance has been observed yet.
|
||||
The pool connection applies difficulty and job messages in stream order,
|
||||
dispatches work to the BM1366 mining session, and tracks up to 32 verified
|
||||
share submissions by request ID. It counts accepted and rejected pool replies
|
||||
separately. Continuous scheduling and live pool acceptance remain unverified.
|
||||
The SDK's strict loopback pool replay test reconstructs 33 cv.106 BM1366
|
||||
captured jobs from Stratum subscription and notify fields. It delivers those
|
||||
jobs through the OS pool client and HAL simulator, replays the real ASIC
|
||||
nonces, verifies each proof of work independently, and receives 33 matching
|
||||
pool ACCEPT responses. The 33rd job also exercises the chain reset before
|
||||
hardware work ID reuse. This is host-only evidence, not a stock-firmware
|
||||
boot or a production board adapter.
|
||||
The same strict pool fixture reconstructs one BM1362 job with an empty
|
||||
extranonce2 and independently verifies its captured share before returning
|
||||
ACCEPT. This extends the host pool path to a second chip family; physical
|
||||
chain initialization and stock firmware remain unverified. A separate Rust
|
||||
integration test feeds the pinned BM1362 header and 11-byte report through
|
||||
the mining controller's work encoder, report decoder, and proof check.
|
||||
The core also validates a supplied Litecoin Scrypt header using the fixed
|
||||
N=1024, r=1, p=1 algorithm. Its output matches Litecoin's
|
||||
[published block 29255 proof-of-work vector](https://github.com/litecoin-project/litecoin/wiki/Scrypt-proof-of-work)
|
||||
and has a dedicated microbenchmark. This is a
|
||||
share-verification primitive only; BM1489/BM1491 report decoding, pool
|
||||
difficulty conventions, physical chain control, and L7/L9 acceptance remain
|
||||
open.
|
||||
Its cycle helper reads one pool event, drains up to 256 ASIC reports, and sends
|
||||
verified shares when present. A share reply unanswered for 30 seconds closes
|
||||
the connection so a caller can reconnect instead of filling the pending
|
||||
queue indefinitely. Terminal pool errors request miner shutdown, and pool
|
||||
reads use 1 ms slices after the handshake so ASIC polling continues. Partial
|
||||
pool lines have a 2-second deadline and pool writes have a 100 ms deadline.
|
||||
When the 32 hardware work IDs are exhausted, the client checks temperature,
|
||||
resets the chain, discards old reports, and only then reuses an ID for the next
|
||||
job. A reset failure requests PSU shutdown. A host test dispatches 33 jobs
|
||||
and checks the reset boundary; sustained board operation is still unverified.
|
||||
The executable still lacks a board adapter and run loop.
|
||||
The Stratum V1 decoder bounds and validates `mining.subscribe` responses,
|
||||
nine-field Bitcoin `mining.notify` jobs, difficulty and extranonce changes,
|
||||
and negotiated BIP310 version-mask updates. Exact decimal difficulty values
|
||||
become 256-bit pool targets without floating point rounding. Pool job
|
||||
bookkeeping keeps earlier work tied to its original target and extranonce,
|
||||
invalidates old work on `clean_jobs`, and rechecks a reported share before
|
||||
formatting it for submission. It does not reuse ASIC work IDs until the caller
|
||||
confirms a hardware reset. Hardware job dispatch and share reply tracking are
|
||||
library-only so far; continuous mining remains to be implemented.
|
||||
The exact Rust dependency sources are under `vendor/` with Cargo checksums,
|
||||
so SDK board builds can compile offline. Dependencies retain the license terms
|
||||
in their vendored manifests and license files.
|
||||
The library has a versioned Unix-socket HAL client, BM1366 mining-session
|
||||
logic, Stratum V1 job and share handling, SHA-256d share checks for BM1362 and
|
||||
BM1366, and a Litecoin Scrypt proof verifier. Its fault path requests PSU
|
||||
shutdown on a sensor error. Failed shutdown faults the miner until a retry
|
||||
succeeds. Work IDs stay reserved until a confirmed chain reset or PSU
|
||||
shutdown. The backend still needs a power lease, an independent watchdog,
|
||||
and a board-validated temperature limit.
|
||||
|
||||
The `main` branch has full tests and a conformance gate; releases are created
|
||||
only after every required cell passes. `next` runs a build check and produces
|
||||
release candidates. `ci/version-x.txt` is the manually edited major version.
|
||||
For this repository, Y changes when the mining protocol, HAL contract, tuning
|
||||
policy or API changes; Z changes for compatible fixes and packaging updates.
|
||||
Host tests replayed real captured nonces through the SDK HAL and a strict
|
||||
loopback pool: 33 distinct BM1366 shares and one BM1362 share received
|
||||
matching ACCEPT responses. The 33rd BM1366 job tested safe work-ID reuse
|
||||
after a chain reset. These tests do not establish physical chain control,
|
||||
stock-firmware boot, or production pool acceptance. The Scrypt verifier
|
||||
matches Litecoin's
|
||||
[block 29255 vector](https://github.com/litecoin-project/litecoin/wiki/Scrypt-proof-of-work);
|
||||
BM1489/BM1491 report handling and L7/L9 mining remain open.
|
||||
|
||||
For a simulator HAL socket and a Stratum V1 pool, set `ALKANE_POOL_PASSWORD`
|
||||
and run `alkane-os --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER`. The
|
||||
optional fourth argument stops after that many accepted shares. The command
|
||||
uses the simulator's 80 C temperature limit and exits on a pool or hardware
|
||||
fault. The SDK HAL server must cut power when its client stalls or disconnects.
|
||||
|
||||
## Release gate
|
||||
|
||||
All 64 theoretical same-vendor control-board/chip pairings are required:
|
||||
52 Bitmain and 12 WhatsMiner. A stock image may reject a pairing if the
|
||||
simulator records its first genuine rejection gate; Alkane OS must still
|
||||
mine. CI needs unmodified stock firmware, real captured silicon nonces,
|
||||
pool acceptance at difficulty 1 or higher, and independent bench
|
||||
validation. Bench devices provide captures and validation, not CI execution.
|
||||
The gate is red. See [the evidence contract](ci/CONFORMANCE.md).
|
||||
|
||||
`main` runs tests, benchmarks, and conformance before release. `next`
|
||||
builds release candidates. Edit `ci/version-x.txt` for a major release;
|
||||
increment the minor version for mining protocol, HAL, tuning policy, or API
|
||||
changes, and the patch version for compatible fixes.
|
||||
|
||||
Badges measure host code only. The CI badge shows the last completed branch
|
||||
attempt, and benchmark deltas compare results from the same CPU class. They
|
||||
do not certify board images or the pairing matrix.
|
||||
|
||||
## Local checks
|
||||
|
||||
@@ -113,29 +69,16 @@ policy or API changes; Z changes for compatible fixes and packaging updates.
|
||||
export CARGO_TARGET_DIR=/var/tmp/alkane-os-target
|
||||
cargo fmt --check
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo test
|
||||
cargo test --locked
|
||||
cargo build --release --locked
|
||||
GITHUB_RUN_ID=123 python3 ci/check-conformance.py
|
||||
```
|
||||
|
||||
Use an executable local `CARGO_TARGET_DIR` when the workspace mount strips
|
||||
executable bits. Replace `123` with the numeric ID of the CI run that
|
||||
generated its evidence. The last command currently fails because simulator
|
||||
and device evidence are still pending. It cross-checks the matrix against the built binary's
|
||||
targets and requires per-cell reports from the current CI run, bound to the
|
||||
source commit and binary digest. Referenced artifacts are opened and hashed;
|
||||
SHA-256 captured shares must satisfy a difficulty-one-or-harder target and
|
||||
carry a matching pool ACCEPT response. Scrypt and Equihash verification is
|
||||
pending. It is a release gate, not a unit test. The simulator
|
||||
runner that produces this evidence has not yet been implemented.
|
||||
The required artifact contract is in [ci/CONFORMANCE.md](ci/CONFORMANCE.md).
|
||||
Use an executable target directory if the source mount is `noexec`. The
|
||||
conformance checker requires artifacts from a real CI run; its input format
|
||||
is in [ci/CONFORMANCE.md](ci/CONFORMANCE.md). Rust dependencies are vendored
|
||||
for offline SDK builds and keep their upstream licenses.
|
||||
|
||||
The badges record measured host-side checks for this initial core. They do
|
||||
not imply that any board image or mining target has passed conformance.
|
||||
CI and metric badges are served from a private, machine-maintained branch.
|
||||
The CI badge shows the last completed attempt for this source branch while
|
||||
newer runs are queued; main CI refreshes measured metrics before conformance.
|
||||
Microbenchmarks report the median of seven calibrated samples and compare
|
||||
only with an earlier commit measured on the same CPU class. The code-quality
|
||||
letter requires warnings-denied Clippy to pass and uses measured test line
|
||||
coverage: A at 90%, B at 80%, C at 70%, D at 60%, and F below 60%.
|
||||
## License
|
||||
|
||||
Alkane OS source is [MIT licensed](LICENSE). Vendored dependencies retain
|
||||
their own licenses.
|
||||
|
||||
+6
-2
@@ -18,7 +18,8 @@ The report references files under `ci/evidence/` with objects containing
|
||||
`simulator_model`, `control_capture`, `chip_capture`,
|
||||
`alkane_share_accept_capture`, and `bench_validation`.
|
||||
The checker opens and hashes each file. It loads the trace and capture JSON,
|
||||
checks the current run/image/cell identities, verifies SHA-256d nonces against
|
||||
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
|
||||
@@ -29,7 +30,10 @@ 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.
|
||||
Scrypt and Equihash share verifiers are pending, so those cells fail closed.
|
||||
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.
|
||||
|
||||
+10
-2
@@ -149,8 +149,16 @@ def reconstructed_header(capture: dict, params: list[str]) -> tuple[bytes, int]:
|
||||
return bytes(header), submitted_nonce
|
||||
|
||||
|
||||
def proof_digest(header: bytes, algorithm: str) -> bytes:
|
||||
if algorithm == "Sha256":
|
||||
return hashlib.sha256(hashlib.sha256(header).digest()).digest()
|
||||
if algorithm == "Scrypt":
|
||||
return hashlib.scrypt(header, salt=header, n=1024, r=1, p=1, dklen=32)
|
||||
raise ValueError(f"{algorithm} share verifier is not implemented")
|
||||
|
||||
|
||||
def verify_accept(capture: dict, algorithm: str) -> None:
|
||||
if algorithm != "Sha256":
|
||||
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")
|
||||
@@ -204,7 +212,7 @@ def verify_accept(capture: dict, algorithm: str) -> None:
|
||||
rebuilt, submitted_nonce = reconstructed_header(capture, params)
|
||||
if submitted_nonce != nonce or rebuilt != header:
|
||||
raise ValueError("submitted Stratum job differs from captured header")
|
||||
hash_bytes = hashlib.sha256(hashlib.sha256(header).digest()).digest()
|
||||
hash_bytes = proof_digest(header, algorithm)
|
||||
if int.from_bytes(hash_bytes, "little") > target:
|
||||
raise ValueError("captured nonce misses the pool target")
|
||||
|
||||
|
||||
+17
-3
@@ -64,9 +64,23 @@ class ConformanceGateTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "submitted nonce"):
|
||||
gate.verify_accept(capture, "Sha256")
|
||||
|
||||
def test_non_sha256_cells_need_algorithm_specific_verifiers(self):
|
||||
with self.assertRaisesRegex(ValueError, "Scrypt share verifier"):
|
||||
gate.verify_accept({}, "Scrypt")
|
||||
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")
|
||||
|
||||
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
// 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};
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
+3
-27
@@ -4,6 +4,9 @@
|
||||
pub const WORK_BYTES: usize = 88;
|
||||
pub const REPORT_BYTES: usize = 11;
|
||||
|
||||
pub use crate::bm13xx::crc16;
|
||||
use crate::bm13xx::crc5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct NonceReport {
|
||||
pub nonce: u32,
|
||||
@@ -20,33 +23,6 @@ pub enum ReportError {
|
||||
Checksum,
|
||||
}
|
||||
|
||||
pub fn crc16(bytes: &[u8]) -> u16 {
|
||||
let mut value = 0xffff_u16;
|
||||
for byte in bytes {
|
||||
value ^= u16::from(*byte) << 8;
|
||||
for _ in 0..8 {
|
||||
value = if value & 0x8000 != 0 {
|
||||
(value << 1) ^ 0x1021
|
||||
} else {
|
||||
value << 1
|
||||
};
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn crc5(bytes: &[u8]) -> u8 {
|
||||
let mut value = 0x1f_u8;
|
||||
for byte in bytes {
|
||||
for shift in (0..8).rev() {
|
||||
let feedback = ((value >> 4) ^ (byte >> shift)) & 1;
|
||||
value = ((value << 1) | feedback) & 0x1f;
|
||||
value ^= feedback << 2;
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn reverse_words(input: &[u8]) -> [u8; 32] {
|
||||
let mut output = [0_u8; 32];
|
||||
for index in 0..8 {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Shared BM13xx wire checksums. This module never generates mining nonces.
|
||||
|
||||
/// CRC5 used by command and nonce-report frames, initial value 0x1f.
|
||||
pub fn crc5(bytes: &[u8]) -> u8 {
|
||||
let mut state = 0x1f_u8;
|
||||
for &byte in bytes {
|
||||
for bit in (0..8).rev() {
|
||||
let feedback = ((state >> 4) ^ (byte >> bit)) & 1;
|
||||
state = ((state << 1) | feedback) & 0x1f;
|
||||
state ^= feedback << 2;
|
||||
}
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
/// CRC16-CCITT-FALSE used by 88-byte SEND_JOB frames.
|
||||
pub fn crc16(bytes: &[u8]) -> u16 {
|
||||
let mut state = 0xffff_u16;
|
||||
for &byte in bytes {
|
||||
state ^= u16::from(byte) << 8;
|
||||
for _ in 0..8 {
|
||||
state = if state & 0x8000 == 0 {
|
||||
state << 1
|
||||
} else {
|
||||
(state << 1) ^ 0x1021
|
||||
};
|
||||
}
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn captured_command_checksums() {
|
||||
let vectors: &[(&[u8], u8)] = &[
|
||||
(&[0x53, 0x05, 0, 0], 0x03),
|
||||
(&[0x40, 0x05, 0, 0], 0x1c),
|
||||
(&[0x52, 0x05, 0, 0], 0x0a),
|
||||
(&[0x40, 0x05, 8, 0], 0x07),
|
||||
(&[0x42, 0x05, 0x40, 0x1c], 0x0b),
|
||||
(&[0x51, 0x09, 0, 0x80, 0, 0, 0, 0], 0x1c),
|
||||
(&[0x41, 0x09, 0x40, 0x18, 0, 0, 0x7a, 0x31], 0x11),
|
||||
];
|
||||
for &(body, expected) in vectors {
|
||||
assert_eq!(crc5(body), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_crc16_check() {
|
||||
assert_eq!(crc16(b"123456789"), 0x29b1);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@
|
||||
//! An entry in the target matrix is a development obligation, not a claim that
|
||||
//! the pairing already mines. Hardware backends are supplied by SDK images.
|
||||
|
||||
pub mod bm1362;
|
||||
pub mod bm1366;
|
||||
pub mod bm13xx;
|
||||
pub mod difficulty;
|
||||
pub mod hal_wire;
|
||||
pub mod miner;
|
||||
|
||||
+66
-2
@@ -1,7 +1,65 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
use alkane_os::hal_wire::HalClient;
|
||||
use alkane_os::miner::Bm1366Miner;
|
||||
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
|
||||
use alkane_os::target_matrix;
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
||||
let socket = args.next().ok_or("missing HAL socket")?;
|
||||
let address: SocketAddr = args.next().ok_or("missing pool address")?.parse()?;
|
||||
let worker = args.next().ok_or("missing pool worker")?;
|
||||
let max_accepts: Option<u64> = args.next().map(|value| value.parse()).transpose()?;
|
||||
if args.next().is_some() || worker.is_empty() || max_accepts == Some(0) {
|
||||
return Err("invalid simulator mining arguments".into());
|
||||
}
|
||||
let password = std::env::var("ALKANE_POOL_PASSWORD")
|
||||
.map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?;
|
||||
|
||||
// Connect to the pool before enabling power. The SDK HAL server owns the
|
||||
// power lease and cuts power if this process stalls or disconnects.
|
||||
let mut pool = PoolConnection::connect(
|
||||
address,
|
||||
concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
|
||||
&worker,
|
||||
&password,
|
||||
Duration::from_secs(2),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.map_err(|error| io::Error::other(format!("pool handshake: {error:?}")))?;
|
||||
let mut backend = HalClient::connect(socket)?;
|
||||
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000)
|
||||
.ok_or("invalid simulator safety configuration")?;
|
||||
miner.start()?;
|
||||
let mut accepted = 0_u64;
|
||||
loop {
|
||||
let (event, reports) = pool
|
||||
.cycle(&mut miner)
|
||||
.map_err(|error| io::Error::other(format!("mining cycle: {error:?}")))?;
|
||||
match event {
|
||||
PoolEvent::ShareAccepted(_) => {
|
||||
accepted += 1;
|
||||
if max_accepts == Some(accepted) {
|
||||
miner.stop()?;
|
||||
println!("simulator shares accepted: {accepted}");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
PoolEvent::ShareRejected(id) => eprintln!("pool rejected share request {id}"),
|
||||
_ => {}
|
||||
}
|
||||
if matches!(event, PoolEvent::Idle) && reports.is_empty() {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
let mut args = std::env::args().skip(1);
|
||||
match args.next().as_deref() {
|
||||
Some("--list-targets") => {
|
||||
println!("control_board,hash_chip,algorithm");
|
||||
for target in target_matrix() {
|
||||
@@ -12,8 +70,14 @@ fn main() {
|
||||
}
|
||||
}
|
||||
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
|
||||
Some("--mine-simulator") => {
|
||||
if let Err(error) = sim_mine(args) {
|
||||
eprintln!("simulator mining failed: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: alkane-os --list-targets | --version");
|
||||
eprintln!("usage: alkane-os --list-targets | --version | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER [MAX_ACCEPTS]");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use alkane_os::bm1362::{
|
||||
bt8d_for_baud, chain_inactive, encode_job, read_register, read_register_all, set_chip_address,
|
||||
write_register, write_register_all, Job, S19J_PRO,
|
||||
};
|
||||
use alkane_os::bm1366::{decode_nonce_report, encode_work};
|
||||
use alkane_os::difficulty::PoolDifficulty;
|
||||
use alkane_os::miner::Bm1366Miner;
|
||||
@@ -94,6 +98,39 @@ fn bench_bm1366_work_encoding() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "microbenchmark"]
|
||||
fn bench_bm1362_commands() {
|
||||
measure("bm1362_commands", 20_000, || {
|
||||
black_box(chain_inactive());
|
||||
black_box(set_chip_address(black_box(8)));
|
||||
black_box(read_register(black_box(0x40), 0x1c));
|
||||
black_box(read_register_all(0));
|
||||
black_box(write_register(black_box(0x40), 0x18, 0x7a31));
|
||||
black_box(write_register_all(0x80, 0));
|
||||
black_box(bt8d_for_baud(black_box(115_200)));
|
||||
black_box(S19J_PRO.chip_addresses().last());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "microbenchmark"]
|
||||
fn bench_bm1362_job_encoding() {
|
||||
let job = Job {
|
||||
work_id: 8,
|
||||
num_midstates: 1,
|
||||
start_nonce: 0,
|
||||
nbits: 0x1a1f_2c34,
|
||||
ntime: 0x5e9b_3cd4,
|
||||
merkle_root: [0xa5; 32],
|
||||
previous_hash: [0x5a; 32],
|
||||
version: 0x2000_0000,
|
||||
};
|
||||
measure("bm1362_job_encoding", 20_000, || {
|
||||
black_box(encode_job(black_box(&job)));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "microbenchmark"]
|
||||
fn bench_bm1366_report_decode() {
|
||||
|
||||
Reference in New Issue
Block a user