Add a reference HAL server and power telemetry
source-pr / source (pull_request) Successful in 13s

The reference server answers the real ALKH contract from a fixed machine
description, so the whole OS path can run on a development host and a backend
author has a concrete example of every opcode. It serves detection, frequency,
fan, temperature and power over one socket.

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

Fan mapping stays opt-in for --boot (ALKANE_FAN_FANS/ALKANE_FAN_ZONES) because
it perturbs the machine and takes minutes.
This commit is contained in:
2026-10-22 10:59:53 -06:00
parent dccbefc8b7
commit b0d81b5d0e
4 changed files with 290 additions and 6 deletions
+228
View File
@@ -0,0 +1,228 @@
// SPDX-License-Identifier: MIT
//! Reference HAL server.
//!
//! Speaks the same ALKH contract a family backend serves on a real board, but answers from a fixed
//! description of a machine. Two uses: it lets the whole OS path run on any development machine, and
//! it shows a backend author exactly what each opcode must return.
use std::io::{self, Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
const MAGIC: [u8; 4] = *b"ALKH";
const VERSION: u8 = 1;
const RESPONSE: u16 = 1;
const HEADER_LEN: usize = 16;
const SEND_FRAME: u8 = 1;
const RECEIVE_FRAME: u8 = 2;
const SET_CHAIN_RESET: u8 = 3;
const SET_FAN_TARGET: u8 = 4;
const READ_TEMPERATURE: u8 = 5;
const SET_PSU_ENABLED: u8 = 6;
const CAPABILITIES: u8 = 7;
const PROBE_CHAIN: u8 = 8;
const READ_EEPROM: u8 = 9;
const IDENTIFY_PSU: u8 = 10;
const SET_CHAIN_FREQUENCY: u8 = 11;
const READ_POWER: u8 = 12;
const CAP_ALL: u32 = (1 << 5) - 1;
/// What the simulated machine looks like.
#[derive(Clone, Debug)]
pub struct SimConfig {
/// Chains that identify. Chains beyond this answer silent.
pub chains: u8,
/// Chips reported per chain.
pub chips: u16,
/// Chip identifier on the wire (1 = bm1362).
pub chip: u8,
/// Report a working EEPROM instead of an absent one.
pub eeprom: bool,
/// PSU name and envelope, or `None` to fail identification.
pub psu: Option<(String, u16, u16, u16, u16, u16)>,
}
impl Default for SimConfig {
fn default() -> Self {
Self {
chains: 3,
chips: 126,
chip: 1,
eeprom: false,
psu: Some(("APW12".into(), 1200, 1600, 0, 1000, 3600)),
}
}
}
struct State {
config: SimConfig,
frequency_mhz: u16,
fan_pwm: u8,
}
/// Serve one socket path until the program exits.
pub fn serve(path: &Path, config: SimConfig) -> io::Result<()> {
let _ = std::fs::remove_file(path);
let listener = UnixListener::bind(path)?;
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let mut state = State {
config: config.clone(),
frequency_mhz: 0,
fan_pwm: 0,
};
let _ = serve_connection(stream, &mut state);
}
Ok(())
}
fn serve_connection(mut stream: UnixStream, state: &mut State) -> io::Result<()> {
loop {
let mut header = [0_u8; HEADER_LEN];
if stream.read_exact(&mut header).is_err() {
return Ok(());
}
if header[..4] != MAGIC {
return Err(io::Error::new(io::ErrorKind::InvalidData, "bad HAL magic"));
}
let opcode = header[5];
let sequence = header[8..12].to_vec();
let length = u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && stream.read_exact(&mut payload).is_err() {
return Ok(());
}
let body = respond(opcode, &payload, state);
let mut out = [0_u8; HEADER_LEN];
out[..4].copy_from_slice(&MAGIC);
out[4] = VERSION;
out[5] = opcode;
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
stream.write_all(&out)?;
stream.write_all(&body)?;
stream.flush()?;
}
}
fn respond(opcode: u8, payload: &[u8], state: &mut State) -> Vec<u8> {
match opcode {
CAPABILITIES => {
let mut body = vec![0_u8];
body.extend_from_slice(&CAP_ALL.to_le_bytes());
body
}
PROBE_CHAIN => {
let chain = payload.first().copied().unwrap_or(0);
if chain >= state.config.chains {
return vec![0, 1, 0, 0, 0]; // silent
}
let chips = state.config.chips.to_le_bytes();
vec![0, 0, state.config.chip, chips[0], chips[1]]
}
READ_EEPROM => {
if state.config.eeprom {
let mut body = vec![0_u8, 0];
body.extend_from_slice(b"BHB42601");
body
} else {
vec![0, 1]
}
}
IDENTIFY_PSU => match &state.config.psu {
Some((name, v_min, v_max, f_min, f_max, watts)) => {
let mut body = vec![0_u8, name.len() as u8];
body.extend_from_slice(name.as_bytes());
for word in [*v_min, *v_max, *f_min, *f_max, *watts] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
None => vec![1],
},
SET_CHAIN_FREQUENCY => {
if let Some(mhz) = payload.get(1..3) {
state.frequency_mhz = u16::from_le_bytes([mhz[0], mhz[1]]);
}
vec![0]
}
SET_FAN_TARGET => {
state.fan_pwm = payload.get(1).copied().unwrap_or(0);
vec![0]
}
READ_TEMPERATURE => {
// Temperature rises with frequency so the tuning loop has something to regulate.
let rise = i32::from(state.frequency_mhz) * 20;
let mut body = vec![0_u8];
body.extend_from_slice(&(45_000 + rise).to_le_bytes());
body
}
READ_POWER => {
// Four watts per MHz, so a power target has something to regulate.
let watts = u16::try_from(u32::from(state.frequency_mhz) * 4).unwrap_or(u16::MAX);
let mut body = vec![0_u8];
body.extend_from_slice(&watts.to_le_bytes());
body
}
SET_CHAIN_RESET | SET_PSU_ENABLED => vec![0],
SEND_FRAME => vec![0],
RECEIVE_FRAME => {
// No nonce traffic in the reference backend.
let count: u16 = 0;
let mut body = vec![0_u8];
body.extend_from_slice(&count.to_le_bytes());
body
}
_ => vec![1],
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hal_wire::HalClient;
use crate::HardwareBackend;
#[test]
fn a_client_can_detect_against_the_reference_server() {
let path = std::env::temp_dir().join(format!("alkane-sim-hal-{}.sock", std::process::id()));
// Bind before spawning so the client cannot race the socket into existence.
let listener = UnixListener::bind(&path).expect("bind");
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().expect("accept");
let mut state = State {
config: SimConfig::default(),
frequency_mhz: 0,
fan_pwm: 0,
};
let _ = serve_connection(stream, &mut state);
});
let mut client = HalClient::connect(&path).expect("connect");
assert_eq!(client.capabilities().expect("caps"), CAP_ALL);
match client.probe_chain(0, 0).expect("probe") {
crate::detect::ProbeOutcome::Identified { chip, chips } => {
assert_eq!(chip, crate::detect::ChipModel::Bm1362);
assert_eq!(chips, 126);
}
other => panic!("unexpected probe: {other:?}"),
}
assert_eq!(
client.read_eeprom(0).expect("eeprom"),
crate::detect::EepromState::Absent
);
let psu = client.identify_psu().expect("psu");
assert_eq!(psu.name, "APW12");
client.set_chain_frequency(0, 512).expect("freq");
assert_eq!(client.read_power_w().expect("power"), 512 * 4);
assert_eq!(
client.read_temperature_mc(0).expect("temp"),
45_000 + 512 * 20
);
drop(client);
let _ = std::fs::remove_file(&path);
server.join().expect("server");
}
}
+24 -2
View File
@@ -32,12 +32,14 @@ const PROBE_CHAIN: u8 = 8;
const READ_EEPROM: u8 = 9;
const IDENTIFY_PSU: u8 = 10;
const SET_CHAIN_FREQUENCY: u8 = 11;
const READ_POWER: u8 = 12;
/// Backend feature bits reported by `CAPABILITIES`.
pub const CAP_CHAIN_PROBE: u32 = 1 << 0;
pub const CAP_EEPROM: u32 = 1 << 1;
pub const CAP_PSU_IDENTITY: u32 = 1 << 2;
pub const CAP_FREQUENCY: u32 = 1 << 3;
pub const CAP_POWER: u32 = 1 << 4;
const PROBE_IDENTIFIED: u8 = 0;
const PROBE_SILENT: u8 = 1;
@@ -431,6 +433,17 @@ impl HalClient {
self.empty_reply(SET_CHAIN_FREQUENCY, &payload)
}
/// Measured DC input power in watts, when the board can read its PSU.
pub fn read_power_w(&mut self) -> Result<u16, HalError> {
self.require(CAP_POWER)?;
let body = self.exchange(READ_POWER, &[])?;
if body.len() != 2 {
self.poison();
return Err(HalError::Protocol("invalid power response"));
}
Ok(u16::from_le_bytes([body[0], body[1]]))
}
pub fn identify_psu(&mut self) -> Result<PsuCapability, HalError> {
self.require(CAP_PSU_IDENTITY)?;
let body = self.exchange(IDENTIFY_PSU, &[])?;
@@ -588,7 +601,11 @@ mod tests {
CAPABILITIES => {
let mut body = vec![0_u8];
body.extend_from_slice(
&(CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY)
&(CAP_CHAIN_PROBE
| CAP_EEPROM
| CAP_PSU_IDENTITY
| CAP_FREQUENCY
| CAP_POWER)
.to_le_bytes(),
);
body
@@ -610,6 +627,11 @@ mod tests {
body
}
SET_FAN_TARGET | SET_CHAIN_FREQUENCY => vec![0],
READ_POWER => {
let mut body = vec![0_u8];
body.extend_from_slice(&0_u16.to_le_bytes());
body
}
READ_TEMPERATURE => {
let mut body = vec![0_u8];
body.extend_from_slice(&42_000_i32.to_le_bytes());
@@ -638,7 +660,7 @@ mod tests {
assert_eq!(
client.capabilities().expect("capabilities"),
CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY
CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY | CAP_POWER
);
match client.probe_chain(0, 0).expect("probe") {
ProbeOutcome::Identified { chip, chips } => {
+1
View File
@@ -13,6 +13,7 @@ pub mod difficulty;
pub mod fanmap;
pub mod fanmap_store;
pub mod fault;
pub mod hal_sim;
pub mod hal_wire;
pub mod management;
pub mod miner;
+37 -4
View File
@@ -232,9 +232,25 @@ fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
let map_path = std::path::PathBuf::from(
std::env::var("ALKANE_FANMAP").unwrap_or_else(|_| "/var/lib/alkane/fanmap.json".into()),
);
// Fan mapping is opt-in: it perturbs the machine and takes minutes, so a plain boot skips it.
let fans: u8 = std::env::var("ALKANE_FAN_FANS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let zones: u8 = std::env::var("ALKANE_FAN_ZONES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let settings = app::HalBoot {
config: &config,
sweep: Default::default(),
sweep: alkane_os::fanmap::SweepConfig {
fans,
zones,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 20_000,
},
thresholds: Default::default(),
map_path: &map_path,
};
@@ -249,12 +265,13 @@ fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
let mut client = HalClient::connect(std::path::Path::new(&socket))?;
for _ in 0..ticks {
let hottest = client.read_temperature_mc(0).ok();
let power_w = client.read_power_w().ok().map(f32::from);
let outcome = runtime.tick(&Tick {
power_w: None,
power_w,
hashrate_ths: None,
hottest_mc: hottest,
ambient_mc: None,
dt_s: 5.0,
dt_s: 1.0,
});
if let TickOutcome::Run(command) = outcome {
for chain in runtime.active_chains() {
@@ -298,6 +315,22 @@ fn main() {
std::process::exit(1);
}
}
Some("--sim-hal") => {
let socket = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --sim-hal SOCKET");
std::process::exit(2);
}
};
if let Err(error) = alkane_os::hal_sim::serve(
std::path::Path::new(&socket),
alkane_os::hal_sim::SimConfig::default(),
) {
eprintln!("reference HAL stopped: {error}");
std::process::exit(1);
}
}
Some("--self-check") => {
if let Err(error) = self_check() {
eprintln!("self-check failed: {error}");
@@ -311,7 +344,7 @@ fn main() {
}
}
_ => {
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
eprintln!(
"env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..."
);