From a404927a788046a54bd0cefc5f7ccc7fa75e81fc Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:10:06 -0600 Subject: [PATCH 01/83] Add versioned SDK HAL socket client --- README.md | 6 +- src/hal_wire.rs | 196 ++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + tests/hal_wire.rs | 90 +++++++++++++++++++++ 4 files changed, 293 insertions(+), 1 deletion(-) create mode 100644 src/hal_wire.rs create mode 100644 tests/hal_wire.rs diff --git a/README.md b/README.md index 32c0c43..05a57c7 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,11 @@ No live board is required by CI. Bench devices supply captures and independent validation of the simulator. The current executable lists target obligations (`alkane-os --list-targets`) -and its version. It does not start a miner or a network service. +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 `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 diff --git a/src/hal_wire.rs b/src/hal_wire.rs new file mode 100644 index 0000000..555cfe4 --- /dev/null +++ b/src/hal_wire.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: MIT +//! Versioned local wire contract between Alkane OS and an SDK hardware backend. + +use crate::HardwareBackend; +use std::fmt; +use std::io::{self, Read, Write}; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::time::Duration; + +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 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; + +#[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 for HalError { + fn from(error: io::Error) -> Self { + Self::Io(error) + } +} + +/// Local client for the privileged board backend supplied by the SDK image. +pub struct HalClient { + stream: UnixStream, + sequence: u32, + poisoned: bool, +} + +impl HalClient { + pub fn connect(path: impl AsRef) -> Result { + let stream = UnixStream::connect(path)?; + Self::from_stream(stream) + } + + pub fn from_stream(stream: UnixStream) -> Result { + stream.set_read_timeout(Some(Duration::from_secs(2)))?; + stream.set_write_timeout(Some(Duration::from_secs(2)))?; + Ok(Self { + stream, + sequence: 0, + poisoned: false, + }) + } + + fn exchange(&mut self, opcode: u8, payload: &[u8]) -> Result, HalError> { + if self.poisoned { + return Err(HalError::Protocol("connection is unusable")); + } + if payload.len() > MAX_PAYLOAD { + return Err(HalError::FrameTooLong); + } + let result = self.exchange_inner(opcode, payload); + if let Err(ref error) = result { + if !matches!(error, HalError::Device(_)) { + self.poisoned = true; + } + } + result + } + + fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result, HalError> { + 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()); + self.stream.write_all(&header)?; + self.stream.write_all(payload)?; + + self.stream.read_exact(&mut header)?; + 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]; + self.stream.read_exact(&mut body)?; + if body[0] != 0 { + return Err(HalError::Device(body[0])); + } + Ok(body[1..].to_vec()) + } + + fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> { + if !self.exchange(opcode, payload)?.is_empty() { + self.poisoned = true; + return Err(HalError::Protocol("unexpected response data")); + } + Ok(()) + } +} + +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 { + if frame.len() > MAX_PAYLOAD - 3 { + return Err(HalError::FrameTooLong); + } + let mut request = [0_u8; 3]; + request[0] = chain; + request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes()); + let body = self.exchange(RECEIVE_FRAME, &request)?; + if body.len() < 2 { + self.poisoned = true; + return Err(HalError::Protocol("missing receive length")); + } + let count = u16::from_le_bytes([body[0], body[1]]) as usize; + if count > frame.len() || body.len() != count + 2 { + self.poisoned = true; + return Err(HalError::Protocol("invalid received frame size")); + } + frame[..count].copy_from_slice(&body[2..]); + Ok(count) + } + + fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error> { + self.empty_reply(SET_CHAIN_RESET, &[chain, u8::from(asserted)]) + } + + fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error> { + if percent > 100 { + return Err(HalError::InvalidFanPercent); + } + self.empty_reply(SET_FAN_TARGET, &[fan, percent]) + } + + fn read_temperature_mc(&mut self, sensor: u8) -> Result { + let body = self.exchange(READ_TEMPERATURE, &[sensor])?; + let bytes: [u8; 4] = match body.try_into() { + Ok(bytes) => bytes, + Err(_) => { + self.poisoned = true; + return Err(HalError::Protocol("invalid temperature response")); + } + }; + Ok(i32::from_le_bytes(bytes)) + } + + fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> { + self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]) + } +} diff --git a/src/lib.rs b/src/lib.rs index 84a2315..0bf0a79 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,8 @@ //! 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 hal_wire; + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Vendor { Bitmain, diff --git a/tests/hal_wire.rs b/tests/hal_wire.rs new file mode 100644 index 0000000..225dd5a --- /dev/null +++ b/tests/hal_wire.rs @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: MIT +use alkane_os::hal_wire::{HalClient, HalError}; +use alkane_os::HardwareBackend; +use std::io::{Read, Write}; +use std::os::unix::net::UnixStream; +use std::thread; + +fn reply(socket: &mut UnixStream, request: &[u8; 16], body: &[u8]) { + let mut header = *request; + header[6..8].copy_from_slice(&1_u16.to_le_bytes()); + header[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes()); + socket.write_all(&header).unwrap(); + socket.write_all(body).unwrap(); +} + +#[test] +fn sdk_backend_round_trip_and_safety_limits() { + let (client, mut server) = UnixStream::pair().unwrap(); + let worker = thread::spawn(move || { + let expected = [ + (1, vec![2, 3, 0, 0x55, 0xaa, 0x21], vec![0]), + (2, vec![2, 8, 0], vec![0, 3, 0, 0xaa, 0x55, 0x01]), + (3, vec![2, 1], vec![0]), + (4, vec![0, 90], vec![0]), + ( + 5, + vec![1], + [vec![0], 72_500_i32.to_le_bytes().to_vec()].concat(), + ), + (6, vec![1], vec![0]), + ]; + for (index, (opcode, request_body, response_body)) in expected.iter().enumerate() { + let mut header = [0_u8; 16]; + server.read_exact(&mut header).unwrap(); + assert_eq!(&header[..4], b"ALKH"); + assert_eq!(header[4], 1); + assert_eq!(header[5], *opcode); + assert_eq!( + u32::from_le_bytes(header[8..12].try_into().unwrap()), + index as u32 + 1 + ); + let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize; + let mut body = vec![0_u8; length]; + server.read_exact(&mut body).unwrap(); + assert_eq!(&body, request_body); + reply(&mut server, &header, response_body); + } + }); + let mut backend = HalClient::from_stream(client).unwrap(); + backend.send_frame(2, &[0x55, 0xaa, 0x21]).unwrap(); + let mut buffer = [0_u8; 8]; + assert_eq!(backend.receive_frame(2, &mut buffer).unwrap(), 3); + assert_eq!(&buffer[..3], &[0xaa, 0x55, 0x01]); + backend.set_chain_reset(2, true).unwrap(); + backend.set_fan_target(0, 90).unwrap(); + assert_eq!(backend.read_temperature_mc(1).unwrap(), 72_500); + backend.set_psu_enabled(true).unwrap(); + assert!(matches!( + backend.set_fan_target(0, 101), + Err(HalError::InvalidFanPercent) + )); + assert!(matches!( + backend.send_frame(0, &[0_u8; 4094]), + Err(HalError::FrameTooLong) + )); + worker.join().unwrap(); +} + +#[test] +fn rejects_wrong_response_sequence() { + let (client, mut server) = UnixStream::pair().unwrap(); + let worker = thread::spawn(move || { + let mut header = [0_u8; 16]; + server.read_exact(&mut header).unwrap(); + let mut body = [0_u8; 1]; + server.read_exact(&mut body).unwrap(); + header[8..12].copy_from_slice(&2_u32.to_le_bytes()); + reply(&mut server, &header, &[0]); + }); + let mut backend = HalClient::from_stream(client).unwrap(); + assert!(matches!( + backend.set_psu_enabled(true), + Err(HalError::Protocol("response sequence mismatch")) + )); + assert!(matches!( + backend.set_psu_enabled(true), + Err(HalError::Protocol("connection is unusable")) + )); + worker.join().unwrap(); +} From bd52429276e0e97679c67f6e23e1e055434b29d3 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:17:01 -0600 Subject: [PATCH 02/83] Bound HAL socket exchanges and validate errors --- Cargo.lock | 9 +++ Cargo.toml | 4 +- src/hal_wire.rs | 166 +++++++++++++++++++++++++++++++++++++++++++--- tests/hal_wire.rs | 54 +++++++++++++++ 4 files changed, 224 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 51393bb..b5a6236 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,3 +5,12 @@ version = 4 [[package]] name = "alkane-os" version = "0.1.0" +dependencies = [ + "libc", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" diff --git a/Cargo.toml b/Cargo.toml index 5ade4d7..4cd3e26 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,9 @@ description = "Portable mining and tuning core for Alkane control boards" [lib] name = "alkane_os" +[dependencies] +libc = "0.2.169" + [profile.release] lto = true codegen-units = 1 - diff --git a/src/hal_wire.rs b/src/hal_wire.rs index 555cfe4..c71f8eb 100644 --- a/src/hal_wire.rs +++ b/src/hal_wire.rs @@ -4,15 +4,18 @@ use crate::HardwareBackend; use std::fmt; use std::io::{self, Read, Write}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; use std::os::unix::net::UnixStream; use std::path::Path; -use std::time::Duration; +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; @@ -59,13 +62,13 @@ pub struct HalClient { impl HalClient { pub fn connect(path: impl AsRef) -> Result { - let stream = UnixStream::connect(path)?; + let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?; Self::from_stream(stream) } pub fn from_stream(stream: UnixStream) -> Result { - stream.set_read_timeout(Some(Duration::from_secs(2)))?; - stream.set_write_timeout(Some(Duration::from_secs(2)))?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; Ok(Self { stream, sequence: 0, @@ -90,6 +93,7 @@ impl HalClient { } fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result, 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]; @@ -98,10 +102,10 @@ impl HalClient { 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()); - self.stream.write_all(&header)?; - self.stream.write_all(payload)?; + write_all_until(&mut self.stream, &header, deadline)?; + write_all_until(&mut self.stream, payload, deadline)?; - self.stream.read_exact(&mut header)?; + 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")); } @@ -116,8 +120,11 @@ impl HalClient { return Err(HalError::Protocol("invalid response length")); } let mut body = vec![0_u8; length]; - self.stream.read_exact(&mut body)?; + 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()) @@ -132,6 +139,149 @@ impl HalClient { } } +fn timeout_error() -> io::Error { + io::Error::new(io::ErrorKind::TimedOut, "HAL operation timed out") +} + +fn remaining(deadline: Instant) -> io::Result { + 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 { + let bytes = path.as_os_str().as_bytes(); + let max_path = std::mem::size_of::() + - std::mem::offset_of!(libc::sockaddr_un, 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 { + libc::socket( + libc::AF_UNIX, + libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, + 0, + ) + }; + if raw < 0 { + return Err(io::Error::last_os_error()); + } + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + let mut address: libc::sockaddr_un = unsafe { std::mem::zeroed() }; + address.sun_family = libc::AF_UNIX as libc::sa_family_t; + for (destination, source) in address.sun_path.iter_mut().zip(bytes) { + *destination = *source as libc::c_char; + } + let length = + (std::mem::offset_of!(libc::sockaddr_un, sun_path) + bytes.len() + 1) as libc::socklen_t; + loop { + let result = unsafe { + libc::connect( + fd.as_raw_fd(), + &address as *const _ as *const libc::sockaddr, + length, + ) + }; + if result == 0 { + break; + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::EISCONN) { + break; + } + if !matches!( + error.raw_os_error(), + Some(libc::EINPROGRESS) | Some(libc::EAGAIN) + ) { + return Err(error); + } + let mut poll_fd = libc::pollfd { + fd: fd.as_raw_fd(), + events: libc::POLLOUT, + revents: 0, + }; + let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32; + let polled = unsafe { libc::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: libc::c_int = 0; + let mut socket_error_len = std::mem::size_of_val(&socket_error) as libc::socklen_t; + if unsafe { + libc::getsockopt( + fd.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_ERROR, + &mut socket_error as *mut _ as *mut libc::c_void, + &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(libc::EINPROGRESS) { + break; + } + } + let stream = UnixStream::from(fd); + stream.set_nonblocking(false)?; + Ok(stream) +} + impl HardwareBackend for HalClient { type Error = HalError; diff --git a/tests/hal_wire.rs b/tests/hal_wire.rs index 225dd5a..6912da6 100644 --- a/tests/hal_wire.rs +++ b/tests/hal_wire.rs @@ -4,6 +4,7 @@ use alkane_os::HardwareBackend; use std::io::{Read, Write}; use std::os::unix::net::UnixStream; use std::thread; +use std::time::{Duration, Instant}; fn reply(socket: &mut UnixStream, request: &[u8; 16], body: &[u8]) { let mut header = *request; @@ -88,3 +89,56 @@ fn rejects_wrong_response_sequence() { )); worker.join().unwrap(); } + +#[test] +fn rejects_malformed_error_response_and_poisoned_connection() { + for body in [&[4_u8][..], &[3_u8, 99][..]] { + let (client, mut server) = UnixStream::pair().unwrap(); + let response = body.to_vec(); + let worker = thread::spawn(move || { + let mut header = [0_u8; 16]; + server.read_exact(&mut header).unwrap(); + let mut request = [0_u8; 1]; + server.read_exact(&mut request).unwrap(); + reply(&mut server, &header, &response); + }); + let mut backend = HalClient::from_stream(client).unwrap(); + assert!(matches!( + backend.set_psu_enabled(true), + Err(HalError::Protocol("invalid error response")) + )); + assert!(matches!( + backend.set_psu_enabled(true), + Err(HalError::Protocol("connection is unusable")) + )); + worker.join().unwrap(); + } +} + +#[test] +fn slow_partial_response_hits_absolute_exchange_deadline() { + let (client, mut server) = UnixStream::pair().unwrap(); + let worker = thread::spawn(move || { + let mut header = [0_u8; 16]; + server.read_exact(&mut header).unwrap(); + let mut request = [0_u8; 1]; + server.read_exact(&mut request).unwrap(); + header[6..8].copy_from_slice(&1_u16.to_le_bytes()); + header[12..16].copy_from_slice(&1_u32.to_le_bytes()); + for byte in header.into_iter().chain([0]) { + if server.write_all(&[byte]).is_err() { + break; + } + thread::sleep(Duration::from_millis(250)); + } + }); + let mut backend = HalClient::from_stream(client).unwrap(); + let start = Instant::now(); + assert!(matches!( + backend.set_psu_enabled(true), + Err(HalError::Io(_)) + )); + assert!(start.elapsed() < Duration::from_secs(4)); + drop(backend); + worker.join().unwrap(); +} From 3efc252059ccfe869a7033c47c854b9be7417e09 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:19:26 -0600 Subject: [PATCH 03/83] Keep bounded HAL connections dependency free --- Cargo.lock | 9 ----- Cargo.toml | 3 -- src/hal_wire.rs | 93 +++++++++++++++++++++++++++++++++++------------ tests/hal_wire.rs | 27 +++++++++++++- 4 files changed, 96 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b5a6236..51393bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,12 +5,3 @@ version = 4 [[package]] name = "alkane-os" version = "0.1.0" -dependencies = [ - "libc", -] - -[[package]] -name = "libc" -version = "0.2.190" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" diff --git a/Cargo.toml b/Cargo.toml index 4cd3e26..aa73056 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,9 +8,6 @@ description = "Portable mining and tuning core for Alkane control boards" [lib] name = "alkane_os" -[dependencies] -libc = "0.2.169" - [profile.release] lto = true codegen-units = 1 diff --git a/src/hal_wire.rs b/src/hal_wire.rs index c71f8eb..2f4baad 100644 --- a/src/hal_wire.rs +++ b/src/hal_wire.rs @@ -24,6 +24,53 @@ const SET_FAN_TARGET: u8 = 4; const READ_TEMPERATURE: u8 = 5; const SET_PSU_ENABLED: u8 = 6; +#[cfg(not(target_os = "linux"))] +compile_error!("Alkane HAL sockets require Linux"); + +#[cfg(target_os = "linux")] +mod sys { + pub use std::ffi::{c_char as CChar, c_int as CInt, c_void as CVoid}; + pub type SaFamily = u16; + pub type SocklenT = u32; + + pub const AF_UNIX: CInt = 1; + pub const SOCK_STREAM: CInt = 1; + pub const SOCK_NONBLOCK: CInt = 0x800; + pub const SOCK_CLOEXEC: CInt = 0x80000; + pub const SOL_SOCKET: CInt = 1; + pub const SO_ERROR: CInt = 4; + pub const POLLOUT: i16 = 4; + pub const EAGAIN: CInt = 11; + pub const EISCONN: CInt = 106; + pub const EINPROGRESS: CInt = 115; + + #[repr(C)] + pub struct SockaddrUn { + pub sun_family: SaFamily, + pub sun_path: [CChar; 108], + } + + #[repr(C)] + pub struct PollFd { + pub fd: CInt, + pub events: i16, + pub revents: i16, + } + + extern "C" { + pub fn socket(domain: CInt, socket_type: CInt, protocol: CInt) -> CInt; + pub fn connect(fd: CInt, address: *const CVoid, length: SocklenT) -> CInt; + pub fn poll(fds: *mut PollFd, count: usize, timeout_ms: CInt) -> CInt; + pub fn getsockopt( + fd: CInt, + level: CInt, + name: CInt, + value: *mut CVoid, + length: *mut SocklenT, + ) -> CInt; + } +} + #[derive(Debug)] pub enum HalError { Io(io::Error), @@ -192,8 +239,8 @@ fn read_exact_until( fn connect_until(path: &Path, deadline: Instant) -> io::Result { let bytes = path.as_os_str().as_bytes(); - let max_path = std::mem::size_of::() - - std::mem::offset_of!(libc::sockaddr_un, sun_path); + let max_path = + std::mem::size_of::() - 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, @@ -201,9 +248,9 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result { )); } let raw = unsafe { - libc::socket( - libc::AF_UNIX, - libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, + sys::socket( + sys::AF_UNIX, + sys::SOCK_STREAM | sys::SOCK_NONBLOCK | sys::SOCK_CLOEXEC, 0, ) }; @@ -211,18 +258,18 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result { return Err(io::Error::last_os_error()); } let fd = unsafe { OwnedFd::from_raw_fd(raw) }; - let mut address: libc::sockaddr_un = unsafe { std::mem::zeroed() }; - address.sun_family = libc::AF_UNIX as libc::sa_family_t; + 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 libc::c_char; + *destination = *source as sys::CChar; } let length = - (std::mem::offset_of!(libc::sockaddr_un, sun_path) + bytes.len() + 1) as libc::socklen_t; + (std::mem::offset_of!(sys::SockaddrUn, sun_path) + bytes.len() + 1) as sys::SocklenT; loop { let result = unsafe { - libc::connect( + sys::connect( fd.as_raw_fd(), - &address as *const _ as *const libc::sockaddr, + &address as *const _ as *const sys::CVoid, length, ) }; @@ -230,22 +277,22 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result { break; } let error = io::Error::last_os_error(); - if error.raw_os_error() == Some(libc::EISCONN) { + if error.raw_os_error() == Some(sys::EISCONN) { break; } if !matches!( error.raw_os_error(), - Some(libc::EINPROGRESS) | Some(libc::EAGAIN) + Some(sys::EINPROGRESS) | Some(sys::EAGAIN) ) { return Err(error); } - let mut poll_fd = libc::pollfd { + let mut poll_fd = sys::PollFd { fd: fd.as_raw_fd(), - events: libc::POLLOUT, + events: sys::POLLOUT, revents: 0, }; let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32; - let polled = unsafe { libc::poll(&mut poll_fd, 1, wait.max(1)) }; + 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 { @@ -256,14 +303,14 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result { if polled == 0 { return Err(timeout_error()); } - let mut socket_error: libc::c_int = 0; - let mut socket_error_len = std::mem::size_of_val(&socket_error) as libc::socklen_t; + let mut socket_error: sys::CInt = 0; + let mut socket_error_len = std::mem::size_of_val(&socket_error) as sys::SocklenT; if unsafe { - libc::getsockopt( + sys::getsockopt( fd.as_raw_fd(), - libc::SOL_SOCKET, - libc::SO_ERROR, - &mut socket_error as *mut _ as *mut libc::c_void, + sys::SOL_SOCKET, + sys::SO_ERROR, + &mut socket_error as *mut _ as *mut sys::CVoid, &mut socket_error_len, ) } < 0 @@ -273,7 +320,7 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result { if socket_error != 0 { return Err(io::Error::from_raw_os_error(socket_error)); } - if error.raw_os_error() == Some(libc::EINPROGRESS) { + if error.raw_os_error() == Some(sys::EINPROGRESS) { break; } } diff --git a/tests/hal_wire.rs b/tests/hal_wire.rs index 6912da6..f799fdd 100644 --- a/tests/hal_wire.rs +++ b/tests/hal_wire.rs @@ -2,7 +2,7 @@ use alkane_os::hal_wire::{HalClient, HalError}; use alkane_os::HardwareBackend; use std::io::{Read, Write}; -use std::os::unix::net::UnixStream; +use std::os::unix::net::{UnixListener, UnixStream}; use std::thread; use std::time::{Duration, Instant}; @@ -142,3 +142,28 @@ fn slow_partial_response_hits_absolute_exchange_deadline() { drop(backend); worker.join().unwrap(); } + +#[test] +fn connects_to_a_local_backend_socket() { + let path = std::env::temp_dir().join(format!( + "alkane-hal-{}-{}.sock", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let listener = UnixListener::bind(&path).unwrap(); + let worker = thread::spawn(move || { + let (mut server, _) = listener.accept().unwrap(); + let mut header = [0_u8; 16]; + server.read_exact(&mut header).unwrap(); + let mut request = [0_u8; 1]; + server.read_exact(&mut request).unwrap(); + reply(&mut server, &header, &[0]); + }); + let mut backend = HalClient::connect(&path).unwrap(); + backend.set_psu_enabled(true).unwrap(); + worker.join().unwrap(); + std::fs::remove_file(path).unwrap(); +} From 212cb30b9701a99c166a1b879ae99066f5788a2c Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:37:16 -0600 Subject: [PATCH 04/83] Verify captured ASIC shares and probe SDK simulator --- README.md | 9 ++ examples/simulator_replay_probe.rs | 79 ++++++++++ src/lib.rs | 1 + src/pow.rs | 234 +++++++++++++++++++++++++++++ tests/bench.rs | 16 ++ 5 files changed, 339 insertions(+) create mode 100644 examples/simulator_replay_probe.rs create mode 100644 src/pow.rs diff --git a/README.md b/README.md index 05a57c7..3962666 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,15 @@ now includes a versioned local Unix-socket client for the SDK hardware backend, with bounded frames, two-second I/O timeouts, and fail-closed response validation. The matching SDK server framing library exists, but no board adapter is installed in an image yet. +The library can also verify an ASIC-reported SHA-256d share against an exact +pool target, including BM13xx version rolling. A test checks a BM1366 nonce +captured from real silicon at difficulty 1588. This verifies reports only; +work distribution, pool communication, and mining control are still pending. +The `simulator_replay_probe` example sends that captured job through the Rust +HAL client to the SDK's host-only C/Python replay server, then verifies the +returned nonce. From this repository, run it with +`cargo run --example simulator_replay_probe -- SOCKET_PATH` after starting +the SDK server. It is a simulator check and sends work to the named socket. The `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 diff --git a/examples/simulator_replay_probe.rs b/examples/simulator_replay_probe.rs new file mode 100644 index 0000000..2cbc6b7 --- /dev/null +++ b/examples/simulator_replay_probe.rs @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MIT +//! Exercise the SDK's host-only BM1366 HAL simulator with a captured job. + +use alkane_os::hal_wire::HalClient; +use alkane_os::pow::verify_sha256_report; +use alkane_os::HardwareBackend; +use std::error::Error; + +const HEADER: [u8; 80] = [ + 0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38, 0x9d, + 0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, 0x57, 0xb6, 0xc2, 0x25, + 0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78, + 0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38, + 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, +]; + +fn 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 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 +} + +fn captured_job() -> [u8; 88] { + let mut frame = [0_u8; 88]; + frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]); + frame[4] = 0x18; + 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 crc = crc16(&frame[2..86]); + frame[86..88].copy_from_slice(&crc.to_be_bytes()); + frame +} + +fn main() -> Result<(), Box> { + let path = std::env::args() + .nth(1) + .ok_or("usage: simulator_replay_probe SOCKET_PATH")?; + let mut backend = HalClient::connect(path)?; + backend.set_psu_enabled(true)?; + backend.set_chain_reset(0, true)?; + backend.set_chain_reset(0, false)?; + backend.send_frame(0, &captured_job())?; + let mut buffer = [0_u8; 11]; + let length = backend.receive_frame(0, &mut buffer)?; + if length != 11 || buffer[..2] != [0xaa, 0x55] || buffer[10] & 0x80 == 0 { + return Err("missing BM1366 nonce report".into()); + } + let nonce = u32::from_le_bytes(buffer[2..6].try_into()?); + let version_field = u16::from_be_bytes(buffer[8..10].try_into()?); + let mut target = [0_u8; 32]; + target[26..28].fill(0xff); + let result = verify_sha256_report(&HEADER, nonce, version_field, &target); + backend.set_psu_enabled(false)?; + if !result.meets_target { + return Err("captured nonce does not meet difficulty 1".into()); + } + println!("BM1366 captured report verified at difficulty 1"); + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index 0bf0a79..41902a0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ //! the pairing already mines. Hardware backends are supplied by SDK images. pub mod hal_wire; +pub mod pow; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Vendor { diff --git a/src/pow.rs b/src/pow.rs new file mode 100644 index 0000000..b4efd33 --- /dev/null +++ b/src/pow.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT +//! Verify reported SHA-256d shares. This module does not search for nonces. + +const BM1366_VERSION_BITS: u32 = 0x1FFF_E000; + +const ROUND: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +const INITIAL: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]; + +fn compress(state: &mut [u32; 8], block: &[u8]) { + let mut words = [0_u32; 64]; + for (index, part) in block.chunks_exact(4).enumerate() { + words[index] = u32::from_be_bytes(part.try_into().expect("four-byte word")); + } + for index in 16..64 { + let a = words[index - 15]; + let b = words[index - 2]; + let small_zero = a.rotate_right(7) ^ a.rotate_right(18) ^ (a >> 3); + let small_one = b.rotate_right(17) ^ b.rotate_right(19) ^ (b >> 10); + words[index] = words[index - 16] + .wrapping_add(small_zero) + .wrapping_add(words[index - 7]) + .wrapping_add(small_one); + } + + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; + for index in 0..64 { + let choose = (e & f) ^ (!e & g); + let majority = (a & b) ^ (a & c) ^ (b & c); + let big_one = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let big_zero = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let first = h + .wrapping_add(big_one) + .wrapping_add(choose) + .wrapping_add(ROUND[index]) + .wrapping_add(words[index]); + let second = big_zero.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(first); + d = c; + c = b; + b = a; + a = first.wrapping_add(second); + } + for (current, result) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *current = current.wrapping_add(result); + } +} + +/// Compute SHA-256 for a message whose length fits the standard 64-bit field. +pub fn sha256(message: &[u8]) -> [u8; 32] { + let mut state = INITIAL; + let chunks = message.chunks_exact(64); + let remainder = chunks.remainder(); + for chunk in chunks { + compress(&mut state, chunk); + } + let final_size = if remainder.len() >= 56 { 128 } else { 64 }; + let mut final_blocks = [0_u8; 128]; + final_blocks[..remainder.len()].copy_from_slice(remainder); + final_blocks[remainder.len()] = 0x80; + final_blocks[final_size - 8..final_size] + .copy_from_slice(&((message.len() as u64).wrapping_mul(8)).to_be_bytes()); + for chunk in final_blocks[..final_size].chunks_exact(64) { + compress(&mut state, chunk); + } + let mut digest = [0_u8; 32]; + for (word, bytes) in state.into_iter().zip(digest.chunks_exact_mut(4)) { + bytes.copy_from_slice(&word.to_be_bytes()); + } + digest +} + +/// Compute one double hash for verification, never for nonce search. +pub fn sha256d(message: &[u8]) -> [u8; 32] { + sha256(&sha256(message)) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ShareCheck { + pub rolled_version: u32, + pub hash_le: [u8; 32], + pub meets_target: bool, +} + +/// Decode the raw BM1366 version extension against the version sent to the ASIC. +/// The chip reports additional set bits; pool submission uses a separate mask. +pub fn decode_bm1366_version(job_version: u32, version_field: u16) -> u32 { + job_version | ((u32::from(version_field) << 13) & BM1366_VERSION_BITS) +} + +/// The BIP310 mask negotiated with a pool, limited to BM1366 rolling bits. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct VersionMask(u32); + +impl VersionMask { + pub fn new(mask: u32) -> Option { + (mask & !BM1366_VERSION_BITS == 0).then_some(Self(mask)) + } + + pub fn apply_submission_bits(self, base_version: u32, version_bits: u32) -> Option { + (version_bits & !self.0 == 0).then_some((base_version & !self.0) | version_bits) + } +} + +/// Check one ASIC-reported nonce against a little-endian 256-bit pool target. +pub fn verify_sha256_report( + nonce_zero_header: &[u8; 80], + nonce: u32, + version_field: u16, + target_le: &[u8; 32], +) -> ShareCheck { + let mut header = *nonce_zero_header; + let base_version = u32::from_le_bytes(header[..4].try_into().expect("version field")); + let rolled_version = decode_bm1366_version(base_version, version_field); + header[..4].copy_from_slice(&rolled_version.to_le_bytes()); + header[76..80].copy_from_slice(&nonce.to_le_bytes()); + let hash_le = sha256d(&header); + let meets_target = hash_le.iter().rev().cmp(target_le.iter().rev()).is_le(); + ShareCheck { + rolled_version, + hash_le, + meets_target, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + + #[test] + fn sha256_matches_standard_padding_vectors() { + let vectors: [(&[u8], &str); 6] = [ + ( + b"", + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ), + ( + b"abc", + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ), + ( + &(0_u8..55).collect::>(), + "463eb28e72f82e0a96c0a4cc53690c571281131f672aa229e0d45ae59b598b59", + ), + ( + &(0_u8..56).collect::>(), + "da2ae4d6b36748f2a318f23e7ab1dfdf45acdc9d049bd80e59de82a60895f562", + ), + ( + &(0_u8..64).collect::>(), + "fdeab9acf3710362bd2658cdc9a29e8f9c757fcf9811603a8c447cd1d9151108", + ), + ( + &(0_u8..100).collect::>(), + "bce0aff19cf5aa6a7469a30d61d04e4376e4bbf6381052ee9e7f33925c954d52", + ), + ]; + for (message, expected) in vectors { + assert_eq!(hex(&sha256(message)), expected); + } + } + + #[test] + fn captured_bm1366_report_meets_diff_one_only_with_rolled_version() { + let header = [ + 0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, + 0x38, 0x9d, 0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, + 0x57, 0xb6, 0xc2, 0x25, 0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, + 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78, 0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, + 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38, 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, + 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, + ]; + let mut diff_one = [0_u8; 32]; + diff_one[26..28].fill(0xff); + let result = verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &diff_one); + assert_eq!(result.rolled_version, 0x2096_6000); + assert_eq!( + hex(&result.hash_le), + "4b5e00850cf9de9809f822f8858eda39e49996d9d40f634f1043290000000000" + ); + assert!(result.meets_target); + assert!(!verify_sha256_report(&header, 0xEDAD_FF38, 0, &diff_one).meets_target); + assert!(!verify_sha256_report(&header, 0xEDAD_FF39, 0x04B3, &diff_one).meets_target); + assert!(verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &[0xff; 32]).meets_target); + assert!(!verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &[0; 32]).meets_target); + } + + #[test] + fn raw_asic_version_preserves_bits_sent_to_chip() { + assert_eq!(decode_bm1366_version(0x2100_0004, 1), 0x2100_2004); + assert_eq!(decode_bm1366_version(0x2000_0000, 0), 0x2000_0000); + } + + #[test] + fn pool_version_bits_replace_only_negotiated_mask() { + let mask = VersionMask::new(0x0060_0000).expect("valid restricted mask"); + assert_eq!( + mask.apply_submission_bits(0x2160_0004, 0x0020_0000), + Some(0x2120_0004) + ); + assert_eq!(mask.apply_submission_bits(0x2160_0004, 0x0080_0000), None); + assert_eq!( + VersionMask::new(0) + .unwrap() + .apply_submission_bits(0x2100_0004, 0), + Some(0x2100_0004) + ); + assert_eq!( + VersionMask::new(BM1366_VERSION_BITS) + .unwrap() + .apply_submission_bits(0x2160_0004, 0), + Some(0x2000_0004) + ); + assert!(VersionMask::new(0x8000_0000).is_none()); + } +} diff --git a/tests/bench.rs b/tests/bench.rs index 2b8551b..f898eca 100644 --- a/tests/bench.rs +++ b/tests/bench.rs @@ -1,3 +1,4 @@ +use alkane_os::pow::verify_sha256_report; use alkane_os::{power_decision, target_matrix}; use std::hint::black_box; use std::time::Instant; @@ -30,3 +31,18 @@ fn bench_power_policy() { black_box(power_decision(black_box(Some(64_000)), 80_000)); }); } + +#[test] +#[ignore = "microbenchmark"] +fn bench_share_verification() { + let header = [0_u8; 80]; + let target = [0xff_u8; 32]; + measure("share_verification", 20_000, || { + black_box(verify_sha256_report( + black_box(&header), + black_box(0xEDAD_FF38), + black_box(0x04B3), + black_box(&target), + )); + }); +} From 751d8c0bda6e1bd06fe2f75cd11c21513af319d9 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:42:54 -0600 Subject: [PATCH 05/83] Add reusable BM1366 work and report codec --- examples/simulator_replay_probe.rs | 52 ++-------- src/bm1366.rs | 149 +++++++++++++++++++++++++++++ src/lib.rs | 1 + tests/bench.rs | 21 ++++ 4 files changed, 180 insertions(+), 43 deletions(-) create mode 100644 src/bm1366.rs diff --git a/examples/simulator_replay_probe.rs b/examples/simulator_replay_probe.rs index 2cbc6b7..d9360e4 100644 --- a/examples/simulator_replay_probe.rs +++ b/examples/simulator_replay_probe.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT //! Exercise the SDK's host-only BM1366 HAL simulator with a captured job. +use alkane_os::bm1366::{decode_nonce_report, encode_work, REPORT_BYTES}; use alkane_os::hal_wire::HalClient; use alkane_os::pow::verify_sha256_report; use alkane_os::HardwareBackend; @@ -14,43 +15,6 @@ const HEADER: [u8; 80] = [ 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, ]; -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 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 -} - -fn captured_job() -> [u8; 88] { - let mut frame = [0_u8; 88]; - frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]); - frame[4] = 0x18; - 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 crc = crc16(&frame[2..86]); - frame[86..88].copy_from_slice(&crc.to_be_bytes()); - frame -} - fn main() -> Result<(), Box> { let path = std::env::args() .nth(1) @@ -59,17 +23,19 @@ fn main() -> Result<(), Box> { backend.set_psu_enabled(true)?; backend.set_chain_reset(0, true)?; backend.set_chain_reset(0, false)?; - backend.send_frame(0, &captured_job())?; - let mut buffer = [0_u8; 11]; + backend.send_frame(0, &encode_work(&HEADER, 0x18).ok_or("invalid work header")?)?; + let mut buffer = [0_u8; REPORT_BYTES]; let length = backend.receive_frame(0, &mut buffer)?; - if length != 11 || buffer[..2] != [0xaa, 0x55] || buffer[10] & 0x80 == 0 { + if length != REPORT_BYTES { return Err("missing BM1366 nonce report".into()); } - let nonce = u32::from_le_bytes(buffer[2..6].try_into()?); - let version_field = u16::from_be_bytes(buffer[8..10].try_into()?); + let report = decode_nonce_report(&buffer).map_err(|_| "invalid BM1366 nonce report")?; + if report.work_id != 0x18 { + return Err("stale BM1366 work ID".into()); + } let mut target = [0_u8; 32]; target[26..28].fill(0xff); - let result = verify_sha256_report(&HEADER, nonce, version_field, &target); + let result = verify_sha256_report(&HEADER, report.nonce, report.version_field, &target); backend.set_psu_enabled(false)?; if !result.meets_target { return Err("captured nonce does not meet difficulty 1".into()); diff --git a/src/bm1366.rs b/src/bm1366.rs new file mode 100644 index 0000000..432edc1 --- /dev/null +++ b/src/bm1366.rs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: MIT +//! BM1366 work and response framing. Nonces only come from a device or replay. + +pub const WORK_BYTES: usize = 88; +pub const REPORT_BYTES: usize = 11; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct NonceReport { + pub nonce: u32, + pub work_id: u8, + pub version_field: u16, + pub chip_address: u8, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ReportError { + Length, + Preamble, + RegisterResponse, + Checksum, +} + +pub fn crc16(bytes: &[u8]) -> u16 { + let mut value = 0xffff_u16; + for byte in bytes { + value ^= u16::from(*byte) << 8; + for _ in 0..8 { + value = if value & 0x8000 != 0 { + (value << 1) ^ 0x1021 + } else { + value << 1 + }; + } + } + value +} + +fn crc5(bytes: &[u8]) -> u8 { + let mut value = 0x1f_u8; + for byte in bytes { + for shift in (0..8).rev() { + let feedback = ((value >> 4) ^ (byte >> shift)) & 1; + value = ((value << 1) | feedback) & 0x1f; + value ^= feedback << 2; + } + } + value +} + +fn reverse_words(input: &[u8]) -> [u8; 32] { + let mut output = [0_u8; 32]; + for index in 0..8 { + output[index * 4..index * 4 + 4].copy_from_slice(&input[(7 - index) * 4..(8 - index) * 4]); + } + output +} + +/// Encode a nonce-zero Bitcoin header for the observed 88-byte SEND_JOB form. +/// The low three work-ID bits are reserved by the BM1366 response format. +pub fn encode_work(header: &[u8; 80], work_id: u8) -> Option<[u8; WORK_BYTES]> { + if header[76..80] != [0; 4] || work_id & 7 != 0 { + return None; + } + let mut frame = [0_u8; WORK_BYTES]; + frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]); + frame[4] = work_id; + frame[10..14].copy_from_slice(&header[72..76]); + frame[14..18].copy_from_slice(&header[68..72]); + frame[18..50].copy_from_slice(&reverse_words(&header[36..68])); + frame[50..82].copy_from_slice(&reverse_words(&header[4..36])); + frame[82..86].copy_from_slice(&header[..4]); + let checksum = crc16(&frame[2..86]); + frame[86..88].copy_from_slice(&checksum.to_be_bytes()); + Some(frame) +} + +/// Parse an observed nonce report; register replies must use a separate path. +pub fn decode_nonce_report(frame: &[u8]) -> Result { + if frame.len() != REPORT_BYTES { + return Err(ReportError::Length); + } + if frame[..2] != [0xaa, 0x55] { + return Err(ReportError::Preamble); + } + if frame[10] & 0x80 == 0 { + return Err(ReportError::RegisterResponse); + } + if crc5(&frame[2..]) != 0 { + return Err(ReportError::Checksum); + } + Ok(NonceReport { + nonce: u32::from_le_bytes(frame[2..6].try_into().expect("four-byte nonce")), + chip_address: frame[6], + work_id: frame[7] & 0xf8, + version_field: u16::from_be_bytes(frame[8..10].try_into().expect("version field")), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc16_reference_vector() { + assert_eq!(crc16(b"123456789"), 0x29b1); + } + + #[test] + fn captured_work_and_response() { + let header: [u8; 80] = hex_header(); + let frame = encode_work(&header, 0x18).unwrap(); + assert_eq!(&frame[..5], &[0x55, 0xaa, 0x21, 0x54, 0x18]); + assert_eq!( + crc16(&frame[2..86]), + u16::from_be_bytes([frame[86], frame[87]]) + ); + assert_eq!(&frame[10..14], &header[72..76]); + assert_eq!(&frame[82..86], &header[..4]); + assert!(encode_work(&header, 0x19).is_none()); + let mut with_nonce = header; + with_nonce[76] = 1; + assert!(encode_work(&with_nonce, 0x18).is_none()); + + let report = [ + 0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94, + ]; + let parsed = decode_nonce_report(&report).unwrap(); + assert_eq!(parsed.nonce, 0xedad_ff38); + assert_eq!(parsed.work_id, 0x18); + assert_eq!(parsed.version_field, 0x04b3); + let mut corrupt = report; + corrupt[4] ^= 1; + assert_eq!(decode_nonce_report(&corrupt), Err(ReportError::Checksum)); + } + + fn hex_header() -> [u8; 80] { + let input = concat!( + "00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503", + "b4213a43ae1052ebd44443068fe178e2c61ca4994846fd133addb04aab2b382c5", + "b4c74c1012e6a8f06021700000000" + ); + let mut header = [0_u8; 80]; + for (index, bytes) in input.as_bytes().chunks_exact(2).enumerate() { + let pair = std::str::from_utf8(bytes).unwrap(); + header[index] = u8::from_str_radix(pair, 16).unwrap(); + } + header + } +} diff --git a/src/lib.rs b/src/lib.rs index 41902a0..2029a16 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ //! An entry in the target matrix is a development obligation, not a claim that //! the pairing already mines. Hardware backends are supplied by SDK images. +pub mod bm1366; pub mod hal_wire; pub mod pow; diff --git a/tests/bench.rs b/tests/bench.rs index f898eca..c15c75c 100644 --- a/tests/bench.rs +++ b/tests/bench.rs @@ -1,3 +1,4 @@ +use alkane_os::bm1366::{decode_nonce_report, encode_work}; use alkane_os::pow::verify_sha256_report; use alkane_os::{power_decision, target_matrix}; use std::hint::black_box; @@ -46,3 +47,23 @@ fn bench_share_verification() { )); }); } + +#[test] +#[ignore = "microbenchmark"] +fn bench_bm1366_work_encoding() { + let header = [0_u8; 80]; + measure("bm1366_work_encoding", 20_000, || { + black_box(encode_work(black_box(&header), black_box(0x18))); + }); +} + +#[test] +#[ignore = "microbenchmark"] +fn bench_bm1366_report_decode() { + let report = [ + 0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94, + ]; + measure("bm1366_report_decode", 100_000, || { + let _ = black_box(decode_nonce_report(black_box(&report))); + }); +} From c5f669b3c0e17e5001d2aaffd5d5a3c7e6012416 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:46:44 -0600 Subject: [PATCH 06/83] Publish branch badges from completed CI runs --- .gitea/workflows/ci-badge.yml | 19 ++++++ .gitea/workflows/main.yml | 2 + README.md | 4 +- ci/last-attempt-badge.py | 115 ++++++++++++++++++++++++++++++++++ ci/test-last-attempt-badge.py | 34 ++++++++++ 5 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 .gitea/workflows/ci-badge.yml create mode 100644 ci/last-attempt-badge.py create mode 100644 ci/test-last-attempt-badge.py diff --git a/.gitea/workflows/ci-badge.yml b/.gitea/workflows/ci-badge.yml new file mode 100644 index 0000000..1a344a7 --- /dev/null +++ b/.gitea/workflows/ci-badge.yml @@ -0,0 +1,19 @@ +name: completed-ci-badge + +on: + workflow_run: + workflows: [main-release-gate, next-build] + types: [completed] + +jobs: + publish: + runs-on: alkane-ci + permissions: + actions: read + contents: write + steps: + - uses: actions/checkout@v4 + - name: Publish last completed attempt + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/last-attempt-badge.py diff --git a/.gitea/workflows/main.yml b/.gitea/workflows/main.yml index 3e9268b..04f6e14 100644 --- a/.gitea/workflows/main.yml +++ b/.gitea/workflows/main.yml @@ -15,6 +15,8 @@ jobs: run: rustup component add rustfmt clippy - name: Formatting run: cargo fmt --check + - name: Last-attempt badge checks + run: python3 ci/test-last-attempt-badge.py - name: Quality run: cargo clippy --all-targets --locked -- -D warnings - name: Build diff --git a/README.md b/README.md index 3962666..9e9facf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Alkane OS -[![CI](https://gitea.bluefla.re/blueflare/alkane-os/actions/workflows/main.yml/badge.svg?branch=main)](https://gitea.bluefla.re/blueflare/alkane-os/actions) +[![CI](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-os/actions) ![tests](badges/tests.svg) ![coverage](badges/coverage.svg) ![bench](badges/bench.svg) @@ -62,3 +62,5 @@ still pending. It is a release gate, not a unit test. The badges record measured host-side checks for this initial core. They do not imply that any board image or mining target has passed conformance. +The CI badge is served from a private, machine-maintained branch and shows +the last completed attempt for this source branch while newer runs are queued. diff --git a/ci/last-attempt-badge.py b/ci/last-attempt-badge.py new file mode 100644 index 0000000..c77bdb1 --- /dev/null +++ b/ci/last-attempt-badge.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Publish the last completed main/next CI result to a private badge branch.""" + +import base64 +import json +import os +from pathlib import Path +from urllib.error import HTTPError +from urllib.parse import quote, urlencode +from urllib.request import Request, urlopen + + +WORKFLOWS = {"main.yml": "main", "next.yml": "next"} +BADGE_BRANCH = "ci-badges" + + +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'{title}' + '' + f'' + 'CI' + f'{word}\n').encode() + + +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 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", "cancelled", "skipped"): + 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: + path = f"{api}/repos/{repo}/contents/{branch}.svg" + encoded = base64.b64encode(data).decode("ascii") + for attempt in range(3): + try: + current = request_json(path + "?ref=" + BADGE_BRANCH, token) + current_data = base64.b64decode(current["content"]) + if current_data == 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": f"Record completed {branch} CI attempt"} + 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") + + +def main() -> None: + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text()) + if event.get("action") != "completed": + raise RuntimeError("expected a completed workflow_run event") + run = event["workflow_run"] + workflow = run["path"].split("@", 1)[0].rsplit("/", 1)[-1] + expected_branch = WORKFLOWS.get(workflow) + if expected_branch is None or run.get("head_branch") != expected_branch: + raise RuntimeError("unexpected workflow or branch") + repo = os.environ["GITHUB_REPOSITORY"] + if event["repository"]["full_name"] != repo: + raise RuntimeError("repository mismatch") + api = os.environ["GITHUB_API_URL"].rstrip("/") + token = os.environ["GITEA_TOKEN"] + run_id, conclusion = latest_completed(api, repo, workflow, expected_branch, token) + publish(api, repo, expected_branch, badge(expected_branch, conclusion, run_id), token) + print(f"{expected_branch} badge records completed run {run_id}: {conclusion}") + + +if __name__ == "__main__": + main() diff --git a/ci/test-last-attempt-badge.py b/ci/test-last-attempt-badge.py new file mode 100644 index 0000000..2c19243 --- /dev/null +++ b/ci/test-last-attempt-badge.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Check that queued CI runs do not displace the last completed result.""" + +import importlib.util +from pathlib import Path +from unittest.mock import patch +import xml.etree.ElementTree as ET + +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": 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" in svg +assert b"#d1242f" in svg +assert b">pass" in module.badge("next", "success", 108) +print("last completed CI badge: queued run ignored, pass/fail SVGs valid") From 7e687e0d5dc2aec99006b6d41eea24886b5a41b1 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:53:25 -0600 Subject: [PATCH 07/83] Add fail-safe BM1366 mining session --- README.md | 7 +- examples/simulator_replay_probe.rs | 29 +--- src/lib.rs | 1 + src/miner.rs | 231 +++++++++++++++++++++++++++++ tests/bench.rs | 46 +++++- tests/miner.rs | 198 +++++++++++++++++++++++++ 6 files changed, 489 insertions(+), 23 deletions(-) create mode 100644 src/miner.rs create mode 100644 tests/miner.rs diff --git a/README.md b/README.md index 9e9facf..8aed434 100644 --- a/README.md +++ b/README.md @@ -35,12 +35,17 @@ board adapter is installed in an image yet. The library can also verify an ASIC-reported SHA-256d share against an exact pool target, including BM13xx version rolling. A test checks a BM1366 nonce captured from real silicon at difficulty 1588. This verifies reports only; -work distribution, pool communication, and mining control are still pending. +pool communication and continuous job scheduling are still pending. The `simulator_replay_probe` example sends that captured job through the Rust HAL client to the SDK's host-only C/Python replay server, then verifies the returned nonce. From this repository, run it with `cargo run --example simulator_replay_probe -- SOCKET_PATH` after starting the SDK server. It is a simulator check and sends work to the named socket. +The first BM1366 mining session sequences fan, temperature, PSU, reset, +work submission, and nonce polling through the HAL. It rejects stale work IDs, +malformed reports, and hashes below the caller's pool target. Sensor or HAL +failure stops the PSU. The caller must provide a board-validated temperature +limit. The `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 diff --git a/examples/simulator_replay_probe.rs b/examples/simulator_replay_probe.rs index d9360e4..13fe867 100644 --- a/examples/simulator_replay_probe.rs +++ b/examples/simulator_replay_probe.rs @@ -1,10 +1,8 @@ // SPDX-License-Identifier: MIT //! Exercise the SDK's host-only BM1366 HAL simulator with a captured job. -use alkane_os::bm1366::{decode_nonce_report, encode_work, REPORT_BYTES}; use alkane_os::hal_wire::HalClient; -use alkane_os::pow::verify_sha256_report; -use alkane_os::HardwareBackend; +use alkane_os::miner::Bm1366Miner; use std::error::Error; const HEADER: [u8; 80] = [ @@ -20,26 +18,15 @@ fn main() -> Result<(), Box> { .nth(1) .ok_or("usage: simulator_replay_probe SOCKET_PATH")?; let mut backend = HalClient::connect(path)?; - backend.set_psu_enabled(true)?; - backend.set_chain_reset(0, true)?; - backend.set_chain_reset(0, false)?; - backend.send_frame(0, &encode_work(&HEADER, 0x18).ok_or("invalid work header")?)?; - let mut buffer = [0_u8; REPORT_BYTES]; - let length = backend.receive_frame(0, &mut buffer)?; - if length != REPORT_BYTES { - return Err("missing BM1366 nonce report".into()); - } - let report = decode_nonce_report(&buffer).map_err(|_| "invalid BM1366 nonce report")?; - if report.work_id != 0x18 { - return Err("stale BM1366 work ID".into()); - } + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000) + .ok_or("invalid simulator probe configuration")?; + miner.start()?; let mut target = [0_u8; 32]; target[26..28].fill(0xff); - let result = verify_sha256_report(&HEADER, report.nonce, report.version_field, &target); - backend.set_psu_enabled(false)?; - if !result.meets_target { - return Err("captured nonce does not meet difficulty 1".into()); - } + miner.submit(HEADER, target, 0x18)?; + let share = miner.poll()?.ok_or("missing BM1366 nonce report")?; + miner.stop()?; + assert_eq!(share.nonce, 0xedad_ff38); println!("BM1366 captured report verified at difficulty 1"); Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index 2029a16..9b344f7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod bm1366; pub mod hal_wire; +pub mod miner; pub mod pow; #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/src/miner.rs b/src/miner.rs new file mode 100644 index 0000000..1e7901a --- /dev/null +++ b/src/miner.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT +//! One-chain BM1366 mining control built on the SDK hardware backend. +//! This module never searches for nonces or chooses board safety thresholds. + +use crate::bm1366::{decode_nonce_report, encode_work, ReportError, REPORT_BYTES}; +use crate::pow::verify_sha256_report; +use crate::{power_decision, HardwareBackend, PowerDecision}; +use std::fmt; + +#[derive(Debug, Eq, PartialEq)] +pub enum MinerError { + Backend(E), + AlreadyRunning, + NotRunning, + UnsafeTemperature(i32), + InvalidWork, + InvalidReport(ReportError), + StaleReport, + BelowTarget, +} + +impl fmt::Display for MinerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Backend(error) => write!(f, "hardware backend: {error}"), + Self::AlreadyRunning => f.write_str("miner is already running"), + Self::NotRunning => f.write_str("miner is not running"), + Self::UnsafeTemperature(value) => write!(f, "unsafe temperature: {value} mC"), + Self::InvalidWork => f.write_str("invalid BM1366 work"), + Self::InvalidReport(error) => write!(f, "invalid BM1366 report: {error:?}"), + Self::StaleReport => f.write_str("stale BM1366 work ID"), + Self::BelowTarget => f.write_str("nonce is below the pool target"), + } + } +} + +impl std::error::Error for MinerError {} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ValidShare { + pub nonce: u32, + pub work_id: u8, + pub rolled_version: u32, + pub hash_le: [u8; 32], +} + +#[derive(Clone, Copy)] +struct Work { + header: [u8; 80], + target_le: [u8; 32], + id: u8, +} + +pub struct Bm1366Miner<'a, B: HardwareBackend> { + backend: &'a mut B, + chain: u8, + sensor: u8, + fan: u8, + fan_percent: u8, + max_temperature_mc: i32, + running: bool, + work: Option, +} + +impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> { + /// The caller supplies a threshold validated for this board revision. + pub fn new( + backend: &'a mut B, + chain: u8, + sensor: u8, + fan: u8, + fan_percent: u8, + max_temperature_mc: i32, + ) -> Option { + if fan_percent == 0 || fan_percent > 100 || max_temperature_mc <= 0 { + return None; + } + Some(Self { + backend, + chain, + sensor, + fan, + fan_percent, + max_temperature_mc, + running: false, + work: None, + }) + } + + fn power_off(&mut self) -> Result<(), B::Error> { + self.work = None; + match self.backend.set_psu_enabled(false) { + Ok(()) => { + self.running = false; + Ok(()) + } + Err(error) => { + // The backend may have left power on. Drop retries shutdown. + self.running = true; + Err(error) + } + } + } + + fn check_temperature(&mut self) -> Result<(), MinerError> { + let value = match self.backend.read_temperature_mc(self.sensor) { + Ok(value) => value, + Err(error) => { + let _ = self.power_off(); + return Err(MinerError::Backend(error)); + } + }; + if power_decision(Some(value), self.max_temperature_mc) == PowerDecision::Stop { + let _ = self.power_off(); + return Err(MinerError::UnsafeTemperature(value)); + } + Ok(()) + } + + pub fn start(&mut self) -> Result<(), MinerError> { + if self.running { + return Err(MinerError::AlreadyRunning); + } + self.power_off().map_err(MinerError::Backend)?; + self.check_temperature()?; + self.backend + .set_fan_target(self.fan, self.fan_percent) + .map_err(MinerError::Backend)?; + if let Err(error) = self.backend.set_psu_enabled(true) { + let _ = self.power_off(); + return Err(MinerError::Backend(error)); + } + self.running = true; + if let Err(error) = self.backend.set_chain_reset(self.chain, true) { + let _ = self.power_off(); + return Err(MinerError::Backend(error)); + } + if let Err(error) = self.backend.set_chain_reset(self.chain, false) { + let _ = self.power_off(); + return Err(MinerError::Backend(error)); + } + Ok(()) + } + + pub fn stop(&mut self) -> Result<(), B::Error> { + self.power_off() + } + + pub fn submit( + &mut self, + header: [u8; 80], + target_le: [u8; 32], + work_id: u8, + ) -> Result<(), MinerError> { + if !self.running { + return Err(MinerError::NotRunning); + } + let frame = encode_work(&header, work_id).ok_or(MinerError::InvalidWork)?; + self.check_temperature()?; + if let Err(error) = self.backend.send_frame(self.chain, &frame) { + let _ = self.power_off(); + return Err(MinerError::Backend(error)); + } + self.work = Some(Work { + header, + target_le, + id: work_id, + }); + Ok(()) + } + + pub fn poll(&mut self) -> Result, MinerError> { + if !self.running { + return Err(MinerError::NotRunning); + } + self.check_temperature()?; + let mut frame = [0_u8; REPORT_BYTES]; + let length = match self.backend.receive_frame(self.chain, &mut frame) { + Ok(length) => length, + Err(error) => { + let _ = self.power_off(); + return Err(MinerError::Backend(error)); + } + }; + if length == 0 { + return Ok(None); + } + let report = match decode_nonce_report(&frame[..length.min(REPORT_BYTES)]) { + Ok(report) if length == REPORT_BYTES => report, + Ok(_) => { + let _ = self.power_off(); + return Err(MinerError::InvalidReport(ReportError::Length)); + } + Err(error) => { + let _ = self.power_off(); + return Err(MinerError::InvalidReport(error)); + } + }; + let Some(work) = self.work else { + let _ = self.power_off(); + return Err(MinerError::StaleReport); + }; + if report.work_id != work.id { + let _ = self.power_off(); + return Err(MinerError::StaleReport); + } + let check = verify_sha256_report( + &work.header, + report.nonce, + report.version_field, + &work.target_le, + ); + if !check.meets_target { + return Err(MinerError::BelowTarget); + } + Ok(Some(ValidShare { + nonce: report.nonce, + work_id: report.work_id, + rolled_version: check.rolled_version, + hash_le: check.hash_le, + })) + } +} + +impl Drop for Bm1366Miner<'_, B> { + fn drop(&mut self) { + if self.running { + let _ = self.power_off(); + } + } +} diff --git a/tests/bench.rs b/tests/bench.rs index c15c75c..76cf273 100644 --- a/tests/bench.rs +++ b/tests/bench.rs @@ -1,6 +1,7 @@ use alkane_os::bm1366::{decode_nonce_report, encode_work}; +use alkane_os::miner::Bm1366Miner; use alkane_os::pow::verify_sha256_report; -use alkane_os::{power_decision, target_matrix}; +use alkane_os::{power_decision, target_matrix, HardwareBackend}; use std::hint::black_box; use std::time::Instant; @@ -67,3 +68,46 @@ fn bench_bm1366_report_decode() { let _ = black_box(decode_nonce_report(black_box(&report))); }); } + +struct BenchBackend; + +impl HardwareBackend for BenchBackend { + type Error = (); + + fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> { + black_box(frame); + Ok(()) + } + fn receive_frame(&mut self, _chain: u8, _frame: &mut [u8]) -> Result { + Ok(0) + } + fn set_chain_reset(&mut self, _chain: u8, _asserted: bool) -> Result<(), Self::Error> { + Ok(()) + } + fn set_fan_target(&mut self, _fan: u8, _percent: u8) -> Result<(), Self::Error> { + Ok(()) + } + fn read_temperature_mc(&mut self, _sensor: u8) -> Result { + Ok(50_000) + } + fn set_psu_enabled(&mut self, _enabled: bool) -> Result<(), Self::Error> { + Ok(()) + } +} + +#[test] +#[ignore = "microbenchmark"] +fn bench_bm1366_session_cycle() { + let header = [0_u8; 80]; + let target = [0xff_u8; 32]; + measure("bm1366_session_cycle", 20_000, || { + let mut backend = BenchBackend; + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); + miner.start().unwrap(); + miner + .submit(black_box(header), black_box(target), 0x18) + .unwrap(); + black_box(miner.poll().unwrap()); + miner.stop().unwrap(); + }); +} diff --git a/tests/miner.rs b/tests/miner.rs new file mode 100644 index 0000000..ed4c3b7 --- /dev/null +++ b/tests/miner.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: MIT +use alkane_os::bm1366::REPORT_BYTES; +use alkane_os::miner::{Bm1366Miner, MinerError}; +use alkane_os::HardwareBackend; + +const HEADER: [u8; 80] = [ + 0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38, 0x9d, + 0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, 0x57, 0xb6, 0xc2, 0x25, + 0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78, + 0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38, + 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, +]; +const REPORT: [u8; REPORT_BYTES] = [ + 0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94, +]; + +fn diff_one() -> [u8; 32] { + let mut target = [0_u8; 32]; + target[26..28].fill(0xff); + target +} + +#[derive(Default)] +struct FakeBackend { + events: Vec<&'static str>, + temperatures: Vec, + powered: bool, + fail_off_call: usize, + off_calls: usize, + report: Option<[u8; REPORT_BYTES]>, + sent: Vec, +} + +impl HardwareBackend for FakeBackend { + type Error = &'static str; + + fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> { + assert!(self.powered); + self.events.push("send"); + self.sent = frame.to_vec(); + Ok(()) + } + + fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result { + self.events.push("receive"); + if let Some(report) = self.report.take() { + frame[..REPORT_BYTES].copy_from_slice(&report); + Ok(REPORT_BYTES) + } else { + Ok(0) + } + } + + fn set_chain_reset(&mut self, _chain: u8, asserted: bool) -> Result<(), Self::Error> { + assert!(self.powered); + self.events + .push(if asserted { "reset-on" } else { "reset-off" }); + Ok(()) + } + + fn set_fan_target(&mut self, _fan: u8, percent: u8) -> Result<(), Self::Error> { + assert!(percent > 0); + self.events.push("fan"); + Ok(()) + } + + fn read_temperature_mc(&mut self, _sensor: u8) -> Result { + self.events.push("temperature"); + if self.temperatures.is_empty() { + return Err("sensor unavailable"); + } + Ok(self.temperatures.remove(0)) + } + + fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> { + self.events.push(if enabled { "psu-on" } else { "psu-off" }); + if !enabled { + self.off_calls += 1; + if self.off_calls == self.fail_off_call { + return Err("power-off did not complete"); + } + } + self.powered = enabled; + Ok(()) + } +} + +#[test] +fn captured_nonce_passes_a_started_miner() { + let mut backend = FakeBackend { + temperatures: vec![50_000, 50_000, 50_000], + report: Some(REPORT), + ..Default::default() + }; + { + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); + miner.start().unwrap(); + miner.submit(HEADER, diff_one(), 0x18).unwrap(); + let share = miner.poll().unwrap().unwrap(); + assert_eq!(share.nonce, 0xedad_ff38); + assert_eq!(share.work_id, 0x18); + assert_eq!(share.rolled_version, 0x2096_6000); + miner.stop().unwrap(); + } + assert!(!backend.powered); + assert_eq!(&backend.sent[..5], &[0x55, 0xaa, 0x21, 0x54, 0x18]); + assert_eq!( + &backend.events[..6], + &[ + "psu-off", + "temperature", + "fan", + "psu-on", + "reset-on", + "reset-off" + ] + ); +} + +#[test] +fn hot_or_missing_sensor_stops_power() { + let mut hot = FakeBackend { + temperatures: vec![80_000], + ..Default::default() + }; + let mut miner = Bm1366Miner::new(&mut hot, 0, 0, 0, 100, 80_000).unwrap(); + assert_eq!(miner.start(), Err(MinerError::UnsafeTemperature(80_000))); + drop(miner); + assert!(!hot.powered); + assert!(!hot.events.contains(&"psu-on")); + + let mut missing = FakeBackend::default(); + let mut miner = Bm1366Miner::new(&mut missing, 0, 0, 0, 100, 80_000).unwrap(); + assert_eq!( + miner.start(), + Err(MinerError::Backend("sensor unavailable")) + ); + drop(miner); + assert!(!missing.powered); +} + +#[test] +fn temperature_rise_and_stale_report_fail_closed() { + let mut backend = FakeBackend { + temperatures: vec![50_000, 50_000, 90_000], + report: Some(REPORT), + ..Default::default() + }; + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); + miner.start().unwrap(); + miner.submit(HEADER, diff_one(), 0x18).unwrap(); + assert_eq!(miner.poll(), Err(MinerError::UnsafeTemperature(90_000))); + assert_eq!(miner.poll(), Err(MinerError::NotRunning)); + drop(miner); + assert!(!backend.powered); + + let mut backend = FakeBackend { + temperatures: vec![50_000, 50_000, 50_000], + report: Some(REPORT), + ..Default::default() + }; + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); + miner.start().unwrap(); + miner.submit(HEADER, diff_one(), 0x20).unwrap(); + assert_eq!(miner.poll(), Err(MinerError::StaleReport)); + drop(miner); + assert!(!backend.powered); +} + +#[test] +fn below_target_is_rejected_without_misreporting_a_share() { + let mut backend = FakeBackend { + temperatures: vec![50_000, 50_000, 50_000], + report: Some(REPORT), + ..Default::default() + }; + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); + miner.start().unwrap(); + miner.submit(HEADER, [0; 32], 0x18).unwrap(); + assert_eq!(miner.poll(), Err(MinerError::BelowTarget)); + drop(miner); + assert!(!backend.powered); +} + +#[test] +fn failed_power_off_is_retried_on_drop() { + let mut backend = FakeBackend { + temperatures: vec![50_000], + fail_off_call: 2, + ..Default::default() + }; + let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); + miner.start().unwrap(); + assert_eq!(miner.stop(), Err("power-off did not complete")); + drop(miner); + assert_eq!(backend.off_calls, 3); + assert!(!backend.powered); +} From 7a7a5b1612c27a299b75b222bd742eff8b35547f Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:58:13 -0600 Subject: [PATCH 08/83] Ignore cancelled runs in completed CI badge --- ci/last-attempt-badge.py | 2 +- ci/test-last-attempt-badge.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/last-attempt-badge.py b/ci/last-attempt-badge.py index c77bdb1..fd58560 100644 --- a/ci/last-attempt-badge.py +++ b/ci/last-attempt-badge.py @@ -51,7 +51,7 @@ def latest_completed(api: str, repo: str, workflow: str, branch: str, for run in runs: if run.get("head_branch") != branch or run.get("status") != "completed": continue - if run.get("conclusion") not in ("success", "failure", "cancelled", "skipped"): + if run.get("conclusion") not in ("success", "failure"): continue candidate = (int(run["id"]), run["conclusion"]) if latest is None or candidate[0] > latest[0]: diff --git a/ci/test-last-attempt-badge.py b/ci/test-last-attempt-badge.py index 2c19243..e954512 100644 --- a/ci/test-last-attempt-badge.py +++ b/ci/test-last-attempt-badge.py @@ -15,6 +15,7 @@ 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"}, From 2c58237e7869481a163760450dc5eb7413b0eab7 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 20:10:42 -0600 Subject: [PATCH 09/83] Publish measured OS badges to private branch --- .gitea/workflows/main.yml | 7 +++++ README.md | 21 +++++++------- ci/badge_store.py | 54 +++++++++++++++++++++++++++++++++++ ci/last-attempt-badge.py | 44 +++------------------------- ci/publish-metrics.py | 32 +++++++++++++++++++++ ci/test-last-attempt-badge.py | 10 +++++++ 6 files changed, 118 insertions(+), 50 deletions(-) create mode 100644 ci/badge_store.py create mode 100644 ci/publish-metrics.py diff --git a/.gitea/workflows/main.yml b/.gitea/workflows/main.yml index 04f6e14..671402b 100644 --- a/.gitea/workflows/main.yml +++ b/.gitea/workflows/main.yml @@ -7,6 +7,9 @@ on: jobs: verify-and-release: runs-on: alkane-ci + permissions: + contents: write + actions: write steps: - uses: actions/checkout@v4 with: @@ -57,6 +60,10 @@ jobs: 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: Pairing and simulator conformance run: python3 ci/check-conformance.py - name: Select release version diff --git a/README.md b/README.md index 8aed434..cf62dbb 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # Alkane OS [![CI](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-os/actions) -![tests](badges/tests.svg) -![coverage](badges/coverage.svg) -![bench](badges/bench.svg) -![bench coverage](badges/bench-coverage.svg) -![lines of code](badges/loc.svg) -![dependencies](badges/dependencies.svg) -![code quality](badges/quality.svg) -![license](badges/license.svg) +![tests](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/tests.svg) +![coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/coverage.svg) +![bench](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench.svg) +![bench coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench-coverage.svg) +![lines of code](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/loc.svg) +![dependencies](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/dependencies.svg) +![code quality](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/quality.svg) +![license](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/license.svg) Portable mining, tuning, and management logic for Alkane control boards. The source is MIT licensed. `alkane-sdk` owns the board images and supplies the @@ -67,5 +67,6 @@ still pending. It is a release gate, not a unit test. The badges record measured host-side checks for this initial core. They do not imply that any board image or mining target has passed conformance. -The CI badge is served from a private, machine-maintained branch and shows -the last completed attempt for this source branch while newer runs are queued. +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. diff --git a/ci/badge_store.py b/ci/badge_store.py new file mode 100644 index 0000000..679c917 --- /dev/null +++ b/ci/badge_store.py @@ -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) -> None: + if not filename or filename.startswith("/") or any( + part in ("", ".", "..") for part in filename.split("/")): + raise ValueError("invalid badge path") + if len(data) > 65_536: + raise ValueError("badge artifact exceeds 64 KiB") + 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") diff --git a/ci/last-attempt-badge.py b/ci/last-attempt-badge.py index fd58560..c7eca28 100644 --- a/ci/last-attempt-badge.py +++ b/ci/last-attempt-badge.py @@ -2,17 +2,15 @@ # SPDX-License-Identifier: MIT """Publish the last completed main/next CI result to a private badge branch.""" -import base64 import json import os from pathlib import Path -from urllib.error import HTTPError from urllib.parse import quote, urlencode -from urllib.request import Request, urlopen + +from badge_store import publish_file, request_json WORKFLOWS = {"main.yml": "main", "next.yml": "next"} -BADGE_BRANCH = "ci-badges" def badge(branch: str, conclusion: str, run_id: int) -> bytes: @@ -30,16 +28,6 @@ def badge(branch: str, conclusion: str, run_id: int) -> bytes: f'font-family="sans-serif" font-size="11">{word}\n').encode() -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 latest_completed(api: str, repo: str, workflow: str, branch: str, token: str) -> tuple[int, str]: path = quote(workflow, safe="") @@ -64,32 +52,8 @@ def latest_completed(api: str, repo: str, workflow: str, branch: str, def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None: - path = f"{api}/repos/{repo}/contents/{branch}.svg" - encoded = base64.b64encode(data).decode("ascii") - for attempt in range(3): - try: - current = request_json(path + "?ref=" + BADGE_BRANCH, token) - current_data = base64.b64decode(current["content"]) - if current_data == 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": f"Record completed {branch} CI attempt"} - 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") + publish_file(api, repo, f"{branch}.svg", data, token, + f"Record completed {branch} CI attempt") def main() -> None: diff --git a/ci/publish-metrics.py b/ci/publish-metrics.py new file mode 100644 index 0000000..46cc9c7 --- /dev/null +++ b/ci/publish-metrics.py @@ -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"fail" in svg assert b"#d1242f" in svg assert b">pass" in module.badge("next", "success", 108) +for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"): + try: + publish_file("https://example.invalid/api/v1", "owner/repo", invalid, + b"", "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") From f49083ee96de873fecd3afc73bfab4c51685e60e Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 20:17:23 -0600 Subject: [PATCH 10/83] Record private per-commit OS benchmark history --- .gitea/workflows/main.yml | 14 ++++ ci/badge_store.py | 6 +- ci/bench_history.py | 146 ++++++++++++++++++++++++++++++++++++++ ci/metrics.py | 3 +- ci/test-bench-history.py | 46 ++++++++++++ 5 files changed, 211 insertions(+), 4 deletions(-) create mode 100644 ci/bench_history.py create mode 100644 ci/test-bench-history.py diff --git a/.gitea/workflows/main.yml b/.gitea/workflows/main.yml index 671402b..30b6018 100644 --- a/.gitea/workflows/main.yml +++ b/.gitea/workflows/main.yml @@ -20,6 +20,8 @@ jobs: run: cargo fmt --check - name: Last-attempt badge checks run: python3 ci/test-last-attempt-badge.py + - name: Benchmark history checks + run: python3 ci/test-bench-history.py - name: Quality run: cargo clippy --all-targets --locked -- -D warnings - name: Build @@ -47,6 +49,10 @@ jobs: 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 \ @@ -64,6 +70,14 @@ jobs: 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: actions/upload-artifact@v4 + with: + name: alkane-os-benchmark-site-preview + path: bench-site/index.html - name: Pairing and simulator conformance run: python3 ci/check-conformance.py - name: Select release version diff --git a/ci/badge_store.py b/ci/badge_store.py index 679c917..bc3250d 100644 --- a/ci/badge_store.py +++ b/ci/badge_store.py @@ -21,12 +21,12 @@ def request_json(url: str, token: str, method: str = "GET", def publish_file(api: str, repo: str, filename: str, data: bytes, - token: str, message: str) -> None: + 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) > 65_536: - raise ValueError("badge artifact exceeds 64 KiB") + 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): diff --git a/ci/bench_history.py b/ci/bench_history.py new file mode 100644 index 0000000..8591779 --- /dev/null +++ b/ci/bench_history.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Keep measured main-branch benchmarks in the private CI artifact branch.""" + +import argparse +import base64 +from datetime import datetime, timezone +import html +import json +import math +import os +from pathlib import Path +import re +import subprocess +from urllib.error import HTTPError +from urllib.parse import quote + +from badge_store import BADGE_BRANCH, publish_file, request_json + +INDEX = "history/index.json" +MAX_INDEX_ENTRIES = 50 + + +def read_artifact(api: str, repo: str, token: str, filename: str): + url = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}?ref={BADGE_BRANCH}" + try: + value = request_json(url, token) + except HTTPError as error: + if error.code == 404: + return None + raise + return json.loads(base64.b64decode(value["content"])) + + +def valid_benches(metrics: dict) -> dict[str, float]: + values = metrics.get("bench_ns_per_op") + if not isinstance(values, dict) or not values: + raise ValueError("benchmark measurements are missing") + if any(not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key) + or not isinstance(value, (float, int)) or isinstance(value, bool) + or not math.isfinite(value) or value <= 0 for key, value in values.items()): + raise ValueError("benchmark measurements are invalid") + return values + + +def git_distance(ancestor: str, sha: str) -> int | None: + result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"), + capture_output=True, text=True, check=False) + if result.returncode != 0: + return None + ancestor_check = subprocess.run(("git", "merge-base", "--is-ancestor", ancestor, sha), + capture_output=True, check=False) + return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None + + +def previous_measurement(index: dict, sha: str, distance=None) -> dict: + distance = distance or git_distance + choices = [] + for entry in index.get("entries", []): + ancestor = entry.get("sha") + if ancestor == sha or not isinstance(ancestor, str): + continue + gap = distance(ancestor, sha) + if gap is not None and gap > 0: + choices.append((gap, entry)) + if not choices: + return {} + return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"]) + + +def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict: + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("invalid commit SHA") + valid_benches(metrics) + entries = [entry for entry in index.get("entries", []) if entry.get("sha") != sha] + entries.append({"sha": sha, "timestamp": timestamp, "metrics": metrics}) + return {"schema": 1, "entries": entries[-MAX_INDEX_ENTRIES:]} + + +def render_html(index: dict) -> str: + entries = list(reversed(index.get("entries", []))) + names = sorted({name for entry in entries + for name in valid_benches(entry["metrics"])}) + rows = [] + for entry in entries: + sha = entry["sha"] + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("invalid commit SHA in history") + cells = [f'{sha[:10]}', + f'{html.escape(entry["timestamp"])}'] + values = valid_benches(entry["metrics"]) + cells += [f'{values[name]:.3f}' if name in values else 'new' + for name in names] + rows.append("" + "".join(cells) + "") + headings = "".join(f"{html.escape(name)} (ns/op)" for name in names) + return ("\n" + "" + "Alkane OS benchmarks" + "

