This commit is contained in:
@@ -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
|
||||
|
||||
+196
@@ -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<io::Error> for HalError {
|
||||
fn from(error: io::Error) -> Self {
|
||||
Self::Io(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// Local client for the privileged board backend supplied by the SDK image.
|
||||
pub struct HalClient {
|
||||
stream: UnixStream,
|
||||
sequence: u32,
|
||||
poisoned: bool,
|
||||
}
|
||||
|
||||
impl HalClient {
|
||||
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
|
||||
let stream = UnixStream::connect(path)?;
|
||||
Self::from_stream(stream)
|
||||
}
|
||||
|
||||
pub fn from_stream(stream: UnixStream) -> Result<Self, HalError> {
|
||||
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<Vec<u8>, HalError> {
|
||||
if self.poisoned {
|
||||
return Err(HalError::Protocol("connection is unusable"));
|
||||
}
|
||||
if payload.len() > MAX_PAYLOAD {
|
||||
return Err(HalError::FrameTooLong);
|
||||
}
|
||||
let result = self.exchange_inner(opcode, payload);
|
||||
if let Err(ref error) = result {
|
||||
if !matches!(error, HalError::Device(_)) {
|
||||
self.poisoned = true;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
|
||||
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<usize, Self::Error> {
|
||||
if frame.len() > MAX_PAYLOAD - 3 {
|
||||
return Err(HalError::FrameTooLong);
|
||||
}
|
||||
let mut request = [0_u8; 3];
|
||||
request[0] = chain;
|
||||
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
|
||||
let body = self.exchange(RECEIVE_FRAME, &request)?;
|
||||
if body.len() < 2 {
|
||||
self.poisoned = true;
|
||||
return Err(HalError::Protocol("missing receive length"));
|
||||
}
|
||||
let count = u16::from_le_bytes([body[0], body[1]]) as usize;
|
||||
if count > frame.len() || body.len() != count + 2 {
|
||||
self.poisoned = true;
|
||||
return Err(HalError::Protocol("invalid received frame size"));
|
||||
}
|
||||
frame[..count].copy_from_slice(&body[2..]);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error> {
|
||||
self.empty_reply(SET_CHAIN_RESET, &[chain, u8::from(asserted)])
|
||||
}
|
||||
|
||||
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error> {
|
||||
if percent > 100 {
|
||||
return Err(HalError::InvalidFanPercent);
|
||||
}
|
||||
self.empty_reply(SET_FAN_TARGET, &[fan, percent])
|
||||
}
|
||||
|
||||
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error> {
|
||||
let body = self.exchange(READ_TEMPERATURE, &[sensor])?;
|
||||
let bytes: [u8; 4] = match body.try_into() {
|
||||
Ok(bytes) => bytes,
|
||||
Err(_) => {
|
||||
self.poisoned = true;
|
||||
return Err(HalError::Protocol("invalid temperature response"));
|
||||
}
|
||||
};
|
||||
Ok(i32::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
|
||||
self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)])
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user