Alkane OS microbenchmarks

" + "

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.

" + f"

Most recent {len(entries)} measured commits. Full per-commit JSON is retained " + "in the private ci-badges branch.

" + f"
" + f"{headings}{''.join(rows)}" + "
CommitUTC
\n") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("prepare", "publish")) + args = parser.parse_args() + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + token = os.environ["GITEA_TOKEN"] + sha = os.environ["GITHUB_SHA"] + index = read_artifact(api, repo, token, INDEX) or {"schema": 1, "entries": []} + if index.get("schema") != 1 or not isinstance(index.get("entries"), list): + raise ValueError("unsupported benchmark history index") + if args.action == "prepare": + baseline = previous_measurement(index, sha) + Path("badges").mkdir(exist_ok=True) + Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n") + print(f"Loaded {len(baseline)} prior benchmark measurements") + return + metrics = json.loads(Path("badges/metrics.json").read_text()) + timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") + index = updated_index(index, sha, metrics, timestamp) + record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n" + publish_file(api, repo, f"history/{sha}.json", record, token, + "Record Alkane OS benchmarks", max_bytes=1_048_576) + publish_file(api, repo, INDEX, json.dumps(index, indent=2).encode() + b"\n", + token, "Update Alkane OS benchmark index", max_bytes=1_048_576) + Path("bench-site").mkdir(exist_ok=True) + Path("bench-site/index.html").write_text(render_html(index)) + print(f"Recorded benchmarks for {sha[:10]}") + + +if __name__ == "__main__": + main() diff --git a/ci/metrics.py b/ci/metrics.py index fc6a6e2..c86ccec 100644 --- a/ci/metrics.py +++ b/ci/metrics.py @@ -51,6 +51,7 @@ def main(): parser.add_argument("--tests-coverage", required=True) parser.add_argument("--bench-output", required=True) parser.add_argument("--bench-coverage", required=True) + parser.add_argument("--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))) @@ -59,7 +60,7 @@ def main(): current = bench_results(args.bench_output) if not current or any(value <= 0 for value in current.values()): raise SystemExit("microbenchmark result missing or zero") - base_path = pathlib.Path("badges/bench-baseline.json") + base_path = pathlib.Path(args.bench_baseline) baseline = json.loads(base_path.read_text()) if base_path.exists() else {} common = [name for name in current if name in baseline and baseline[name] > 0] delta = (sum((baseline[name] - current[name]) / baseline[name] for name in common) diff --git a/ci/test-bench-history.py b/ci/test-bench-history.py new file mode 100644 index 0000000..a8b0a29 --- /dev/null +++ b/ci/test-bench-history.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise benchmark history selection and safe site rendering.""" + +import sys +from pathlib import Path +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from bench_history import previous_measurement, render_html, updated_index + + +class HistoryTests(unittest.TestCase): + def test_retry_uses_previous_commit(self): + first = "a" * 40 + second = "b" * 40 + index = {"schema": 1, "entries": [ + {"sha": first, "timestamp": "2026-01-01T00:00:00+00:00", + "metrics": {"bench_ns_per_op": {"hash": 10.0}}}, + {"sha": second, "timestamp": "2026-01-02T00:00:00+00:00", + "metrics": {"bench_ns_per_op": {"hash": 8.0}}}]} + self.assertEqual(previous_measurement(index, second, + lambda ancestor, sha: 1 if ancestor == first else None), + {"hash": 10.0}) + updated = updated_index(index, second, {"bench_ns_per_op": {"hash": 7.5}}, + "2026-01-03T00:00:00+00:00") + self.assertEqual(len(updated["entries"]), 2) + self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5) + + def test_invalid_measurement_and_sha_rejected(self): + with self.assertRaises(ValueError): + updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now") + with self.assertRaises(ValueError): + updated_index({}, "a" * 40, {"bench_ns_per_op": {"hash": -1}}, "now") + + def test_site_escapes_history_content(self): + entry = {"sha": "a" * 40, "timestamp": "", + "metrics": {"bench_ns_per_op": {"hash": 10.0}}} + page = render_html({"entries": [entry]}) + self.assertIn("<script>", page) + self.assertNotIn("", - "metrics": {"bench_ns_per_op": {"hash": 10.0}}} + "metrics": {"bench_ns_per_op": {"hash": 10.0}, + "bench_host": {"cpu_model": ""}}} page = render_html({"entries": [entry]}) self.assertIn("<script>", page) self.assertNotIn("