diff --git a/profiles.example.json b/profiles.example.json new file mode 100644 index 0000000..6dc7f98 --- /dev/null +++ b/profiles.example.json @@ -0,0 +1,19 @@ +{ + "schema": 1, + "profiles": [ + { + "name": "s19jpro-bm1362-pic", + "chip": "bm1362", + "sensor": "pic", + "chains": 3, + "envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700} + }, + { + "name": "s19kpro-bm1366-nopic", + "chip": "bm1366", + "sensor": "nopic", + "chains": 3, + "envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700} + } + ] +} diff --git a/src/app.rs b/src/app.rs new file mode 100644 index 0000000..680342a --- /dev/null +++ b/src/app.rs @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: MIT +//! Process wiring: start the API and UI servers and publish the hardware snapshot. +//! +//! The binary and the tests use the same function, so the wiring that CI exercises is the wiring +//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover +//! ephemeral ports instead of guessing them. + +use crate::detect::{ + run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget, + SensorTopology, +}; +use crate::fanmap::{FanMap, MapThresholds, SweepConfig}; +use crate::fanmap_store::ensure_map; +use crate::fault::FaultPolicy; +use crate::hal_wire::{HalClient, HalError}; +use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus}; +use crate::profiles::{ProfileDb, ProfileError}; +use crate::runtime::MinerRuntime; +use crate::tuning::{PidConfig, TuningTarget}; +use crate::web; +use std::fmt; +use std::io; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::path::Path; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::time::Duration; + +/// Bound servers and their worker threads. +pub struct Servers { + pub api: Option, + pub web: Option, + handles: Vec>, +} + +impl Servers { + /// Addresses actually bound, which matters when port 0 was requested. + pub fn addresses(&self) -> (Option, Option) { + (self.api, self.web) + } + + /// Wait for the workers. Only useful in tests; the binary runs until it is killed. + pub fn join(self) { + for handle in self.handles { + let _ = handle.join(); + } + } +} + +/// Bind and start the cgminer-style API and the web UI, each when an address is given. +pub fn start( + status: Arc, + api: Option, + web_bind: Option, +) -> io::Result { + let api_listener = match api { + Some(address) => Some(bind_local(address)?), + None => None, + }; + let api_address = api_listener + .as_ref() + .map(|listener| listener.local_addr()) + .transpose()?; + let web_listener = match web_bind { + Some(address) => Some(TcpListener::bind(address)?), + None => None, + }; + let web_address = web_listener + .as_ref() + .map(|listener| listener.local_addr()) + .transpose()?; + + let mut handles = Vec::new(); + if let Some(listener) = api_listener { + let snapshot = Arc::clone(&status); + handles.push(std::thread::spawn(move || { + if let Err(error) = serve(listener, snapshot) { + eprintln!("management API stopped: {error}"); + } + })); + } + if let Some(listener) = web_listener { + let snapshot = Arc::clone(&status); + handles.push(std::thread::spawn(move || { + if let Err(error) = web::serve_listener(listener, snapshot) { + eprintln!("web UI stopped: {error}"); + } + })); + } + Ok(Servers { + api: api_address, + web: web_address, + handles, + }) +} + +/// Build the API snapshot from the live runtime. +pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot { + let plan = runtime.plan(); + HardwareSnapshot { + plan: plan.clone(), + active_chains: runtime.active_chains(), + stopped: runtime.stop_reason().map(|reason| match reason { + crate::fault::StopReason::Temperature => "temperature", + crate::fault::StopReason::NoChainsLeft => "no chains left", + }), + frequency_mhz: runtime.operating_point().frequency_mhz, + target: target.to_owned(), + } +} + +/// Everything a boot needs besides the backend. +#[derive(Clone, Debug, PartialEq)] +pub struct BootConfig { + pub profile_db_json: String, + pub chain_ports: Vec, + pub sensor: SensorTopology, + pub budget: ProbeBudget, + pub fan_zones: Vec, + pub target: TuningTarget, + pub pid: PidConfig, + pub ceiling_mc: i32, + pub fault_policy: FaultPolicy, +} + +/// Why boot did not reach a running runtime. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum BootError { + Profile(ProfileError), + Detection(DetectionFailure), + /// The board backend could not be reached or refused an operation. + Backend(E), +} + +impl fmt::Display for BootError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Profile(error) => write!(f, "profile database rejected: {error:?}"), + Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"), + Self::Backend(error) => write!(f, "hardware backend failed: {error:?}"), + } + } +} + +impl std::error::Error for BootError {} + +/// Operator target in the form the API and UI report. +pub fn target_label(target: &TuningTarget) -> String { + match *target { + TuningTarget::PowerW(watts) => format!("power:{watts:.0}"), + TuningTarget::HashrateThs(rate) => format!("hashrate:{rate:.0}"), + TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"), + TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"), + } +} + +/// Detect, decide, and publish: the sequence a family image runs at start-up. +pub fn boot( + backend: &mut B, + config: &BootConfig, + status: &MiningStatus, +) -> Result> { + let db = ProfileDb::from_json(&config.profile_db_json).map_err(BootError::Profile)?; + let request = DetectionRequest { + chain_ports: &config.chain_ports, + budget: config.budget, + sensor: config.sensor, + fan_zones: config.fan_zones.clone(), + }; + let plan = run_detection(backend, &db, &request).map_err(BootError::Detection)?; + let runtime = MinerRuntime::new( + plan, + config.fault_policy, + config.target, + config.pid, + config.ceiling_mc, + ); + status.set_hardware(snapshot(&runtime, &target_label(&config.target))); + Ok(runtime) +} + +/// A boot over the real local HAL contract, including the one-time fan sweep. +pub struct HalBoot<'a> { + pub config: &'a BootConfig, + pub sweep: SweepConfig, + pub thresholds: MapThresholds, + pub map_path: &'a Path, +} + +/// Connect the board backend, detect, map the fans once, and publish. +/// +/// This is the path an image takes on real hardware; the fakes in the tests speak the same HAL +/// protocol, so the wiring is exercised rather than assumed. +pub fn boot_from_hal( + socket: &Path, + settings: &HalBoot<'_>, + status: &MiningStatus, +) -> Result<(MinerRuntime, FanMap), BootError> { + let mut client = HalClient::connect(socket).map_err(BootError::Backend)?; + let zone_count = settings.sweep.zones; + let map = if zone_count == 0 { + FanMap::default() + } else { + ensure_map( + &mut client, + &settings.sweep, + settings.thresholds, + settings.map_path, + |millis| std::thread::sleep(std::time::Duration::from_millis(u64::from(millis))), + ) + .map_err(|error| match error { + crate::fanmap_store::StoreError::Sweep(crate::fanmap::SweepError::Backend(error)) => { + BootError::Backend(error) + } + crate::fanmap_store::StoreError::Sweep(_) => { + BootError::Backend(HalError::Protocol("fan sweep configuration rejected")) + } + crate::fanmap_store::StoreError::Io(message) => { + BootError::Backend(HalError::Protocol(message)) + } + })? + }; + let config = BootConfig { + fan_zones: map.assignments.clone(), + ..settings.config.clone() + }; + let runtime = boot(&mut client, &config, status)?; + Ok((runtime, map)) +} + +/// Read one HTTP response body from a bound server, for health checks and tests. +pub fn http_get(address: SocketAddr, path: &str) -> io::Result { + use std::io::{Read, Write}; + let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2))?; + stream.set_read_timeout(Some(Duration::from_secs(2)))?; + stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())?; + let mut reply = String::new(); + stream.read_to_string(&mut reply)?; + Ok(reply) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::detect::{ + ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint, + }; + use crate::detect::{ProbeOutcome, PsuCapability}; + use crate::fanmap::{MapThresholds, SweepConfig}; + use crate::fault::FaultPolicy; + use crate::tuning::{PidConfig, TuningTarget}; + use std::io::{Read, Write}; + + fn runtime() -> MinerRuntime { + MinerRuntime::new( + HardwarePlan { + profile: "s19jpro-bm1362-pic".into(), + chip: ChipModel::Bm1362, + chains: vec![ChainReport { + index: 0, + chip: ChipModel::Bm1362, + chips_found: 126, + eeprom: EepromState::Absent, + response_per_mille: Some(950), + }], + envelope: Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + operating_point: OperatingPoint { + voltage_mv: 1200, + frequency_mhz: 300, + confirmed: false, + }, + psu: "APW12".into(), + fan_zones: vec![FanZone { + fan: 0, + zones: vec![0], + }], + }, + FaultPolicy::default(), + TuningTarget::PowerW(2_400.0), + PidConfig::default(), + 95_000, + ) + } + + #[test] + fn both_servers_serve_the_published_snapshot() { + let status = Arc::new(MiningStatus::new()); + status.set_hardware(snapshot(&runtime(), "power:2400")); + let servers = start( + Arc::clone(&status), + Some("127.0.0.1:0".parse().unwrap()), + Some("127.0.0.1:0".parse().unwrap()), + ) + .expect("start"); + let (api, web) = servers.addresses(); + let api = api.expect("api address"); + let web = web.expect("web address"); + + let page = http_get(web, "/api/hardware").expect("web"); + assert!(page.contains("s19jpro-bm1362-pic")); + assert!(page.contains("power:2400")); + + let mut client = + TcpStream::connect_timeout(&api, Duration::from_secs(2)).expect("api connect"); + client + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("timeout"); + client.write_all(b"summary").expect("api write"); + let mut summary = String::new(); + client.read_to_string(&mut summary).expect("api read"); + assert!(summary.contains("SUMMARY")); + } + + #[test] + fn servers_are_optional() { + let status = Arc::new(MiningStatus::new()); + let servers = start(status, None, None).expect("start"); + assert_eq!(servers.addresses(), (None, None)); + } + + #[test] + fn the_snapshot_reports_runtime_state_not_boot_defaults() { + let mut runtime = runtime(); + runtime.tick(&crate::runtime::Tick { + power_w: Some(1_000.0), + hashrate_ths: None, + hottest_mc: Some(60_000), + ambient_mc: None, + dt_s: 1.0, + }); + let snapshot = snapshot(&runtime, "power:2400"); + assert_eq!(snapshot.target, "power:2400"); + assert_eq!(snapshot.active_chains, vec![0]); + assert!(snapshot.frequency_mhz > 300); + assert!(snapshot.stopped.is_none()); + } + + struct BootBackend { + outcome: ProbeOutcome, + psu: Option, + } + + impl DetectionBackend for BootBackend { + type Error = (); + + fn probe(&mut self, _chain: u8, _attempt: u8) -> Result { + Ok(self.outcome) + } + + fn eeprom(&mut self, _chain: u8) -> Result { + Ok(EepromState::Absent) + } + + fn identify_psu(&mut self) -> Result, ()> { + Ok(self.psu.clone()) + } + } + + const DB: &str = r#"{"schema":1,"profiles":[{"name":"s19jpro-bm1362-pic", + "chip":"bm1362","sensor":"pic","chains":3, + "envelope":{"v_min_mv":1100,"v_max_mv":1500,"f_min_mhz":300,"f_max_mhz":700}}]}"#; + + fn boot_config() -> BootConfig { + BootConfig { + profile_db_json: DB.into(), + chain_ports: vec![0, 1, 2], + sensor: SensorTopology::Pic, + budget: ProbeBudget::default(), + fan_zones: Vec::new(), + target: TuningTarget::PowerW(2_400.0), + pid: PidConfig::default(), + ceiling_mc: 95_000, + fault_policy: FaultPolicy::default(), + } + } + + fn psu() -> PsuCapability { + PsuCapability { + name: "APW12".into(), + envelope: Envelope { + v_min_mv: 1200, + v_max_mv: 1600, + f_min_mhz: 0, + f_max_mhz: 1_000, + }, + max_dc_watts: 3_600, + } + } + + #[test] + fn boot_detects_and_publishes() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + psu: Some(psu()), + }; + let status = MiningStatus::new(); + let runtime = boot(&mut backend, &boot_config(), &status).expect("boot"); + assert_eq!(runtime.active_chains(), vec![0, 1, 2]); + let document = status.hardware_document(); + assert_eq!(document["available"], true); + assert_eq!(document["target"], "power:2400"); + assert_eq!(document["psu"], "APW12"); + } + + #[test] + fn boot_refuses_an_unknown_chip() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Silent, + psu: Some(psu()), + }; + let status = MiningStatus::new(); + assert!(matches!( + boot(&mut backend, &boot_config(), &status), + Err(BootError::Detection(DetectionFailure::Refused(_))) + )); + assert_eq!(status.hardware_document()["available"], false); + } + + #[test] + fn boot_refuses_a_bad_profile_database() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + psu: Some(psu()), + }; + let mut config = boot_config(); + config.profile_db_json = "{\"schema\": 9}".into(); + assert!(matches!( + boot(&mut backend, &config, &MiningStatus::new()), + Err(BootError::Profile(_)) + )); + } + + #[test] + fn boot_refuses_a_missing_psu() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + psu: None, + }; + assert!(matches!( + boot(&mut backend, &boot_config(), &MiningStatus::new()), + Err(BootError::Detection(DetectionFailure::Refused(_))) + )); + } + + #[test] + fn target_labels_are_stable() { + assert_eq!(target_label(&TuningTarget::PowerW(3_000.0)), "power:3000"); + assert_eq!( + target_label(&TuningTarget::HashrateThs(200.0)), + "hashrate:200" + ); + assert_eq!( + target_label(&TuningTarget::AmbientC { margin_mc: 20_000 }), + "ambient:20000" + ); + assert_eq!( + target_label(&TuningTarget::MaxFan { max_pwm: 100 }), + "fan:100" + ); + } + + fn hal_server(socket: std::path::PathBuf) -> std::thread::JoinHandle<()> { + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + let listener = UnixListener::bind(&socket).expect("bind hal"); + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + loop { + let mut header = [0_u8; 16]; + if stream.read_exact(&mut header).is_err() { + return; + } + let opcode = header[5]; + let sequence = header[8..12].to_vec(); + let length = + u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize; + let mut payload = vec![0_u8; length]; + if length > 0 && stream.read_exact(&mut payload).is_err() { + return; + } + let body: Vec = match opcode { + // CAPABILITIES: chain probe, EEPROM, PSU identity. + 7 => { + let mut body = vec![0_u8]; + body.extend_from_slice(&7_u32.to_le_bytes()); + body + } + // PROBE_CHAIN: identified, bm1362, 126 chips. + 8 => vec![0, 0, 1, 126, 0], + // READ_EEPROM: absent. + 9 => vec![0, 1], + // IDENTIFY_PSU: APW12 with its envelope. + 10 => { + let name = b"APW12"; + let mut body = vec![0_u8, name.len() as u8]; + body.extend_from_slice(name); + for word in [1200_u16, 1600, 0, 1000, 3600] { + body.extend_from_slice(&word.to_le_bytes()); + } + body + } + _ => vec![1], + }; + let mut out = [0_u8; 16]; + out[..4].copy_from_slice(b"ALKH"); + out[4] = 1; + out[5] = opcode; + out[6..8].copy_from_slice(&1_u16.to_le_bytes()); + out[8..12].copy_from_slice(&sequence); + out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes()); + if stream.write_all(&out).is_err() || stream.write_all(&body).is_err() { + return; + } + } + }) + } + + #[test] + fn boot_over_the_hal_socket_detects_and_publishes() { + let base = std::env::temp_dir().join(format!("alkane-hal-{}", std::process::id())); + let socket = base.with_extension("sock"); + let map_path = base.with_extension("map.json"); + let _ = std::fs::remove_file(&socket); + let server = hal_server(socket.clone()); + let status = MiningStatus::new(); + let config = boot_config(); + let settings = HalBoot { + config: &config, + sweep: SweepConfig { + fans: 0, + zones: 0, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }, + thresholds: MapThresholds::default(), + map_path: &map_path, + }; + let (runtime, map) = boot_from_hal(&socket, &settings, &status).expect("boot over hal"); + assert_eq!(runtime.active_chains(), vec![0, 1, 2]); + assert!(map.assignments.is_empty()); + let document = status.hardware_document(); + assert_eq!(document["available"], true); + assert_eq!(document["psu"], "APW12"); + assert_eq!(document["chip"], "bm1362"); + let _ = std::fs::remove_file(&socket); + let _ = server.join(); + } + + #[test] + fn boot_over_a_missing_socket_is_a_backend_error() { + let socket = + std::env::temp_dir().join(format!("alkane-missing-{}.sock", std::process::id())); + let status = MiningStatus::new(); + let config = boot_config(); + let settings = HalBoot { + config: &config, + sweep: SweepConfig { + fans: 0, + zones: 0, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }, + thresholds: MapThresholds::default(), + map_path: &socket, + }; + assert!(matches!( + boot_from_hal(&socket, &settings, &status), + Err(BootError::Backend(_)) + )); + } +} diff --git a/src/detect.rs b/src/detect.rs new file mode 100644 index 0000000..3c7d325 --- /dev/null +++ b/src/detect.rs @@ -0,0 +1,761 @@ +// SPDX-License-Identifier: MIT +//! Hardware detection model. +//! +//! The detection core decides what is physically attached to a control board and whether that +//! combination is safe to run. It never talks to a chain directly; backends report what they +//! probed, and this module turns that into a `HardwarePlan` the miner can execute. +//! +//! Identification deliberately does not require a hashboard EEPROM. The EEPROM, when present and +//! valid, confirms a board revision; a chain probe alone is enough to select a chip profile. + +/// Chip families the detection core can name. `Unknown` is a real answer, not a placeholder. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ChipModel { + Bm1362, + Bm1366, + Bm1368, + Bm1370, + Bm1398, + Unknown, +} + +impl ChipModel { + /// Stable wire/API name for this chip family. + pub fn name(self) -> &'static str { + match self { + Self::Bm1362 => "bm1362", + Self::Bm1366 => "bm1366", + Self::Bm1368 => "bm1368", + Self::Bm1370 => "bm1370", + Self::Bm1398 => "bm1398", + Self::Unknown => "unknown", + } + } +} + +/// How a chain reports temperature. PIC boards proxy telemetry through the power MCU. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SensorTopology { + Pic, + NoPic, + Unknown, +} + +/// State of a hashboard EEPROM. Absence is normal and must never block detection. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum EepromState { + Present { model: String }, + Absent, + Invalid, +} + +/// What a backend observed on one physical chain. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ChainReport { + pub index: u8, + pub chip: ChipModel, + pub chips_found: u16, + pub eeprom: EepromState, + /// Nonce responses per mille of dispatched work, when the backend could measure it. + pub response_per_mille: Option, +} + +impl ChainReport { + pub fn is_identified(&self) -> bool { + self.chip != ChipModel::Unknown && self.chips_found > 0 + } +} + +/// Safe operating envelope for one hashboard/chip profile, from the profile database. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Envelope { + pub v_min_mv: u16, + pub v_max_mv: u16, + pub f_min_mhz: u16, + pub f_max_mhz: u16, +} + +impl Envelope { + /// Voltage that pairs with a frequency across this envelope. + /// + /// Voltage follows frequency linearly between the profile's floor and ceiling and is clamped + /// outside it. Boards do not run at a fixed voltage across their frequency range, so reporting + /// one voltage while the frequency moves would describe a machine that does not exist. + pub fn voltage_for(self, frequency_mhz: u16) -> u16 { + if frequency_mhz <= self.f_min_mhz { + return self.v_min_mv; + } + if frequency_mhz >= self.f_max_mhz { + return self.v_max_mv; + } + let span_f = u32::from(self.f_max_mhz - self.f_min_mhz); + let span_v = u32::from(self.v_max_mv - self.v_min_mv); + let offset = u32::from(frequency_mhz - self.f_min_mhz); + let voltage = u32::from(self.v_min_mv) + (span_v * offset) / span_f; + voltage.min(u32::from(u16::MAX)) as u16 + } + + pub fn intersect(self, other: Envelope) -> Option { + let v_min_mv = self.v_min_mv.max(other.v_min_mv); + let v_max_mv = self.v_max_mv.min(other.v_max_mv); + let f_min_mhz = self.f_min_mhz.max(other.f_min_mhz); + let f_max_mhz = self.f_max_mhz.min(other.f_max_mhz); + if v_min_mv > v_max_mv || f_min_mhz > f_max_mhz { + return None; + } + Some(Envelope { + v_min_mv, + v_max_mv, + f_min_mhz, + f_max_mhz, + }) + } +} + +/// A hashboard profile from the database. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct BoardProfile { + pub name: String, + pub chip: ChipModel, + pub sensor: SensorTopology, + pub chains: u8, + pub envelope: Envelope, +} + +/// What the PSU reports about itself and what it can deliver. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PsuCapability { + pub name: String, + pub envelope: Envelope, + pub max_dc_watts: u16, +} + +/// Which fans cool which thermal zones, learned by active probing. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FanZone { + pub fan: u8, + pub zones: Vec, +} + +/// Why detection refused a combination. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DetectionError { + NoChains, + UnknownChip, + ChipProfileMismatch, + PsuUnidentified, + EnvelopeEmpty, +} + +/// Operating point chosen for the machine. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct OperatingPoint { + pub voltage_mv: u16, + pub frequency_mhz: u16, + /// True when the profile was confirmed by an EEPROM or a full chain identification. + pub confirmed: bool, +} + +/// The result of detection: everything the miner needs and nothing it has to guess. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct HardwarePlan { + pub profile: String, + pub chip: ChipModel, + pub chains: Vec, + pub envelope: Envelope, + pub operating_point: OperatingPoint, + pub psu: String, + pub fan_zones: Vec, +} + +impl HardwarePlan { + /// Chains that identified but reported no nonces, or fewer than expected chips. + pub fn degraded_chains(&self, expected: u16) -> Vec { + self.chains + .iter() + .filter(|chain| { + chain.chips_found < expected + || chain.response_per_mille.is_some_and(|ratio| ratio == 0) + }) + .map(|chain| chain.index) + .collect() + } +} + +/// Turn observations into a plan, or refuse. +/// +/// Refusal is a feature: an unverified or out-of-envelope combination must not mine silently. +pub fn plan( + chains: &[ChainReport], + profile: &BoardProfile, + psu: Option<&PsuCapability>, + fan_zones: Vec, +) -> Result { + if chains.is_empty() { + return Err(DetectionError::NoChains); + } + if chains.iter().all(|chain| chain.chip == ChipModel::Unknown) { + return Err(DetectionError::UnknownChip); + } + if chains + .iter() + .filter(|chain| chain.is_identified()) + .any(|chain| chain.chip != profile.chip) + { + return Err(DetectionError::ChipProfileMismatch); + } + let psu = psu.ok_or(DetectionError::PsuUnidentified)?; + let envelope = profile + .envelope + .intersect(psu.envelope) + .ok_or(DetectionError::EnvelopeEmpty)?; + let confirmed = chains + .iter() + .any(|chain| matches!(chain.eeprom, EepromState::Present { .. })) + && chains.iter().all(ChainReport::is_identified); + let operating_point = if confirmed { + OperatingPoint { + voltage_mv: envelope.v_max_mv.min(profile.envelope.v_max_mv), + frequency_mhz: envelope.f_max_mhz.min(profile.envelope.f_max_mhz), + confirmed: true, + } + } else { + // Unverified hardware runs at the conservative floor of the usable envelope. + OperatingPoint { + voltage_mv: envelope.v_min_mv, + frequency_mhz: envelope.f_min_mhz, + confirmed: false, + } + }; + Ok(HardwarePlan { + profile: profile.name.clone(), + chip: profile.chip, + chains: chains.to_vec(), + envelope, + operating_point, + psu: psu.name.clone(), + fan_zones, + }) +} + +/// Outcome of one chip-identification attempt on a chain. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ProbeOutcome { + /// Chips answered: the model and how many responded. + Identified { chip: ChipModel, chips: u16 }, + /// The port is electrically silent (no signal at all). + Silent, + /// Bytes arrived but did not frame as a chip response: wrong baud, noise, or a dead TX. + Garbled, +} + +/// Backend contract for identification. +/// +/// Framing, baud switching and electrical detail stay in the SDK image for that family; the OS +/// only decides how many attempts to spend and what the results mean. +pub trait DetectionBackend { + type Error; + + /// Attempt one identification on `chain`. `attempt` lets the backend cycle its candidate + /// interface/baud set deterministically. A transport failure is an error, never `Silent`. + fn probe(&mut self, chain: u8, attempt: u8) -> Result; + /// Read the hashboard EEPROM, or report that it is absent or unreadable. + fn eeprom(&mut self, chain: u8) -> Result; + /// Identify the PSU, if this backend can. `None` means "cannot tell", which refuses later. + fn identify_psu(&mut self) -> Result, Self::Error>; +} + +/// How many identification attempts to spend per chain before declaring it unidentified. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ProbeBudget { + pub attempts: u8, +} + +impl Default for ProbeBudget { + fn default() -> Self { + Self { attempts: 4 } + } +} + +/// Probe one chain until it identifies or the budget is spent. +/// +/// A chain that never identifies is reported as `ChipModel::Unknown` with zero chips rather than +/// being dropped, so the plan can refuse explicitly and the API can show why. +pub fn probe_chain( + backend: &mut B, + chain: u8, + budget: ProbeBudget, +) -> Result { + let mut outcome = ProbeOutcome::Silent; + for attempt in 0..budget.attempts.max(1) { + outcome = backend.probe(chain, attempt)?; + if matches!(outcome, ProbeOutcome::Identified { .. }) { + break; + } + } + let (chip, chips_found) = match outcome { + ProbeOutcome::Identified { chip, chips } => (chip, chips), + _ => (ChipModel::Unknown, 0), + }; + Ok(ChainReport { + index: chain, + chip, + chips_found, + eeprom: backend.eeprom(chain)?, + response_per_mille: None, + }) +} + +/// Probe every declared chain port. +pub fn detect_chains( + backend: &mut B, + chains: &[u8], + budget: ProbeBudget, +) -> Result, B::Error> { + let mut reports = Vec::with_capacity(chains.len()); + for &chain in chains { + reports.push(probe_chain(backend, chain, budget)?); + } + Ok(reports) +} + +/// Everything the caller knows before probing: which ports exist, how hard to try, and how the +/// hashboards report temperature. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DetectionRequest<'a> { + pub chain_ports: &'a [u8], + pub budget: ProbeBudget, + pub sensor: SensorTopology, + pub fan_zones: Vec, +} + +/// Why a detection run did not produce a plan. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum DetectionFailure { + Backend(E), + Refused(DetectionError), + NoProfile, +} + +/// Detect, select a profile, and decide whether the machine may run. +/// +/// The profile is selected by chip, sensor wiring and the number of physical chain ports, so a +/// machine with a dead chain still matches its profile and runs degraded instead of being +/// reclassified as a different model. +pub fn run_detection( + backend: &mut B, + db: &crate::profiles::ProfileDb, + request: &DetectionRequest<'_>, +) -> Result> { + let reports = detect_chains(backend, request.chain_ports, request.budget) + .map_err(DetectionFailure::Backend)?; + let chip = reports + .iter() + .find(|report| report.is_identified()) + .map(|report| report.chip) + .ok_or(DetectionFailure::Refused(DetectionError::UnknownChip))?; + let chains = u8::try_from(request.chain_ports.len()).unwrap_or(u8::MAX); + let profile = db + .find(chip, chains, request.sensor) + .ok_or(DetectionFailure::NoProfile)?; + let psu = backend.identify_psu().map_err(DetectionFailure::Backend)?; + plan(&reports, profile, psu.as_ref(), request.fan_zones.clone()) + .map_err(DetectionFailure::Refused) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profile() -> BoardProfile { + BoardProfile { + name: "s19jpro-bm1362".into(), + chip: ChipModel::Bm1362, + sensor: SensorTopology::Pic, + chains: 3, + envelope: Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + } + } + + fn psu() -> PsuCapability { + PsuCapability { + name: "APW12".into(), + envelope: Envelope { + v_min_mv: 1200, + v_max_mv: 1600, + f_min_mhz: 0, + f_max_mhz: 1000, + }, + max_dc_watts: 3600, + } + } + + fn chain(index: u8, eeprom: EepromState) -> ChainReport { + ChainReport { + index, + chip: ChipModel::Bm1362, + chips_found: 126, + eeprom, + response_per_mille: Some(980), + } + } + + #[test] + fn confirmed_plan_uses_verified_ceiling() { + let chains = [chain( + 0, + EepromState::Present { + model: "BHB42601".into(), + }, + )]; + let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan"); + assert!(plan.operating_point.confirmed); + assert_eq!(plan.operating_point.voltage_mv, 1500); + assert_eq!(plan.operating_point.frequency_mhz, 700); + assert_eq!(plan.envelope.v_min_mv, 1200); + } + + #[test] + fn absent_eeprom_still_yields_a_conservative_plan() { + let chains = [chain(0, EepromState::Absent)]; + let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan"); + assert!(!plan.operating_point.confirmed); + assert_eq!(plan.operating_point.voltage_mv, plan.envelope.v_min_mv); + assert_eq!(plan.operating_point.frequency_mhz, plan.envelope.f_min_mhz); + } + + #[test] + fn unknown_chip_refuses() { + let mut chains = [chain(0, EepromState::Absent)]; + chains[0].chip = ChipModel::Unknown; + assert_eq!( + plan(&chains, &profile(), Some(&psu()), Vec::new()), + Err(DetectionError::UnknownChip) + ); + } + + #[test] + fn wrong_chip_refuses() { + let mut chains = [chain(0, EepromState::Absent)]; + chains[0].chip = ChipModel::Bm1366; + assert_eq!( + plan(&chains, &profile(), Some(&psu()), Vec::new()), + Err(DetectionError::ChipProfileMismatch) + ); + } + + #[test] + fn missing_psu_refuses() { + let chains = [chain(0, EepromState::Absent)]; + assert_eq!( + plan(&chains, &profile(), None, Vec::new()), + Err(DetectionError::PsuUnidentified) + ); + } + + #[test] + fn incompatible_psu_refuses() { + let chains = [chain(0, EepromState::Absent)]; + let weak = PsuCapability { + name: "APW3".into(), + envelope: Envelope { + v_min_mv: 700, + v_max_mv: 1090, + f_min_mhz: 0, + f_max_mhz: 1000, + }, + max_dc_watts: 1600, + }; + assert_eq!( + plan(&chains, &profile(), Some(&weak), Vec::new()), + Err(DetectionError::EnvelopeEmpty) + ); + } + + #[test] + fn empty_chain_set_refuses() { + assert_eq!( + plan(&[], &profile(), Some(&psu()), Vec::new()), + Err(DetectionError::NoChains) + ); + } + + #[test] + fn degraded_chains_are_reported_not_fatal() { + let mut silent = chain(1, EepromState::Absent); + silent.response_per_mille = Some(0); + let chains = [chain(0, EepromState::Absent), silent]; + let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan"); + assert_eq!(plan.degraded_chains(126), vec![1]); + } + + #[test] + fn fan_zones_are_carried_into_the_plan() { + let chains = [chain(0, EepromState::Absent)]; + let zones = vec![FanZone { + fan: 0, + zones: vec![0, 1], + }]; + let plan = plan(&chains, &profile(), Some(&psu()), zones.clone()).expect("plan"); + assert_eq!(plan.fan_zones, zones); + } + + struct ScriptedProbe { + plan: std::collections::VecDeque, + eeprom: EepromState, + calls: usize, + fail_at: u8, + psu: Option, + } + + impl ScriptedProbe { + fn new(plan: &[ProbeOutcome], eeprom: EepromState) -> Self { + Self { + plan: plan.iter().copied().collect(), + eeprom, + calls: 0, + fail_at: u8::MAX, + psu: Some(psu()), + } + } + } + + impl DetectionBackend for ScriptedProbe { + type Error = (); + + fn probe(&mut self, _chain: u8, attempt: u8) -> Result { + self.calls += 1; + if attempt == self.fail_at { + return Err(()); + } + Ok(self.plan.pop_front().unwrap_or(ProbeOutcome::Silent)) + } + + fn eeprom(&mut self, _chain: u8) -> Result { + Ok(self.eeprom.clone()) + } + + fn identify_psu(&mut self) -> Result, ()> { + Ok(self.psu.clone()) + } + } + + #[test] + fn probe_retries_until_the_chain_identifies() { + let mut backend = ScriptedProbe::new( + &[ + ProbeOutcome::Silent, + ProbeOutcome::Garbled, + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ], + EepromState::Absent, + ); + let report = probe_chain(&mut backend, 0, ProbeBudget { attempts: 4 }).expect("probe"); + assert_eq!(backend.calls, 3); + assert_eq!(report.chip, ChipModel::Bm1362); + assert_eq!(report.chips_found, 126); + assert!(report.is_identified()); + } + + #[test] + fn probe_exhaustion_is_reported_not_hidden() { + let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent); + let report = probe_chain(&mut backend, 1, ProbeBudget { attempts: 4 }).expect("probe"); + assert_eq!(backend.calls, 4); + assert_eq!(report.chip, ChipModel::Unknown); + assert_eq!(report.chips_found, 0); + assert!(!report.is_identified()); + } + + #[test] + fn probe_keeps_the_eeprom_state_even_when_unidentified() { + let mut backend = ScriptedProbe::new( + &[ProbeOutcome::Garbled; 2], + EepromState::Present { + model: "BHB42601".into(), + }, + ); + let report = probe_chain(&mut backend, 2, ProbeBudget { attempts: 2 }).expect("probe"); + assert_eq!(report.chip, ChipModel::Unknown); + assert_eq!( + report.eeprom, + EepromState::Present { + model: "BHB42601".into() + } + ); + } + + #[test] + fn detection_covers_every_declared_chain_port() { + let mut backend = ScriptedProbe::new( + &[ + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ], + EepromState::Absent, + ); + let reports = + detect_chains(&mut backend, &[0, 1, 2], ProbeBudget::default()).expect("detect"); + assert_eq!(reports.len(), 3); + assert_eq!( + reports.iter().map(|r| r.index).collect::>(), + vec![0, 1, 2] + ); + assert!(reports.iter().all(ChainReport::is_identified)); + } + + #[test] + fn transport_failure_is_not_reported_as_a_silent_port() { + let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent); + backend.fail_at = 1; + assert_eq!( + probe_chain(&mut backend, 0, ProbeBudget::default()), + Err(()) + ); + assert_eq!(backend.calls, 2); + } + + #[test] + fn unidentified_chain_makes_the_plan_refuse() { + let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent); + let reports = detect_chains(&mut backend, &[0], ProbeBudget::default()).expect("detect"); + assert_eq!( + plan(&reports, &profile(), Some(&psu()), Vec::new()), + Err(DetectionError::UnknownChip) + ); + } + + fn db() -> crate::profiles::ProfileDb { + crate::profiles::ProfileDb::new(vec![profile()]).expect("db") + } + + #[test] + fn run_detection_emits_a_plan_end_to_end() { + let mut backend = ScriptedProbe::new( + &[ + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ], + EepromState::Absent, + ); + let request = DetectionRequest { + chain_ports: &[0, 1, 2], + budget: ProbeBudget::default(), + sensor: SensorTopology::Pic, + fan_zones: vec![FanZone { + fan: 0, + zones: vec![0], + }], + }; + let plan = run_detection(&mut backend, &db(), &request).expect("plan"); + assert_eq!(plan.chains.len(), 3); + assert_eq!(plan.psu, "APW12"); + assert!(!plan.operating_point.confirmed); + assert_eq!(plan.operating_point.voltage_mv, 1200); + } + + #[test] + fn run_detection_refuses_when_no_profile_matches() { + let mut backend = ScriptedProbe::new( + &[ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }], + EepromState::Absent, + ); + let request = DetectionRequest { + chain_ports: &[0], + budget: ProbeBudget::default(), + sensor: SensorTopology::Pic, + fan_zones: Vec::new(), + }; + assert_eq!( + run_detection(&mut backend, &db(), &request), + Err(DetectionFailure::NoProfile) + ); + } + + #[test] + fn run_detection_runs_degraded_with_a_dead_chain() { + let mut backend = ScriptedProbe::new( + &[ + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + ProbeOutcome::Silent, + ProbeOutcome::Silent, + ProbeOutcome::Silent, + ProbeOutcome::Silent, + ], + EepromState::Absent, + ); + let request = DetectionRequest { + chain_ports: &[0, 1, 2], + budget: ProbeBudget::default(), + sensor: SensorTopology::Pic, + fan_zones: Vec::new(), + }; + let plan = run_detection(&mut backend, &db(), &request).expect("plan"); + assert_eq!(plan.degraded_chains(126), vec![2]); + } + + #[test] + fn voltage_follows_frequency_and_clamps_outside_the_envelope() { + let envelope = Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }; + assert_eq!(envelope.voltage_for(200), 1100); + assert_eq!(envelope.voltage_for(300), 1100); + assert_eq!(envelope.voltage_for(500), 1300); + assert_eq!(envelope.voltage_for(700), 1500); + assert_eq!(envelope.voltage_for(900), 1500); + } + + #[test] + fn a_single_frequency_envelope_reports_its_floor() { + let envelope = Envelope { + v_min_mv: 1200, + v_max_mv: 1400, + f_min_mhz: 500, + f_max_mhz: 500, + }; + assert_eq!(envelope.voltage_for(500), 1200); + assert_eq!(envelope.voltage_for(600), 1400); + } +} diff --git a/src/fanmap.rs b/src/fanmap.rs new file mode 100644 index 0000000..fb2f430 --- /dev/null +++ b/src/fanmap.rs @@ -0,0 +1,469 @@ +// SPDX-License-Identifier: MIT +//! Active fan-to-thermal-zone mapping. +//! +//! Antminer chassis wire fans to zones in a way that is not reported by the hardware: a fan may +//! cool one hashboard heavily and another barely, and the front/back, top/bottom labels are +//! physical. The mapping is learned by stepping one fan at a time and watching which zone's +//! temperature responds, which is why this module takes measurements rather than configuration. + +use crate::detect::FanZone; + +/// One sensor reading taken while a fan was held at a given duty. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ZoneReading { + pub zone: u8, + pub temp_mc: i32, +} + +/// One measurement step: a fan duty and the temperatures observed during it. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ProbeSample { + pub fan: u8, + pub pwm: u8, + pub readings: Vec, +} + +/// Thresholds that decide when a response is real. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct MapThresholds { + /// Minimum cooling (millidegrees) between the low and high duty to count as a response. + pub min_drop_mc: i32, + /// Minimum margin over the next-best fan, in parts per thousand of the best response. + pub min_margin_per_mille: u16, +} + +impl Default for MapThresholds { + fn default() -> Self { + Self { + min_drop_mc: 500, + min_margin_per_mille: 250, + } + } +} + +/// The learned mapping. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct FanMap { + pub assignments: Vec, + /// Zones whose response was ambiguous and were therefore left unassigned. + pub unresolved: Vec, + /// Per assigned zone, the margin over the runner-up in parts per thousand. + pub confidence_per_mille: Vec, +} + +impl FanMap { + /// Zones a fan was confidently assigned to. + pub fn zones_for(&self, fan: u8) -> Vec { + self.assignments + .iter() + .find(|assignment| assignment.fan == fan) + .map(|assignment| assignment.zones.clone()) + .unwrap_or_default() + } +} + +/// Response per (fan, zone): positive means the zone cooled when that fan sped up. +fn responses(samples: &[ProbeSample], zones: &[u8]) -> Vec<(u8, Vec<(u8, i32)>)> { + let mut fans: Vec = samples.iter().map(|sample| sample.fan).collect(); + fans.sort_unstable(); + fans.dedup(); + let mut out = Vec::new(); + for fan in fans { + let fan_samples: Vec<&ProbeSample> = + samples.iter().filter(|sample| sample.fan == fan).collect(); + let min_pwm = fan_samples.iter().map(|sample| sample.pwm).min(); + let max_pwm = fan_samples.iter().map(|sample| sample.pwm).max(); + let (Some(low), Some(high)) = (min_pwm, max_pwm) else { + continue; + }; + if low == high { + continue; + } + let mut per_zone = Vec::with_capacity(zones.len()); + for &zone in zones { + let mean_at = |pwm: u8| -> Option { + let values: Vec = fan_samples + .iter() + .filter(|sample| sample.pwm == pwm) + .flat_map(|sample| { + sample + .readings + .iter() + .filter(|reading| reading.zone == zone) + .map(|reading| reading.temp_mc) + }) + .collect(); + if values.is_empty() { + return None; + } + let sum: i64 = values.iter().map(|value| *value as i64).sum(); + Some((sum / values.len() as i64) as i32) + }; + // Duty goes up, temperature should come down: response = warm-run minus fast-run. + if let (Some(slow_temp), Some(fast_temp)) = (mean_at(low), mean_at(high)) { + per_zone.push((zone, slow_temp - fast_temp)); + } + } + out.push((fan, per_zone)); + } + out +} + +/// Learn which fans cool which zones from a stepped measurement run. +/// +/// Every zone goes to the fan with the strongest cooling response, provided that response clears +/// `min_drop_mc` and beats the runner-up by `min_margin_per_mille`. Anything weaker stays +/// unresolved instead of being guessed, so a noisy run cannot invent a fan map. +pub fn map_fans(samples: &[ProbeSample], zones: &[u8], thresholds: MapThresholds) -> FanMap { + let responses = responses(samples, zones); + let mut map = FanMap::default(); + for &zone in zones { + let mut ranked: Vec<(i32, u8)> = responses + .iter() + .filter_map(|(fan, per_zone)| { + per_zone + .iter() + .find(|(candidate, _)| *candidate == zone) + .map(|(_, drop)| (*drop, *fan)) + }) + .collect(); + ranked.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.0)); + let Some(&(best_drop, best_fan)) = ranked.first() else { + map.unresolved.push(zone); + continue; + }; + let runner_up = ranked.get(1).map(|(drop, _)| *drop).unwrap_or(0); + let margin = best_drop - runner_up.max(0); + let margin_per_mille = if best_drop > 0 { + ((margin as i64 * 1000) / best_drop as i64) as u16 + } else { + 0 + }; + if best_drop < thresholds.min_drop_mc || margin_per_mille < thresholds.min_margin_per_mille + { + map.unresolved.push(zone); + continue; + } + match map + .assignments + .iter_mut() + .find(|assignment| assignment.fan == best_fan) + { + Some(assignment) => assignment.zones.push(zone), + None => map.assignments.push(FanZone { + fan: best_fan, + zones: vec![zone], + }), + } + map.confidence_per_mille.push(margin_per_mille); + } + map +} + +/// Safe limits for a fan-mapping sweep. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SweepConfig { + pub fans: u8, + pub zones: u8, + /// Lowest duty used during probing. Never zero: the boards must keep airflow. + pub low_pwm: u8, + pub high_pwm: u8, + /// Readings taken per (fan, duty) step; the mapper averages them. + pub repeats: u8, + /// Time to wait after a duty change before reading temperatures. + pub settle_ms: u32, +} + +impl Default for SweepConfig { + fn default() -> Self { + Self { + fans: 4, + zones: 3, + low_pwm: 40, + high_pwm: 100, + repeats: 2, + settle_ms: 20_000, + } + } +} + +/// Minimum duty a sweep may use. Airflow is never removed to make a measurement. +pub const MIN_PROBE_PWM: u8 = 20; + +/// Why a sweep did not run. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SweepError { + Backend(E), + InvalidConfig(&'static str), +} + +/// The two backend actions a sweep needs. +pub trait FanProbe { + type Error; + + fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error>; + fn read_zone(&mut self, zone: u8) -> Result; +} + +/// Step every fan between the low and high duty and record what the zones do. +/// +/// One fan is moved at a time while the others hold their previous duty, so the response belongs +/// to that fan. The run ends with every fan back at `high_pwm`: leaving a fan low after probing +/// would be a thermal hazard for whatever runs next. +pub fn sweep( + backend: &mut B, + config: &SweepConfig, + mut settle: S, +) -> Result, SweepError> { + if config.fans == 0 { + return Err(SweepError::InvalidConfig("no fans to sweep")); + } + if config.zones == 0 { + return Err(SweepError::InvalidConfig("no zones to read")); + } + if config.low_pwm < MIN_PROBE_PWM { + return Err(SweepError::InvalidConfig( + "probe duty below the safe minimum", + )); + } + if config.high_pwm > 100 { + return Err(SweepError::InvalidConfig("probe duty above 100 percent")); + } + if config.low_pwm >= config.high_pwm { + return Err(SweepError::InvalidConfig("probe duty range is empty")); + } + if config.repeats == 0 { + return Err(SweepError::InvalidConfig("no readings requested")); + } + + let mut samples = Vec::new(); + for fan in 0..config.fans { + for pwm in [config.low_pwm, config.high_pwm] { + backend.set_fan(fan, pwm).map_err(SweepError::Backend)?; + settle(config.settle_ms); + for _ in 0..config.repeats { + let mut readings = Vec::with_capacity(config.zones as usize); + for zone in 0..config.zones { + readings.push(ZoneReading { + zone, + temp_mc: backend.read_zone(zone).map_err(SweepError::Backend)?, + }); + } + samples.push(ProbeSample { fan, pwm, readings }); + } + } + } + for fan in 0..config.fans { + backend + .set_fan(fan, config.high_pwm) + .map_err(SweepError::Backend)?; + } + Ok(samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(fan: u8, pwm: u8, zone_temps: &[(u8, i32)]) -> ProbeSample { + ProbeSample { + fan, + pwm, + readings: zone_temps + .iter() + .map(|(zone, temp)| ZoneReading { + zone: *zone, + temp_mc: *temp, + }) + .collect(), + } + } + + #[test] + fn each_zone_is_assigned_to_the_fan_that_cools_it() { + let samples = vec![ + sample(0, 30, &[(0, 70_000), (1, 60_000)]), + sample(0, 100, &[(0, 50_000), (1, 59_000)]), + sample(1, 30, &[(0, 69_000), (1, 60_000)]), + sample(1, 100, &[(0, 68_000), (1, 40_000)]), + ]; + let map = map_fans(&samples, &[0, 1], MapThresholds::default()); + assert_eq!(map.zones_for(0), vec![0]); + assert_eq!(map.zones_for(1), vec![1]); + assert!(map.unresolved.is_empty()); + } + + #[test] + fn ambiguity_leaves_a_zone_unresolved() { + let samples = vec![ + sample(0, 30, &[(0, 70_000)]), + sample(0, 100, &[(0, 60_000)]), + sample(1, 30, &[(0, 70_500)]), + sample(1, 100, &[(0, 60_500)]), + ]; + let map = map_fans(&samples, &[0], MapThresholds::default()); + assert!(map.assignments.is_empty()); + assert_eq!(map.unresolved, vec![0]); + } + + #[test] + fn a_fan_that_does_not_change_temperature_is_not_assigned() { + let samples = vec![ + sample(0, 30, &[(0, 60_000)]), + sample(0, 100, &[(0, 59_900)]), + ]; + let map = map_fans(&samples, &[0], MapThresholds::default()); + assert!(map.assignments.is_empty()); + assert_eq!(map.unresolved, vec![0]); + } + + #[test] + fn a_fan_without_duty_range_is_skipped() { + let samples = vec![sample(0, 50, &[(0, 60_000)]), sample(0, 50, &[(0, 60_000)])]; + let map = map_fans(&samples, &[0], MapThresholds::default()); + assert!(map.assignments.is_empty()); + assert_eq!(map.unresolved, vec![0]); + } + + #[test] + fn one_fan_can_own_several_zones() { + let samples = vec![ + sample(0, 30, &[(0, 70_000), (1, 71_000), (2, 55_000)]), + sample(0, 100, &[(0, 55_000), (1, 56_000), (2, 54_000)]), + sample(1, 30, &[(0, 70_000), (1, 71_000), (2, 54_000)]), + sample(1, 100, &[(0, 69_000), (1, 70_000), (2, 50_000)]), + ]; + let map = map_fans(&samples, &[0, 1, 2], MapThresholds::default()); + assert_eq!(map.zones_for(0), vec![0, 1]); + assert_eq!(map.zones_for(1), vec![2]); + } + + struct ThermalMock { + duty: Vec, + owners: Vec<(u8, u8)>, + fail: bool, + } + + impl ThermalMock { + fn new(owners: &[(u8, u8)]) -> Self { + let fans = owners.iter().map(|(fan, _)| *fan).max().unwrap_or(0) + 1; + Self { + duty: vec![100; fans as usize], + owners: owners.to_vec(), + fail: false, + } + } + } + + impl FanProbe for ThermalMock { + type Error = &'static str; + + fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> { + if self.fail { + return Err("fan bus down"); + } + self.duty[fan as usize] = pwm; + Ok(()) + } + + fn read_zone(&mut self, zone: u8) -> Result { + if self.fail { + return Err("sensor bus down"); + } + let owner = self + .owners + .iter() + .find(|(_, candidate)| *candidate == zone) + .map(|(fan, _)| *fan) + .expect("zone has an owner"); + let cooled = self.duty[owner as usize] >= 100; + Ok(if cooled { 50_000 } else { 70_000 }) + } + } + + #[test] + fn sweep_then_map_resolves_each_zone() { + let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]); + let config = SweepConfig { + fans: 2, + zones: 2, + low_pwm: 40, + high_pwm: 100, + repeats: 2, + settle_ms: 0, + }; + let samples = sweep(&mut backend, &config, |_| {}).expect("sweep"); + assert_eq!(samples.len(), 2 * 2 * 2); + let map = map_fans(&samples, &[0, 1], MapThresholds::default()); + assert_eq!(map.zones_for(0), vec![0]); + assert_eq!(map.zones_for(1), vec![1]); + assert!(map.unresolved.is_empty()); + } + + #[test] + fn sweep_restores_every_fan_to_high_duty() { + let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]); + let config = SweepConfig { + fans: 2, + zones: 2, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }; + sweep(&mut backend, &config, |_| {}).expect("sweep"); + assert_eq!(backend.duty, vec![100, 100]); + } + + #[test] + fn sweep_refuses_an_unsafe_duty() { + let mut backend = ThermalMock::new(&[(0, 0)]); + let config = SweepConfig { + fans: 1, + zones: 1, + low_pwm: 10, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }; + assert_eq!( + sweep(&mut backend, &config, |_| {}), + Err(SweepError::InvalidConfig( + "probe duty below the safe minimum" + )) + ); + } + + #[test] + fn sweep_refuses_an_empty_range_and_zero_reads() { + let mut backend = ThermalMock::new(&[(0, 0)]); + let flat = SweepConfig { + fans: 1, + zones: 1, + low_pwm: 60, + high_pwm: 60, + repeats: 1, + settle_ms: 0, + }; + assert!(matches!( + sweep(&mut backend, &flat, |_| {}), + Err(SweepError::InvalidConfig(_)) + )); + let no_reads = SweepConfig { repeats: 0, ..flat }; + assert!(matches!( + sweep(&mut backend, &no_reads, |_| {}), + Err(SweepError::InvalidConfig(_)) + )); + } + + #[test] + fn sweep_propagates_backend_failures() { + let mut backend = ThermalMock::new(&[(0, 0)]); + backend.fail = true; + let config = SweepConfig::default(); + assert_eq!( + sweep(&mut backend, &config, |_| {}), + Err(SweepError::Backend("fan bus down")) + ); + } +} diff --git a/src/fanmap_store.rs b/src/fanmap_store.rs new file mode 100644 index 0000000..2fa3c19 --- /dev/null +++ b/src/fanmap_store.rs @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: MIT +//! Persisting the learned fan map. +//! +//! Mapping fans means heating and cooling the machine deliberately, so it is done once, stored, and +//! reused until the fan or sensor set changes. A stored map that does not match the current set is +//! ignored rather than trusted: silently applying a map learned on four fans to a machine with two +//! would mis-control thermals. + +use crate::detect::FanZone; +use crate::fanmap::{map_fans, sweep, FanMap, FanProbe, MapThresholds, SweepConfig, SweepError}; +use serde_json::{json, Value}; +use std::fs; +use std::io; +use std::path::Path; + +/// A stored map together with the hardware it was learned on. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct StoredMap { + pub fans: u8, + pub zones: u8, + pub assignments: Vec, + pub unresolved: Vec, +} + +impl StoredMap { + pub fn from_map(map: &FanMap, fans: u8, zones: u8) -> Self { + Self { + fans, + zones, + assignments: map.assignments.clone(), + unresolved: map.unresolved.clone(), + } + } + + pub fn to_map(&self) -> FanMap { + FanMap { + assignments: self.assignments.clone(), + unresolved: self.unresolved.clone(), + confidence_per_mille: vec![0; self.assignments.len()], + } + } + + /// True when this map was learned on the same fan and zone counts. + pub fn matches(&self, fans: u8, zones: u8) -> bool { + self.fans == fans && self.zones == zones + } + + pub fn to_json(&self) -> String { + json!({ + "schema": 1, + "fans": self.fans, + "zones": self.zones, + "assignments": self.assignments.iter().map(|zone| json!({ + "fan": zone.fan, + "zones": zone.zones, + })).collect::>(), + "unresolved": self.unresolved, + }) + .to_string() + } + + pub fn from_json(text: &str) -> Option { + let root: Value = serde_json::from_str(text).ok()?; + if root.get("schema")?.as_u64()? != 1 { + return None; + } + let fans = u8::try_from(root.get("fans")?.as_u64()?).ok()?; + let zones = u8::try_from(root.get("zones")?.as_u64()?).ok()?; + let assignments = root + .get("assignments")? + .as_array()? + .iter() + .map(|entry| { + Some(FanZone { + fan: u8::try_from(entry.get("fan")?.as_u64()?).ok()?, + zones: entry + .get("zones")? + .as_array()? + .iter() + .map(|zone| u8::try_from(zone.as_u64()?).ok()) + .collect::>>()?, + }) + }) + .collect::>>()?; + let unresolved = root + .get("unresolved")? + .as_array()? + .iter() + .map(|zone| u8::try_from(zone.as_u64()?).ok()) + .collect::>>()?; + Some(Self { + fans, + zones, + assignments, + unresolved, + }) + } +} + +/// Why mapping did not produce a stored map. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum StoreError { + Sweep(SweepError), + Io(&'static str), +} + +/// Read a stored map, if one exists and parses. +pub fn load(path: &Path) -> Option { + let text = fs::read_to_string(path).ok()?; + StoredMap::from_json(&text) +} + +/// Write a map, creating the parent directory when needed. +pub fn save(path: &Path, stored: &StoredMap) -> io::Result<()> { + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() { + fs::create_dir_all(parent)?; + } + } + fs::write(path, stored.to_json()) +} + +/// Return the stored map when it matches this machine, otherwise sweep, map, and store the result. +pub fn ensure_map( + backend: &mut B, + config: &SweepConfig, + thresholds: MapThresholds, + path: &Path, + settle: S, +) -> Result> { + if let Some(stored) = load(path) { + if stored.matches(config.fans, config.zones) { + return Ok(stored.to_map()); + } + } + let zones: Vec = (0..config.zones).collect(); + let samples = sweep(backend, config, settle).map_err(StoreError::Sweep)?; + let map = map_fans(&samples, &zones, thresholds); + let stored = StoredMap::from_map(&map, config.fans, config.zones); + save(path, &stored).map_err(|_| StoreError::Io("cannot write the fan map"))?; + Ok(map) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fanmap::{ProbeSample, ZoneReading}; + + struct CountingBackend { + duty: Vec, + owners: Vec<(u8, u8)>, + calls: usize, + } + + impl FanProbe for CountingBackend { + type Error = (); + + fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), ()> { + self.calls += 1; + self.duty[fan as usize] = pwm; + Ok(()) + } + + fn read_zone(&mut self, zone: u8) -> Result { + // Zones without an explicit owner follow fan 0, which keeps the mock usable when a + // test asks for more zones than the fixture declares. + let owner = self + .owners + .iter() + .find(|(_, candidate)| *candidate == zone) + .map(|(fan, _)| *fan) + .unwrap_or(0); + Ok(if self.duty[owner as usize] >= 100 { + 50_000 + } else { + 70_000 + }) + } + } + + fn backend() -> CountingBackend { + CountingBackend { + duty: vec![100, 100], + owners: vec![(0, 0), (1, 1)], + calls: 0, + } + } + + fn config(zones: u8) -> SweepConfig { + SweepConfig { + fans: 2, + zones, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + } + } + + fn path(name: &str) -> std::path::PathBuf { + let mut dir = std::env::temp_dir(); + dir.push(format!("alkane-fanmap-{}-{name}.json", std::process::id())); + dir + } + + #[test] + fn a_stored_map_round_trips() { + let map = FanMap { + assignments: vec![FanZone { + fan: 0, + zones: vec![0, 1], + }], + unresolved: vec![2], + confidence_per_mille: vec![900], + }; + let stored = StoredMap::from_map(&map, 4, 3); + let text = stored.to_json(); + assert_eq!(StoredMap::from_json(&text).expect("parse"), stored); + let back = stored.to_map(); + assert_eq!(back.assignments, map.assignments); + assert_eq!(back.unresolved, map.unresolved); + } + + #[test] + fn corrupt_or_foreign_json_is_ignored() { + assert!(StoredMap::from_json("not json").is_none()); + assert!(StoredMap::from_json(r#"{"schema":2}"#).is_none()); + assert!(StoredMap::from_json(r#"{"schema":1,"fans":2}"#).is_none()); + } + + #[test] + fn a_matching_map_is_reused_without_sweeping() { + let file = path("reuse"); + let first = ensure_map( + &mut backend(), + &config(2), + MapThresholds::default(), + &file, + |_| {}, + ) + .expect("first"); + assert_eq!(first.zones_for(0), vec![0]); + let mut reuse = backend(); + let second = ensure_map( + &mut reuse, + &config(2), + MapThresholds::default(), + &file, + |_| {}, + ) + .expect("second"); + assert_eq!(second.zones_for(0), vec![0]); + assert_eq!(reuse.calls, 0, "a stored map must not cause another sweep"); + let _ = std::fs::remove_file(&file); + } + + #[test] + fn a_changed_sensor_set_forces_a_new_sweep() { + let file = path("changed"); + ensure_map( + &mut backend(), + &config(2), + MapThresholds::default(), + &file, + |_| {}, + ) + .expect("first"); + let mut fresh = backend(); + let map = ensure_map( + &mut fresh, + &config(2), + MapThresholds::default(), + &file, + |_| {}, + ) + .expect("second"); + assert_eq!(map.zones_for(1), vec![1]); + // The stored file describes two zones; asking for three must not reuse it. + let mut three = CountingBackend { + duty: vec![100, 100], + owners: vec![(0, 0), (1, 1)], + calls: 0, + }; + let _ = ensure_map( + &mut three, + &config(3), + MapThresholds::default(), + &file, + |_| {}, + ); + assert!(three.calls > 0); + let _ = std::fs::remove_file(&file); + } + + #[test] + fn samples_from_a_sweep_still_map_correctly() { + let samples = vec![ + ProbeSample { + fan: 0, + pwm: 40, + readings: vec![ZoneReading { + zone: 0, + temp_mc: 70_000, + }], + }, + ProbeSample { + fan: 0, + pwm: 100, + readings: vec![ZoneReading { + zone: 0, + temp_mc: 50_000, + }], + }, + ]; + let map = map_fans(&samples, &[0], MapThresholds::default()); + assert_eq!(map.zones_for(0), vec![0]); + } +} diff --git a/src/fault.rs b/src/fault.rs new file mode 100644 index 0000000..503ea82 --- /dev/null +++ b/src/fault.rs @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: MIT +//! Fault-tolerance supervisor. +//! +//! The goal is to keep hashing with as many dead chips or chains as possible. Faults therefore +//! escalate in steps (retry, disable chip, disable chain) and only irreversible conditions stop the +//! machine. This module owns that ladder; it does not talk to hardware and it does not choose +//! thermal limits, which come from the profile envelope. + +/// A single health observation from the mining loop. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum FaultEvent { + /// A chain accepted work and reported nonces for it. + NoncesReported { chain: u8, per_mille: u16 }, + /// A chain returned an error for a frame, reset or work dispatch. + ChainError { chain: u8 }, + /// A chain produced nothing for a full observation window. + ChainSilent { chain: u8 }, + /// One chip on a chain failed its identification or stopped responding. + ChipFault { chain: u8, chip: u16 }, + /// A temperature reading left the profile envelope. + TemperatureFault { zone: u8 }, +} + +/// What the caller should do next. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum FaultAction { + /// Keep hashing; nothing changed. + None, + /// Retry the chain before treating the fault as permanent. + Retry { chain: u8 }, + /// Keep the machine running without this chain. + DisableChain { chain: u8 }, + /// Keep the machine running without this chip. + DisableChip { chain: u8, chip: u16 }, + /// Stop hashing entirely; the reason is carried for the API. + Stop { reason: StopReason }, +} + +/// Why the machine stopped. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum StopReason { + Temperature, + NoChainsLeft, +} + +/// Thresholds for escalation. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct FaultPolicy { + /// Consecutive errors tolerated before the chain is disabled (retries included). + pub retries: u8, + /// Nonce-response ratio below which a chain is considered stalled. + pub min_response_per_mille: u16, + /// Consecutive weak windows before a stalled chain is disabled. + pub weak_windows: u8, +} + +impl Default for FaultPolicy { + fn default() -> Self { + Self { + retries: 2, + min_response_per_mille: 100, + weak_windows: 3, + } + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct ChainHealth { + chain: u8, + errors: u8, + weak: u8, + disabled: bool, +} + +/// Escalation state for one machine. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FaultSupervisor { + policy: FaultPolicy, + chains: Vec, + stopped: Option, +} + +impl FaultSupervisor { + pub fn new(chains: &[u8], policy: FaultPolicy) -> Self { + Self { + policy, + chains: chains + .iter() + .map(|&chain| ChainHealth { + chain, + ..ChainHealth::default() + }) + .collect(), + stopped: None, + } + } + + pub fn is_stopped(&self) -> bool { + self.stopped.is_some() + } + + pub fn stop_reason(&self) -> Option { + self.stopped + } + + /// Chains the miner may still dispatch work to. + pub fn active_chains(&self) -> Vec { + self.chains + .iter() + .filter(|health| !health.disabled) + .map(|health| health.chain) + .collect() + } + + /// Apply one observation and return the escalation step it implies. + pub fn observe(&mut self, event: FaultEvent) -> FaultAction { + if self.stopped.is_some() { + return FaultAction::None; + } + match event { + FaultEvent::NoncesReported { chain, per_mille } => { + let min_response = self.policy.min_response_per_mille; + let weak_windows = self.policy.weak_windows; + let Some(health) = self.health_mut(chain) else { + return FaultAction::None; + }; + health.errors = 0; + if per_mille >= min_response { + health.weak = 0; + return FaultAction::None; + } + health.weak = health.weak.saturating_add(1); + if health.weak >= weak_windows { + health.disabled = true; + self.maybe_stop(chain) + } else { + FaultAction::None + } + } + FaultEvent::ChainError { chain } | FaultEvent::ChainSilent { chain } => { + let policy = self.policy; + let Some(health) = self.health_mut(chain) else { + return FaultAction::None; + }; + if health.disabled { + return FaultAction::None; + } + health.errors = health.errors.saturating_add(1); + if health.errors > policy.retries { + health.disabled = true; + self.maybe_stop(chain) + } else { + FaultAction::Retry { chain } + } + } + FaultEvent::ChipFault { chain, chip } => FaultAction::DisableChip { chain, chip }, + FaultEvent::TemperatureFault { .. } => { + self.stopped = Some(StopReason::Temperature); + FaultAction::Stop { + reason: StopReason::Temperature, + } + } + } + } + + fn health_mut(&mut self, chain: u8) -> Option<&mut ChainHealth> { + self.chains.iter_mut().find(|health| health.chain == chain) + } + + fn maybe_stop(&mut self, chain: u8) -> FaultAction { + if self.chains.iter().all(|health| health.disabled) { + self.stopped = Some(StopReason::NoChainsLeft); + return FaultAction::Stop { + reason: StopReason::NoChainsLeft, + }; + } + FaultAction::DisableChain { chain } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn supervisor() -> FaultSupervisor { + FaultSupervisor::new(&[0, 1, 2], FaultPolicy::default()) + } + + #[test] + fn transient_errors_retry_then_disable_the_chain() { + let mut faults = supervisor(); + assert_eq!( + faults.observe(FaultEvent::ChainError { chain: 1 }), + FaultAction::Retry { chain: 1 } + ); + assert_eq!( + faults.observe(FaultEvent::ChainError { chain: 1 }), + FaultAction::Retry { chain: 1 } + ); + assert_eq!( + faults.observe(FaultEvent::ChainSilent { chain: 1 }), + FaultAction::DisableChain { chain: 1 } + ); + assert_eq!(faults.active_chains(), vec![0, 2]); + } + + #[test] + fn healthy_nonces_reset_the_error_count() { + let mut faults = supervisor(); + faults.observe(FaultEvent::ChainError { chain: 0 }); + faults.observe(FaultEvent::ChainError { chain: 0 }); + assert_eq!( + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 900 + }), + FaultAction::None + ); + assert_eq!( + faults.observe(FaultEvent::ChainError { chain: 0 }), + FaultAction::Retry { chain: 0 } + ); + } + + #[test] + fn a_stalled_chain_is_disabled_after_repeated_weak_windows() { + let mut faults = supervisor(); + for _ in 0..2 { + assert_eq!( + faults.observe(FaultEvent::NoncesReported { + chain: 2, + per_mille: 10 + }), + FaultAction::None + ); + } + assert_eq!( + faults.observe(FaultEvent::NoncesReported { + chain: 2, + per_mille: 10 + }), + FaultAction::DisableChain { chain: 2 } + ); + assert_eq!(faults.active_chains(), vec![0, 1]); + } + + #[test] + fn one_good_window_clears_weak_history() { + let mut faults = supervisor(); + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 10, + }); + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 10, + }); + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 900, + }); + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 10, + }); + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 10, + }); + assert_eq!( + faults.observe(FaultEvent::NoncesReported { + chain: 0, + per_mille: 10 + }), + FaultAction::DisableChain { chain: 0 } + ); + } + + #[test] + fn a_chip_fault_disables_only_that_chip() { + let mut faults = supervisor(); + assert_eq!( + faults.observe(FaultEvent::ChipFault { chain: 1, chip: 42 }), + FaultAction::DisableChip { chain: 1, chip: 42 } + ); + assert_eq!(faults.active_chains(), vec![0, 1, 2]); + } + + #[test] + fn temperature_fault_stops_the_machine() { + let mut faults = supervisor(); + assert_eq!( + faults.observe(FaultEvent::TemperatureFault { zone: 2 }), + FaultAction::Stop { + reason: StopReason::Temperature + } + ); + assert!(faults.is_stopped()); + assert_eq!( + faults.observe(FaultEvent::ChainError { chain: 0 }), + FaultAction::None + ); + } + + #[test] + fn losing_every_chain_stops_instead_of_hanging() { + let mut faults = FaultSupervisor::new( + &[0], + FaultPolicy { + retries: 0, + ..FaultPolicy::default() + }, + ); + assert_eq!( + faults.observe(FaultEvent::ChainError { chain: 0 }), + FaultAction::Stop { + reason: StopReason::NoChainsLeft + } + ); + assert_eq!(faults.active_chains(), Vec::::new()); + } + + #[test] + fn unknown_chains_are_ignored() { + let mut faults = supervisor(); + assert_eq!( + faults.observe(FaultEvent::ChainError { chain: 9 }), + FaultAction::None + ); + assert_eq!(faults.active_chains(), vec![0, 1, 2]); + } +} diff --git a/src/hal_conformance.rs b/src/hal_conformance.rs new file mode 100644 index 0000000..4ec6adc --- /dev/null +++ b/src/hal_conformance.rs @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: MIT +//! HAL conformance checks. +//! +//! A family backend is only useful if it answers the contract the OS expects. This module walks the +//! contract in order and reports each check separately, so a backend author sees exactly which +//! opcode is missing or wrong instead of a single opaque failure. +//! +//! Every check uses a fresh connection: a backend that desynchronises one exchange must not make +//! the following checks meaningless. + +use crate::hal_wire::{HalClient, CAP_CHAIN_PROBE, CAP_FREQUENCY, CAP_POWER, CAP_PSU_IDENTITY}; +use crate::HardwareBackend; +use std::path::Path; + +/// One check and its outcome. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Check { + pub name: &'static str, + pub passed: bool, + pub detail: String, +} + +impl Check { + fn pass(name: &'static str, detail: impl Into) -> Self { + Self { + name, + passed: true, + detail: detail.into(), + } + } + + fn fail(name: &'static str, detail: impl Into) -> Self { + Self { + name, + passed: false, + detail: detail.into(), + } + } +} + +/// Run the contract checks against a backend socket. +pub fn run(socket: &Path) -> Vec { + vec![ + check_capabilities(socket), + check_probe(socket), + check_eeprom(socket), + check_psu(socket), + check_frequency_and_temperature(socket), + check_power(socket), + check_fan(socket), + ] +} + +fn connect(socket: &Path) -> Result { + HalClient::connect(socket).map_err(|error| format!("{error:?}")) +} + +fn check_capabilities(socket: &Path) -> Check { + const NAME: &str = "capabilities"; + match connect(socket) + .and_then(|mut client| client.capabilities().map_err(|error| format!("{error:?}"))) + { + Ok(mask) if mask & CAP_CHAIN_PROBE == 0 => { + Check::fail(NAME, format!("mask {mask:#x} lacks chain probing")) + } + Ok(mask) => Check::pass(NAME, format!("mask {mask:#x}")), + Err(error) => Check::fail(NAME, error), + } +} + +fn check_probe(socket: &Path) -> Check { + const NAME: &str = "probe chain 0"; + match connect(socket) { + Ok(mut client) => match client.probe_chain(0, 0) { + Ok(outcome) => Check::pass(NAME, format!("{outcome:?}")), + Err(error) => Check::fail(NAME, format!("{error:?}")), + }, + Err(error) => Check::fail(NAME, error), + } +} + +fn check_eeprom(socket: &Path) -> Check { + const NAME: &str = "read EEPROM chain 0"; + match connect(socket) { + Ok(mut client) => match client.read_eeprom(0) { + Ok(state) => Check::pass(NAME, format!("{state:?}")), + Err(error) => Check::fail(NAME, format!("{error:?}")), + }, + Err(error) => Check::fail(NAME, error), + } +} + +fn check_psu(socket: &Path) -> Check { + const NAME: &str = "identify PSU"; + match connect(socket) { + Ok(mut client) => match client.capabilities() { + Ok(mask) if mask & CAP_PSU_IDENTITY == 0 => { + Check::fail(NAME, "backend does not advertise PSU identity") + } + Ok(_) => match client.identify_psu() { + Ok(psu) if psu.envelope.v_min_mv <= psu.envelope.v_max_mv => { + Check::pass(NAME, format!("{} {} mV", psu.name, psu.envelope.v_max_mv)) + } + Ok(psu) => Check::fail(NAME, format!("inverted envelope from {}", psu.name)), + Err(error) => Check::fail(NAME, format!("{error:?}")), + }, + Err(error) => Check::fail(NAME, format!("{error:?}")), + }, + Err(error) => Check::fail(NAME, error), + } +} + +fn check_frequency_and_temperature(socket: &Path) -> Check { + const NAME: &str = "frequency and temperature"; + match connect(socket) { + Ok(mut client) => { + let caps = match client.capabilities() { + Ok(mask) => mask, + Err(error) => return Check::fail(NAME, format!("{error:?}")), + }; + if caps & CAP_FREQUENCY == 0 { + return Check::fail(NAME, "backend does not advertise frequency control"); + } + if let Err(error) = client.set_chain_frequency(0, 500) { + return Check::fail(NAME, format!("set frequency: {error:?}")); + } + match client.read_temperature_mc(0) { + Ok(value) if (-40_000..=150_000).contains(&value) => { + Check::pass(NAME, format!("500 MHz, {} mC", value)) + } + Ok(value) => Check::fail(NAME, format!("implausible temperature {value} mC")), + Err(error) => Check::fail(NAME, format!("read temperature: {error:?}")), + } + } + Err(error) => Check::fail(NAME, error), + } +} + +fn check_power(socket: &Path) -> Check { + const NAME: &str = "read power"; + match connect(socket) { + Ok(mut client) => match client.capabilities() { + Ok(mask) if mask & CAP_POWER == 0 => { + Check::fail(NAME, "backend does not advertise power telemetry") + } + Ok(_) => { + // Ask for a known operating point first: a backend that always reports 0 W would + // otherwise pass a range check while being useless to a power-target loop. + if let Err(error) = client.set_chain_frequency(0, 500) { + return Check::fail(NAME, format!("set frequency: {error:?}")); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + match client.read_power_w() { + Ok(0) => Check::fail(NAME, "reports 0 W at 500 MHz"), + Ok(watts) if watts <= 10_000 => { + Check::pass(NAME, format!("{watts} W at 500 MHz")) + } + Ok(watts) => Check::fail(NAME, format!("implausible power {watts} W")), + Err(error) => Check::fail(NAME, format!("{error:?}")), + } + } + Err(error) => Check::fail(NAME, format!("{error:?}")), + }, + Err(error) => Check::fail(NAME, error), + } +} + +fn check_fan(socket: &Path) -> Check { + const NAME: &str = "fan target"; + match connect(socket) { + Ok(mut client) => match client.set_fan_target(0, 100) { + Ok(()) => Check::pass(NAME, "100 percent accepted"), + Err(error) => Check::fail(NAME, format!("{error:?}")), + }, + Err(error) => Check::fail(NAME, error), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hal_sim::{serve, SimConfig}; + + fn socket(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("alkane-conf-{}-{name}.sock", std::process::id())) + } + + #[test] + fn the_reference_server_passes_every_check() { + let path = socket("ok"); + let server_path = path.clone(); + let server = std::thread::spawn(move || { + let _ = serve(&server_path, SimConfig::default()); + }); + // The reference server binds inside serve(); wait for the socket to exist. + for _ in 0..100 { + if path.exists() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let checks = run(&path); + let failed: Vec<&Check> = checks.iter().filter(|check| !check.passed).collect(); + assert!(failed.is_empty(), "reference server failed: {failed:?}"); + assert_eq!(checks.len(), 7); + let _ = std::fs::remove_file(&path); + // The server thread is left to exit when the socket disappears. + drop(server); + } + + #[test] + fn an_unreachable_socket_fails_every_check() { + let path = socket("missing"); + let checks = run(&path); + assert_eq!(checks.len(), 7); + assert!(checks.iter().all(|check| !check.passed)); + } +} diff --git a/src/hal_sim.rs b/src/hal_sim.rs new file mode 100644 index 0000000..266b1a6 --- /dev/null +++ b/src/hal_sim.rs @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: MIT +//! Reference HAL server. +//! +//! Speaks the same ALKH contract a family backend serves on a real board, but answers from a fixed +//! description of a machine. Two uses: it lets the whole OS path run on any development machine, and +//! it shows a backend author exactly what each opcode must return. + +use std::io::{self, Read, Write}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::Path; + +const MAGIC: [u8; 4] = *b"ALKH"; +const VERSION: u8 = 1; +const RESPONSE: u16 = 1; +const HEADER_LEN: usize = 16; + +const SEND_FRAME: u8 = 1; +const RECEIVE_FRAME: u8 = 2; +const SET_CHAIN_RESET: u8 = 3; +const SET_FAN_TARGET: u8 = 4; +const READ_TEMPERATURE: u8 = 5; +const SET_PSU_ENABLED: u8 = 6; +const CAPABILITIES: u8 = 7; +const PROBE_CHAIN: u8 = 8; +const READ_EEPROM: u8 = 9; +const IDENTIFY_PSU: u8 = 10; +const SET_CHAIN_FREQUENCY: u8 = 11; +const READ_POWER: u8 = 12; + +const CAP_ALL: u32 = (1 << 5) - 1; + +/// What the simulated machine looks like. +#[derive(Clone, Debug)] +pub struct SimConfig { + /// Chains that identify. Chains beyond this answer silent. + pub chains: u8, + /// Chips reported per chain. + pub chips: u16, + /// Chip identifier on the wire (1 = bm1362). + pub chip: u8, + /// Report a working EEPROM instead of an absent one. + pub eeprom: bool, + /// PSU name and envelope, or `None` to fail identification. + pub psu: Option<(String, u16, u16, u16, u16, u16)>, + /// Fans on the simulated chassis; zones are distributed over them. + pub fans: u8, +} + +impl Default for SimConfig { + fn default() -> Self { + Self { + chains: 3, + chips: 126, + chip: 1, + eeprom: false, + psu: Some(("APW12".into(), 1200, 1600, 0, 1000, 3600)), + fans: 2, + } + } +} + +struct State { + config: SimConfig, + frequency_mhz: u16, + /// Duty per fan, so a zone can respond to the fan that actually cools it. + fan_pwm: [u8; 4], +} + +impl State { + /// Which fan cools a zone. Zones are distributed over the fans round-robin. + fn owner(&self, zone: u8) -> usize { + let fans = usize::from(self.config.fans.max(1)); + usize::from(zone) % fans + } +} + +/// Serve one socket path until the program exits. +pub fn serve(path: &Path, config: SimConfig) -> io::Result<()> { + let _ = std::fs::remove_file(path); + let listener = UnixListener::bind(path)?; + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let mut state = State { + config: config.clone(), + frequency_mhz: 0, + fan_pwm: [100; 4], + }; + let _ = serve_connection(stream, &mut state); + } + Ok(()) +} + +fn serve_connection(mut stream: UnixStream, state: &mut State) -> io::Result<()> { + loop { + let mut header = [0_u8; HEADER_LEN]; + if stream.read_exact(&mut header).is_err() { + return Ok(()); + } + if header[..4] != MAGIC { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad HAL magic")); + } + let opcode = header[5]; + let sequence = header[8..12].to_vec(); + let length = u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize; + let mut payload = vec![0_u8; length]; + if length > 0 && stream.read_exact(&mut payload).is_err() { + return Ok(()); + } + let body = respond(opcode, &payload, state); + let mut out = [0_u8; HEADER_LEN]; + out[..4].copy_from_slice(&MAGIC); + out[4] = VERSION; + out[5] = opcode; + out[6..8].copy_from_slice(&RESPONSE.to_le_bytes()); + out[8..12].copy_from_slice(&sequence); + out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes()); + stream.write_all(&out)?; + stream.write_all(&body)?; + stream.flush()?; + } +} + +fn respond(opcode: u8, payload: &[u8], state: &mut State) -> Vec { + match opcode { + CAPABILITIES => { + let mut body = vec![0_u8]; + body.extend_from_slice(&CAP_ALL.to_le_bytes()); + body + } + PROBE_CHAIN => { + let chain = payload.first().copied().unwrap_or(0); + if chain >= state.config.chains { + return vec![0, 1, 0, 0, 0]; // silent + } + let chips = state.config.chips.to_le_bytes(); + vec![0, 0, state.config.chip, chips[0], chips[1]] + } + READ_EEPROM => { + if state.config.eeprom { + let mut body = vec![0_u8, 0]; + body.extend_from_slice(b"BHB42601"); + body + } else { + vec![0, 1] + } + } + IDENTIFY_PSU => match &state.config.psu { + Some((name, v_min, v_max, f_min, f_max, watts)) => { + let mut body = vec![0_u8, name.len() as u8]; + body.extend_from_slice(name.as_bytes()); + for word in [*v_min, *v_max, *f_min, *f_max, *watts] { + body.extend_from_slice(&word.to_le_bytes()); + } + body + } + None => vec![1], + }, + SET_CHAIN_FREQUENCY => { + if let Some(mhz) = payload.get(1..3) { + state.frequency_mhz = u16::from_le_bytes([mhz[0], mhz[1]]); + } + vec![0] + } + SET_FAN_TARGET => { + let fan = usize::from(payload.first().copied().unwrap_or(0)).min(3); + state.fan_pwm[fan] = payload.get(1).copied().unwrap_or(0); + vec![0] + } + READ_TEMPERATURE => { + // Temperature rises with frequency so the tuner has something to regulate, and falls + // when the fan that owns the zone is fast so the fan sweep can learn the mapping. + let zone = payload.first().copied().unwrap_or(0); + let rise = i32::from(state.frequency_mhz) * 20; + let airflow = if state.fan_pwm[state.owner(zone)] >= 100 { + 0 + } else { + 20_000 + }; + let mut body = vec![0_u8]; + body.extend_from_slice(&(45_000 + rise + airflow).to_le_bytes()); + body + } + READ_POWER => { + // Four watts per MHz, so a power target has something to regulate. + let watts = u16::try_from(u32::from(state.frequency_mhz) * 4).unwrap_or(u16::MAX); + let mut body = vec![0_u8]; + body.extend_from_slice(&watts.to_le_bytes()); + body + } + SET_CHAIN_RESET | SET_PSU_ENABLED => vec![0], + SEND_FRAME => vec![0], + RECEIVE_FRAME => { + // No nonce traffic in the reference backend. + let count: u16 = 0; + let mut body = vec![0_u8]; + body.extend_from_slice(&count.to_le_bytes()); + body + } + _ => vec![1], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fanmap::FanProbe; + use crate::hal_wire::HalClient; + use crate::HardwareBackend; + + #[test] + fn a_client_can_detect_against_the_reference_server() { + let path = std::env::temp_dir().join(format!("alkane-sim-hal-{}.sock", std::process::id())); + // Bind before spawning so the client cannot race the socket into existence. + let listener = UnixListener::bind(&path).expect("bind"); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().expect("accept"); + let mut state = State { + config: SimConfig::default(), + frequency_mhz: 0, + fan_pwm: [100; 4], + }; + let _ = serve_connection(stream, &mut state); + }); + let mut client = HalClient::connect(&path).expect("connect"); + assert_eq!(client.capabilities().expect("caps"), CAP_ALL); + match client.probe_chain(0, 0).expect("probe") { + crate::detect::ProbeOutcome::Identified { chip, chips } => { + assert_eq!(chip, crate::detect::ChipModel::Bm1362); + assert_eq!(chips, 126); + } + other => panic!("unexpected probe: {other:?}"), + } + assert_eq!( + client.read_eeprom(0).expect("eeprom"), + crate::detect::EepromState::Absent + ); + let psu = client.identify_psu().expect("psu"); + assert_eq!(psu.name, "APW12"); + client.set_chain_frequency(0, 512).expect("freq"); + assert_eq!(client.read_power_w().expect("power"), 512 * 4); + // Zone 1 is owned by fan 1: slowing fan 1 must heat zone 1 and not zone 0. + let baseline_0 = client.read_temperature_mc(0).expect("temp"); + let baseline_1 = client.read_temperature_mc(1).expect("temp"); + client.set_fan(1, 40).expect("fan"); + assert_eq!(client.read_temperature_mc(0).expect("temp"), baseline_0); + assert!(client.read_temperature_mc(1).expect("temp") > baseline_1); + assert_eq!( + client.read_temperature_mc(0).expect("temp"), + 45_000 + 512 * 20 + ); + drop(client); + let _ = std::fs::remove_file(&path); + server.join().expect("server"); + } +} diff --git a/src/hal_wire.rs b/src/hal_wire.rs index 5a55346..914ae8a 100644 --- a/src/hal_wire.rs +++ b/src/hal_wire.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: MIT //! Versioned local wire contract between Alkane OS and an SDK hardware backend. +use crate::detect::{ + ChipModel, DetectionBackend, EepromState, Envelope, ProbeOutcome, PsuCapability, +}; use crate::HardwareBackend; use std::fmt; use std::io::{self, Read, Write}; @@ -24,6 +27,27 @@ const SET_CHAIN_RESET: u8 = 3; const SET_FAN_TARGET: u8 = 4; const READ_TEMPERATURE: u8 = 5; const SET_PSU_ENABLED: u8 = 6; +const CAPABILITIES: u8 = 7; +const PROBE_CHAIN: u8 = 8; +const READ_EEPROM: u8 = 9; +const IDENTIFY_PSU: u8 = 10; +const SET_CHAIN_FREQUENCY: u8 = 11; +const READ_POWER: u8 = 12; + +/// Backend feature bits reported by `CAPABILITIES`. +pub const CAP_CHAIN_PROBE: u32 = 1 << 0; +pub const CAP_EEPROM: u32 = 1 << 1; +pub const CAP_PSU_IDENTITY: u32 = 1 << 2; +pub const CAP_FREQUENCY: u32 = 1 << 3; +pub const CAP_POWER: u32 = 1 << 4; + +const PROBE_IDENTIFIED: u8 = 0; +const PROBE_SILENT: u8 = 1; +const PROBE_GARBLED: u8 = 2; + +const EEPROM_PRESENT: u8 = 0; +const EEPROM_ABSENT: u8 = 1; +const EEPROM_INVALID: u8 = 2; #[cfg(not(target_os = "linux"))] compile_error!("Alkane HAL sockets require Linux"); @@ -337,6 +361,156 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result { Ok(stream) } +impl HalClient { + /// Feature mask advertised by the backend. Old backends reject the opcode, which surfaces as + /// a protocol error rather than a silent zero. + pub fn capabilities(&mut self) -> Result { + let body = self.exchange(CAPABILITIES, &[])?; + let bytes: [u8; 4] = body + .try_into() + .map_err(|_| HalError::Protocol("invalid capability response"))?; + Ok(u32::from_le_bytes(bytes)) + } + + fn require(&mut self, capability: u32) -> Result<(), HalError> { + if self.capabilities()? & capability == 0 { + return Err(HalError::Protocol("backend lacks a detection capability")); + } + Ok(()) + } + + pub fn probe_chain(&mut self, chain: u8, attempt: u8) -> Result { + self.require(CAP_CHAIN_PROBE)?; + let body = self.exchange(PROBE_CHAIN, &[chain, attempt])?; + if body.len() != 4 { + self.poison(); + return Err(HalError::Protocol("invalid probe response")); + } + let chips = u16::from_le_bytes([body[2], body[3]]); + match body[0] { + PROBE_IDENTIFIED => match chip_from_wire(body[1]) { + Some(chip) => Ok(ProbeOutcome::Identified { chip, chips }), + None => { + self.poison(); + Err(HalError::Protocol("unknown chip identifier")) + } + }, + PROBE_SILENT => Ok(ProbeOutcome::Silent), + PROBE_GARBLED => Ok(ProbeOutcome::Garbled), + _ => { + self.poison(); + Err(HalError::Protocol("invalid probe outcome")) + } + } + } + + pub fn read_eeprom(&mut self, chain: u8) -> Result { + self.require(CAP_EEPROM)?; + let body = self.exchange(READ_EEPROM, &[chain])?; + match body.first().copied() { + Some(EEPROM_ABSENT) if body.len() == 1 => Ok(EepromState::Absent), + Some(EEPROM_INVALID) if body.len() == 1 => Ok(EepromState::Invalid), + Some(EEPROM_PRESENT) if body.len() > 1 => { + let model = std::str::from_utf8(&body[1..]) + .map_err(|_| HalError::Protocol("invalid EEPROM model text"))?; + Ok(EepromState::Present { + model: model.to_owned(), + }) + } + _ => { + self.poison(); + Err(HalError::Protocol("invalid EEPROM response")) + } + } + } + + /// Apply a chain frequency in MHz. The backend owns the PLL write; the OS owns the decision. + pub fn set_chain_frequency(&mut self, chain: u8, mhz: u16) -> Result<(), HalError> { + self.require(CAP_FREQUENCY)?; + let mut payload = [0_u8; 3]; + payload[0] = chain; + payload[1..].copy_from_slice(&mhz.to_le_bytes()); + self.empty_reply(SET_CHAIN_FREQUENCY, &payload) + } + + /// Measured DC input power in watts, when the board can read its PSU. + pub fn read_power_w(&mut self) -> Result { + 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 { + self.require(CAP_PSU_IDENTITY)?; + let body = self.exchange(IDENTIFY_PSU, &[])?; + let name_len = *body + .first() + .ok_or(HalError::Protocol("empty PSU response"))? as usize; + if body.len() != name_len + 1 + 10 { + self.poison(); + return Err(HalError::Protocol("invalid PSU response")); + } + let name = std::str::from_utf8(&body[1..1 + name_len]) + .map_err(|_| HalError::Protocol("invalid PSU name"))? + .to_owned(); + let at = 1 + name_len; + let word = |offset: usize| u16::from_le_bytes([body[at + offset], body[at + offset + 1]]); + Ok(PsuCapability { + name, + envelope: Envelope { + v_min_mv: word(0), + v_max_mv: word(2), + f_min_mhz: word(4), + f_max_mhz: word(6), + }, + max_dc_watts: word(8), + }) + } +} + +impl DetectionBackend for HalClient { + type Error = HalError; + + fn probe(&mut self, chain: u8, attempt: u8) -> Result { + self.probe_chain(chain, attempt) + } + + fn eeprom(&mut self, chain: u8) -> Result { + self.read_eeprom(chain) + } + + fn identify_psu(&mut self) -> Result, Self::Error> { + self.identify_psu().map(Some) + } +} + +impl crate::fanmap::FanProbe for HalClient { + type Error = HalError; + + fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> { + self.set_fan_target(fan, pwm) + } + + fn read_zone(&mut self, zone: u8) -> Result { + self.read_temperature_mc(zone) + } +} + +fn chip_from_wire(value: u8) -> Option { + match value { + 1 => Some(ChipModel::Bm1362), + 2 => Some(ChipModel::Bm1366), + 3 => Some(ChipModel::Bm1368), + 4 => Some(ChipModel::Bm1370), + 5 => Some(ChipModel::Bm1398), + _ => None, + } +} + impl HardwareBackend for HalClient { type Error = HalError; @@ -403,3 +577,115 @@ impl HardwareBackend for HalClient { result } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::fanmap::FanProbe; + use std::os::unix::net::UnixStream; + + fn mock_backend(mut server: UnixStream) { + loop { + let mut header = [0_u8; 16]; + if server.read_exact(&mut header).is_err() { + return; + } + let opcode = header[5]; + let sequence = [header[8], header[9], header[10], header[11]]; + let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize; + let mut payload = vec![0_u8; length]; + if length > 0 && server.read_exact(&mut payload).is_err() { + return; + } + let body: Vec = match opcode { + CAPABILITIES => { + let mut body = vec![0_u8]; + body.extend_from_slice( + &(CAP_CHAIN_PROBE + | CAP_EEPROM + | CAP_PSU_IDENTITY + | CAP_FREQUENCY + | CAP_POWER) + .to_le_bytes(), + ); + body + } + PROBE_CHAIN => vec![0, PROBE_IDENTIFIED, 1, 126, 0], + READ_EEPROM => { + let mut body = vec![0, EEPROM_PRESENT]; + body.extend_from_slice(b"BHB42601"); + body + } + IDENTIFY_PSU => { + let name = b"APW12"; + let mut body = vec![0_u8]; + body.push(name.len() as u8); + body.extend_from_slice(name); + for word in [1200_u16, 1600, 0, 1000, 3600] { + body.extend_from_slice(&word.to_le_bytes()); + } + body + } + SET_FAN_TARGET | SET_CHAIN_FREQUENCY => vec![0], + READ_POWER => { + let mut body = vec![0_u8]; + body.extend_from_slice(&0_u16.to_le_bytes()); + body + } + READ_TEMPERATURE => { + let mut body = vec![0_u8]; + body.extend_from_slice(&42_000_i32.to_le_bytes()); + body + } + _ => vec![1], + }; + let mut out = [0_u8; 16]; + out[..4].copy_from_slice(&MAGIC); + out[4] = VERSION; + out[5] = opcode; + out[6..8].copy_from_slice(&RESPONSE.to_le_bytes()); + out[8..12].copy_from_slice(&sequence); + out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes()); + if server.write_all(&out).is_err() || server.write_all(&body).is_err() { + return; + } + } + } + + #[test] + fn detection_verbs_round_trip_over_the_wire() { + let (client_stream, server_stream) = UnixStream::pair().expect("socket pair"); + let server = std::thread::spawn(move || mock_backend(server_stream)); + let mut client = HalClient::from_stream(client_stream).expect("client"); + + assert_eq!( + client.capabilities().expect("capabilities"), + CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY | CAP_POWER + ); + match client.probe_chain(0, 0).expect("probe") { + ProbeOutcome::Identified { chip, chips } => { + assert_eq!(chip, ChipModel::Bm1362); + assert_eq!(chips, 126); + } + other => panic!("unexpected probe outcome: {other:?}"), + } + assert_eq!( + client.read_eeprom(0).expect("eeprom"), + EepromState::Present { + model: "BHB42601".into() + } + ); + let psu = client.identify_psu().expect("psu"); + assert_eq!(psu.name, "APW12"); + assert_eq!(psu.envelope.v_min_mv, 1200); + assert_eq!(psu.envelope.v_max_mv, 1600); + assert_eq!(psu.max_dc_watts, 3600); + + client.set_chain_frequency(2, 512).expect("set frequency"); + client.set_fan(1, 60).expect("set fan"); + assert_eq!(client.read_zone(2).expect("read zone"), 42_000); + + drop(client); + server.join().expect("server thread"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 9675636..8a96122 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,22 +3,37 @@ //! An entry in the target matrix is a development obligation, not a claim that //! the pairing already mines. Hardware backends are supplied by SDK images. +pub mod app; pub mod bm1362; pub mod bm1366; pub mod bm1370; pub mod bm13xx; +pub mod detect; pub mod difficulty; +pub mod fanmap; +pub mod fanmap_store; +pub mod fault; +pub mod hal_conformance; +pub mod hal_sim; pub mod hal_wire; pub mod management; pub mod miner; pub mod pow; +pub mod profiles; +pub mod runtime; pub mod scrypt_pow; +pub mod split; pub mod stratum_client; +pub mod stratum_link; pub mod stratum_session; pub mod stratum_submit; pub mod stratum_v1; +pub mod stratum_v2; +pub mod stratum_v2_session; pub mod stratum_wire; pub mod stratum_work; +pub mod tuning; +pub mod web; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Vendor { diff --git a/src/main.rs b/src/main.rs index ec6912a..06ea365 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,17 @@ // SPDX-License-Identifier: MIT +use alkane_os::app; +use alkane_os::detect::{ + ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome, + PsuCapability, SensorTopology, +}; use alkane_os::hal_wire::HalClient; -use alkane_os::management::{bind_local, serve, MiningStatus}; +use alkane_os::management::MiningStatus; use alkane_os::miner::{Bm1366Miner, ChipModel}; +use alkane_os::runtime::{Tick, TickOutcome}; use alkane_os::stratum_client::{PoolConnection, PoolEvent}; use alkane_os::target_matrix; +use alkane_os::tuning::{PidConfig, TuningTarget}; +use alkane_os::HardwareBackend; use std::error::Error; use std::io; use std::net::SocketAddr; @@ -26,14 +34,21 @@ fn sim_mine(mut args: impl Iterator) -> Result<(), Box let password = std::env::var("ALKANE_POOL_PASSWORD") .map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?; let status = Arc::new(MiningStatus::new()); - if let Ok(bind) = std::env::var("ALKANE_API_LISTEN") { - let listener = bind_local(bind.parse()?)?; - let snapshot = Arc::clone(&status); - std::thread::spawn(move || { - if let Err(error) = serve(listener, snapshot) { - eprintln!("management API stopped: {error}"); - } - }); + let api = std::env::var("ALKANE_API_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let web = std::env::var("ALKANE_WEB_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let servers = app::start(Arc::clone(&status), api, web)?; + let (api_address, web_address) = servers.addresses(); + if let Some(address) = api_address { + println!("management API on {address}"); + } + if let Some(address) = web_address { + println!("web UI on http://{address}/"); } // Connect to the pool before enabling power. The SDK HAL server owns the @@ -80,6 +95,214 @@ fn sim_mine(mut args: impl Iterator) -> Result<(), Box } } +/// A backend that answers without hardware, so the boot path can be exercised on any machine. +struct SelfCheckBackend; + +impl DetectionBackend for SelfCheckBackend { + type Error = (); + + fn probe(&mut self, _chain: u8, _attempt: u8) -> Result { + Ok(ProbeOutcome::Identified { + chip: DetectedChip::Bm1362, + chips: 126, + }) + } + + fn eeprom(&mut self, _chain: u8) -> Result { + Ok(EepromState::Absent) + } + + fn identify_psu(&mut self) -> Result, ()> { + Ok(Some(PsuCapability { + name: "APW12".into(), + envelope: Envelope { + v_min_mv: 1200, + v_max_mv: 1600, + f_min_mhz: 0, + f_max_mhz: 1000, + }, + max_dc_watts: 3600, + })) + } +} + +/// Run detection, the runtime loop and the API document against the self-check backend. +/// +/// This is the smoke test an image can run on a bench machine before any hashboard is attached: +/// it proves the profile database parses, detection produces a plan, the tuner moves within the +/// envelope and the published document is well formed. +fn self_check() -> Result<(), Box> { + let status = MiningStatus::new(); + let config = app::BootConfig { + profile_db_json: include_str!("../profiles.example.json").to_owned(), + chain_ports: vec![0, 1, 2], + sensor: SensorTopology::Pic, + budget: ProbeBudget::default(), + fan_zones: Vec::new(), + target: TuningTarget::PowerW(2_400.0), + pid: PidConfig::default(), + ceiling_mc: 95_000, + fault_policy: Default::default(), + }; + let mut backend = SelfCheckBackend; + let mut runtime = app::boot(&mut backend, &config, &status)?; + let start = runtime.operating_point().frequency_mhz; + for _ in 0..20 { + let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz); + runtime.tick(&Tick { + power_w: Some(power), + hashrate_ths: None, + hottest_mc: Some(70_000), + ambient_mc: None, + dt_s: 1.0, + }); + } + let end = runtime.operating_point().frequency_mhz; + if end <= start { + return Err("self-check: frequency did not move toward the target".into()); + } + if runtime.active_chains().len() != 3 { + return Err("self-check: detection did not expose three chains".into()); + } + status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target))); + let document = status.hardware_document(); + if document["available"] != true { + return Err("self-check: hardware document is not available".into()); + } + println!("{}", serde_json::to_string_pretty(&document)?); + Ok(()) +} + +fn parse_target(text: &str) -> Result> { + let (kind, value) = text + .split_once(':') + .ok_or("target must look like power:2400")?; + let value: f32 = value.parse()?; + Ok(match kind { + "power" => TuningTarget::PowerW(value), + "hashrate" => TuningTarget::HashrateThs(value), + "ambient" => TuningTarget::AmbientC { + margin_mc: value as i32, + }, + "fan" => TuningTarget::MaxFan { + max_pwm: value as u8, + }, + _ => return Err("target must be power, hashrate, ambient or fan".into()), + }) +} + +/// Boot a real board through the HAL socket, then run a bounded tuning loop. +fn boot_hal(mut args: impl Iterator) -> Result<(), Box> { + let socket = args.next().ok_or("missing HAL socket")?; + let profiles = args.next().ok_or("missing profile database path")?; + let target = parse_target(&args.next().ok_or("missing target")?)?; + let sensor = match args.next().as_deref() { + Some("nopic") => SensorTopology::NoPic, + Some("pic") | None => SensorTopology::Pic, + Some(_) => return Err("sensor must be pic or nopic".into()), + }; + let ticks: usize = args + .next() + .map(|value| value.parse()) + .transpose()? + .unwrap_or(30); + let profile_db_json = std::fs::read_to_string(&profiles)?; + let status = Arc::new(MiningStatus::new()); + let api = std::env::var("ALKANE_API_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let web = std::env::var("ALKANE_WEB_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let servers = app::start(Arc::clone(&status), api, web)?; + + let config = app::BootConfig { + profile_db_json, + chain_ports: vec![0, 1, 2], + sensor, + budget: ProbeBudget::default(), + fan_zones: Vec::new(), + target, + pid: PidConfig::default(), + ceiling_mc: 95_000, + fault_policy: Default::default(), + }; + 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: alkane_os::fanmap::SweepConfig { + fans, + zones, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: std::env::var("ALKANE_FAN_SETTLE_MS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20_000), + }, + thresholds: Default::default(), + map_path: &map_path, + }; + let (mut runtime, _map) = + app::boot_from_hal(std::path::Path::new(&socket), &settings, &status)?; + println!( + "detected {} with {} active chains", + runtime.plan().profile, + runtime.active_chains().len() + ); + + let mut client = HalClient::connect(std::path::Path::new(&socket))?; + let label = app::target_label(&config.target); + 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, + hashrate_ths: None, + hottest_mc: hottest, + ambient_mc: None, + dt_s: 1.0, + }); + if let TickOutcome::Run(command) = outcome { + for chain in runtime.active_chains() { + client.set_chain_frequency(chain, command.frequency_mhz)?; + } + if let Some(pwm) = command.fan_pwm { + client.set_fan_target(0, pwm)?; + } + } + // Publish every period: a client watching the API must see the live operating point, + // not the boot-time snapshot. + status.set_hardware(app::snapshot(&runtime, &label)); + if let Some(reason) = runtime.stop_reason() { + println!("stopped: {reason:?}"); + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target))); + println!( + "{}", + serde_json::to_string_pretty(&status.hardware_document())? + ); + let _ = servers; + Ok(()) +} + fn main() { let mut args = std::env::args().skip(1); match args.next().as_deref() { @@ -93,6 +316,84 @@ fn main() { } } Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")), + Some("--boot") => { + if let Err(error) = boot_hal(args) { + eprintln!("boot failed: {error}"); + 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("--check-profiles") => { + let path = match args.next() { + Some(path) => path, + None => { + eprintln!("usage: alkane-os --check-profiles PATH"); + std::process::exit(2); + } + }; + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(error) => { + eprintln!("cannot read {path}: {error}"); + std::process::exit(1); + } + }; + match alkane_os::profiles::ProfileDb::from_json(&text) { + Ok(db) => { + println!("{} profiles, schema 1, validated", db.len()); + } + Err(error) => { + eprintln!("profile database rejected: {error:?}"); + std::process::exit(1); + } + } + } + Some("--check-hal") => { + let socket = match args.next() { + Some(path) => path, + None => { + eprintln!("usage: alkane-os --check-hal SOCKET"); + std::process::exit(2); + } + }; + let checks = alkane_os::hal_conformance::run(std::path::Path::new(&socket)); + let mut failed = 0; + for check in &checks { + println!( + "{:<28} {:<4} {}", + check.name, + if check.passed { "PASS" } else { "FAIL" }, + check.detail + ); + if !check.passed { + failed += 1; + } + } + if failed > 0 { + std::process::exit(1); + } + } + Some("--self-check") => { + if let Err(error) = self_check() { + eprintln!("self-check failed: {error}"); + std::process::exit(1); + } + } Some("--mine-simulator") => { if let Err(error) = sim_mine(args) { eprintln!("simulator mining failed: {error}"); @@ -100,7 +401,10 @@ fn main() { } } _ => { - eprintln!("usage: alkane-os --list-targets | --version | --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 | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); + eprintln!( + "env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..." + ); std::process::exit(2); } } diff --git a/src/management.rs b/src/management.rs index a98edd2..4013169 100644 --- a/src/management.rs +++ b/src/management.rs @@ -1,23 +1,39 @@ // SPDX-License-Identifier: MIT //! Bounded, read-only cgminer-style status for a local management client. +use crate::detect::{EepromState, HardwarePlan}; use serde_json::{json, Value}; use std::io::{self, Read, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; +use std::sync::Mutex; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; const MAX_REQUEST_BYTES: usize = 2048; const CLIENT_TIMEOUT: Duration = Duration::from_millis(500); const REQUEST_DEADLINE: Duration = Duration::from_secs(2); +/// Everything the extended API exposes beyond share counters. +#[derive(Clone, Debug, PartialEq)] +pub struct HardwareSnapshot { + pub plan: HardwarePlan, + /// Chains the supervisor still allows work on. + pub active_chains: Vec, + /// `None` while hashing; otherwise why the machine stopped. + pub stopped: Option<&'static str>, + pub frequency_mhz: u16, + /// Operator target in the form `power:3000`, `hashrate:200`, `ambient:20000`, `fan:100`. + pub target: String, +} + #[derive(Debug)] pub struct MiningStatus { started: Instant, running: AtomicBool, accepted: AtomicU64, rejected: AtomicU64, + hardware: Mutex>, } impl Default for MiningStatus { @@ -33,9 +49,31 @@ impl MiningStatus { running: AtomicBool::new(false), accepted: AtomicU64::new(0), rejected: AtomicU64::new(0), + hardware: Mutex::new(None), } } + /// Publish the current hardware view for the API. + pub fn set_hardware(&self, snapshot: HardwareSnapshot) { + if let Ok(mut slot) = self.hardware.lock() { + *slot = Some(snapshot); + } + } + + /// The `hardware` document, for the on-box UI and local clients. + pub fn hardware_document(&self) -> Value { + hardware_json(self.hardware()) + } + + /// The `summary` document, for the on-box UI and local clients. + pub fn summary_document(&self) -> Value { + self.response("summary") + } + + fn hardware(&self) -> Option { + self.hardware.lock().ok().and_then(|slot| slot.clone()) + } + pub fn set_running(&self, running: bool) { self.running.store(running, Ordering::Relaxed); } @@ -72,6 +110,16 @@ impl MiningStatus { "API": "1.0" }]}), ), + "hardware" => ( + "S", + "Hardware", + json!({"HARDWARE": [hardware_json(self.hardware())]}), + ), + "stats" => ( + "S", + "Stats", + json!({"STATS": [stats_json(self.hardware())]}), + ), _ => ("E", "Unknown command", json!({})), }; let mut response = json!({"STATUS": [{ @@ -89,6 +137,69 @@ impl MiningStatus { } } +fn eeprom_json(state: &EepromState) -> Value { + match state { + EepromState::Present { model } => json!({"state": "present", "model": model}), + EepromState::Absent => json!({"state": "absent"}), + EepromState::Invalid => json!({"state": "invalid"}), + } +} + +fn hardware_json(snapshot: Option) -> Value { + let Some(snapshot) = snapshot else { + return json!({"available": false}); + }; + let plan = &snapshot.plan; + json!({ + "available": true, + "profile": plan.profile, + "chip": plan.chip.name(), + "psu": plan.psu, + "envelope": { + "v_min_mv": plan.envelope.v_min_mv, + "v_max_mv": plan.envelope.v_max_mv, + "f_min_mhz": plan.envelope.f_min_mhz, + "f_max_mhz": plan.envelope.f_max_mhz, + }, + "operating_point": { + "voltage_mv": plan.envelope.voltage_for(snapshot.frequency_mhz), + "frequency_mhz": snapshot.frequency_mhz, + "confirmed": plan.operating_point.confirmed, + }, + "chains": plan.chains.iter().map(|chain| json!({ + "index": chain.index, + "chip": chain.chip.name(), + "chips_found": chain.chips_found, + "eeprom": eeprom_json(&chain.eeprom), + "response_per_mille": chain.response_per_mille, + })).collect::>(), + "fan_zones": plan.fan_zones.iter().map(|zone| json!({ + "fan": zone.fan, + "zones": zone.zones, + })).collect::>(), + "active_chains": snapshot.active_chains, + "stopped": snapshot.stopped, + "target": snapshot.target, + "frequency_mhz": snapshot.frequency_mhz, + }) +} + +fn stats_json(snapshot: Option) -> Value { + let Some(snapshot) = snapshot else { + return json!({"available": false}); + }; + json!({ + "Profile": snapshot.plan.profile, + "Chip": snapshot.plan.chip.name(), + "PSU": snapshot.plan.psu, + "FrequencyMHz": snapshot.frequency_mhz, + "VoltageMV": snapshot.plan.envelope.voltage_for(snapshot.frequency_mhz), + "Target": snapshot.target, + "ActiveChains": snapshot.active_chains.len(), + "Stopped": snapshot.stopped, + }) +} + fn request_command(bytes: &[u8]) -> Option<&str> { let request = std::str::from_utf8(bytes).ok()?.trim(); if request.starts_with('{') { @@ -97,12 +208,16 @@ fn request_command(bytes: &[u8]) -> Option<&str> { match command { "summary" => Some("summary"), "version" => Some("version"), + "hardware" => Some("hardware"), + "stats" => Some("stats"), _ => Some("unknown"), } } else { match request { "summary" => Some("summary"), "version" => Some("version"), + "hardware" => Some("hardware"), + "stats" => Some("stats"), _ => Some("unknown"), } } @@ -246,4 +361,85 @@ mod tests { assert!(parsed.get("SUMMARY").is_some()); worker.join().unwrap(); } + + fn snapshot() -> HardwareSnapshot { + HardwareSnapshot { + plan: HardwarePlan { + profile: "s19jpro-bm1362-pic".into(), + chip: crate::detect::ChipModel::Bm1362, + chains: vec![crate::detect::ChainReport { + index: 0, + chip: crate::detect::ChipModel::Bm1362, + chips_found: 126, + eeprom: EepromState::Absent, + response_per_mille: Some(950), + }], + envelope: crate::detect::Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + operating_point: crate::detect::OperatingPoint { + voltage_mv: 1200, + frequency_mhz: 500, + confirmed: false, + }, + psu: "APW12".into(), + fan_zones: vec![crate::detect::FanZone { + fan: 0, + zones: vec![0, 1], + }], + }, + active_chains: vec![0], + stopped: None, + frequency_mhz: 512, + target: "power:3000".into(), + } + } + + #[test] + fn hardware_is_unavailable_until_published() { + let status = MiningStatus::new(); + let reply = status.response("hardware"); + assert_eq!(reply["HARDWARE"][0]["available"], false); + } + + #[test] + fn hardware_command_exposes_detection_and_fault_state() { + let status = MiningStatus::new(); + status.set_hardware(snapshot()); + let reply = status.response("hardware"); + let hardware = &reply["HARDWARE"][0]; + assert_eq!(hardware["available"], true); + assert_eq!(hardware["profile"], "s19jpro-bm1362-pic"); + assert_eq!(hardware["chip"], "bm1362"); + assert_eq!(hardware["psu"], "APW12"); + assert_eq!(hardware["chains"][0]["chips_found"], 126); + assert_eq!(hardware["chains"][0]["eeprom"]["state"], "absent"); + assert_eq!(hardware["operating_point"]["confirmed"], false); + assert_eq!(hardware["active_chains"][0], 0); + assert_eq!(hardware["target"], "power:3000"); + assert_eq!(hardware["fan_zones"][0]["zones"][1], 1); + } + + #[test] + fn stats_command_keeps_cgminer_shape() { + let status = MiningStatus::new(); + status.set_hardware(snapshot()); + let reply = status.response("stats"); + let stats = &reply["STATS"][0]; + assert_eq!(stats["Profile"], "s19jpro-bm1362-pic"); + assert_eq!(stats["FrequencyMHz"], 512); + assert_eq!(stats["VoltageMV"], 1312); + assert_eq!(stats["ActiveChains"], 1); + assert!(stats["Stopped"].is_null()); + } + + #[test] + fn unknown_commands_still_refuse() { + let status = MiningStatus::new(); + let reply = status.response("reboot"); + assert_eq!(reply["STATUS"][0]["STATUS"], "E"); + } } diff --git a/src/profiles.rs b/src/profiles.rs new file mode 100644 index 0000000..1d9bb3b --- /dev/null +++ b/src/profiles.rs @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: MIT +//! Board profile database. +//! +//! Profiles carry the safe voltage/frequency envelope a chip/board combination may run inside. +//! Detection may only use what this database provides: if a combination is absent, the answer is +//! "refuse", never "assume a number". Entries are data, so they can be filled from captures +//! without touching code. + +use crate::detect::{BoardProfile, ChipModel, Envelope, SensorTopology}; +use serde_json::Value; + +/// Why a profile database was rejected. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ProfileError { + InvalidJson, + UnsupportedSchema, + MissingProfiles, + UnknownChip(String), + UnknownSensor(String), + InvalidEnvelope(String), + DuplicateName(String), +} + +/// A validated set of profiles. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ProfileDb { + profiles: Vec, +} + +impl ProfileDb { + /// Validate and keep a set of profiles. + pub fn new(profiles: Vec) -> Result { + for (index, profile) in profiles.iter().enumerate() { + if profiles[..index] + .iter() + .any(|other| other.name == profile.name) + { + return Err(ProfileError::DuplicateName(profile.name.clone())); + } + if profile.chains == 0 { + return Err(ProfileError::InvalidEnvelope(profile.name.clone())); + } + let envelope = profile.envelope; + if envelope.v_min_mv == 0 + || envelope.v_min_mv > envelope.v_max_mv + || envelope.f_min_mhz > envelope.f_max_mhz + { + return Err(ProfileError::InvalidEnvelope(profile.name.clone())); + } + } + Ok(Self { profiles }) + } + + /// Parse the schema-1 profile document. + pub fn from_json(text: &str) -> Result { + let root: Value = serde_json::from_str(text).map_err(|_| ProfileError::InvalidJson)?; + match root.get("schema").and_then(Value::as_u64) { + Some(1) => {} + Some(_) => return Err(ProfileError::UnsupportedSchema), + None => return Err(ProfileError::UnsupportedSchema), + } + let entries = root + .get("profiles") + .and_then(Value::as_array) + .ok_or(ProfileError::MissingProfiles)?; + let mut profiles = Vec::with_capacity(entries.len()); + for entry in entries { + profiles.push(profile_from_value(entry)?); + } + if profiles.is_empty() { + return Err(ProfileError::MissingProfiles); + } + Self::new(profiles) + } + + /// Exact lookup: a profile only applies to the chip, chain count and sensor wiring it declares. + pub fn find( + &self, + chip: ChipModel, + chains: u8, + sensor: SensorTopology, + ) -> Option<&BoardProfile> { + self.profiles.iter().find(|profile| { + profile.chip == chip && profile.chains == chains && profile.sensor == sensor + }) + } + + pub fn len(&self) -> usize { + self.profiles.len() + } + + pub fn is_empty(&self) -> bool { + self.profiles.is_empty() + } +} + +fn profile_from_value(entry: &Value) -> Result { + let name = entry + .get("name") + .and_then(Value::as_str) + .ok_or(ProfileError::InvalidJson)? + .to_owned(); + let chip_text = entry + .get("chip") + .and_then(Value::as_str) + .ok_or(ProfileError::UnknownChip(name.clone()))?; + let chip = match chip_text { + "bm1362" => ChipModel::Bm1362, + "bm1366" => ChipModel::Bm1366, + "bm1368" => ChipModel::Bm1368, + "bm1370" => ChipModel::Bm1370, + "bm1398" => ChipModel::Bm1398, + other => return Err(ProfileError::UnknownChip(other.to_owned())), + }; + let sensor_text = entry + .get("sensor") + .and_then(Value::as_str) + .ok_or(ProfileError::UnknownSensor(name.clone()))?; + let sensor = match sensor_text { + "pic" => SensorTopology::Pic, + "nopic" => SensorTopology::NoPic, + "unknown" => SensorTopology::Unknown, + other => return Err(ProfileError::UnknownSensor(other.to_owned())), + }; + let chains = entry + .get("chains") + .and_then(Value::as_u64) + .and_then(|value| u8::try_from(value).ok()) + .ok_or(ProfileError::InvalidEnvelope(name.clone()))?; + let envelope = entry + .get("envelope") + .and_then(Value::as_object) + .ok_or(ProfileError::InvalidEnvelope(name.clone()))?; + let field = |key: &str| -> Result { + envelope + .get(key) + .and_then(Value::as_u64) + .and_then(|value| u16::try_from(value).ok()) + .ok_or(ProfileError::InvalidEnvelope(name.clone())) + }; + let envelope = Envelope { + v_min_mv: field("v_min_mv")?, + v_max_mv: field("v_max_mv")?, + f_min_mhz: field("f_min_mhz")?, + f_max_mhz: field("f_max_mhz")?, + }; + Ok(BoardProfile { + name, + chip, + sensor, + chains, + envelope, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const VALID: &str = r#"{ + "schema": 1, + "profiles": [ + { + "name": "s19jpro-bm1362-pic", + "chip": "bm1362", + "sensor": "pic", + "chains": 3, + "envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700} + } + ] + }"#; + + #[test] + fn valid_document_loads_and_resolves() { + let db = ProfileDb::from_json(VALID).expect("db"); + assert_eq!(db.len(), 1); + let profile = db + .find(ChipModel::Bm1362, 3, SensorTopology::Pic) + .expect("profile"); + assert_eq!(profile.name, "s19jpro-bm1362-pic"); + assert_eq!(profile.envelope.v_max_mv, 1500); + assert!(db.find(ChipModel::Bm1362, 2, SensorTopology::Pic).is_none()); + assert!(db + .find(ChipModel::Bm1362, 3, SensorTopology::NoPic) + .is_none()); + } + + #[test] + fn unknown_chip_is_rejected() { + let text = VALID.replace("bm1362", "bm9999"); + assert_eq!( + ProfileDb::from_json(&text), + Err(ProfileError::UnknownChip("bm9999".into())) + ); + } + + #[test] + fn inverted_envelope_is_rejected() { + let text = VALID.replace( + "\"v_min_mv\": 1100, \"v_max_mv\": 1500", + "\"v_min_mv\": 1500, \"v_max_mv\": 1100", + ); + assert!(matches!( + ProfileDb::from_json(&text), + Err(ProfileError::InvalidEnvelope(_)) + )); + } + + #[test] + fn wrong_schema_is_rejected() { + let text = VALID.replace("\"schema\": 1", "\"schema\": 2"); + assert_eq!( + ProfileDb::from_json(&text), + Err(ProfileError::UnsupportedSchema) + ); + } + + #[test] + fn missing_profiles_are_rejected() { + assert_eq!( + ProfileDb::from_json("{\"schema\": 1}"), + Err(ProfileError::MissingProfiles) + ); + } + + #[test] + fn duplicate_names_are_rejected() { + let one = VALID.split("\"profiles\": [").nth(1).unwrap(); + let entry = one.trim().trim_end_matches("]\n }").trim(); + let duplicated = format!("{{\"schema\": 1, \"profiles\": [{entry}, {entry}]}}"); + assert!(matches!( + ProfileDb::from_json(&duplicated), + Err(ProfileError::DuplicateName(_)) + )); + } +} diff --git a/src/runtime.rs b/src/runtime.rs new file mode 100644 index 0000000..15acccd --- /dev/null +++ b/src/runtime.rs @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: MIT +//! Mining runtime: one state machine over the detection plan, the fault ladder and the tuner. +//! +//! Each tick takes a measurement, lets the tuner move the operating point, and lets the fault +//! supervisor veto the machine. The pieces are tested in isolation elsewhere; this module is the +//! place where their order is decided, and the order matters: a stopped machine must not be tuned, +//! and a disabled chain must not be dispatched to. + +use crate::detect::{HardwarePlan, OperatingPoint}; +use crate::fault::{FaultAction, FaultEvent, FaultPolicy, FaultSupervisor, StopReason}; +use crate::tuning::{Command, Observation, PidConfig, TuningError, TuningLoop, TuningTarget}; + +/// One control period's measurements. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tick { + pub power_w: Option, + pub hashrate_ths: Option, + pub hottest_mc: Option, + pub ambient_mc: Option, + pub dt_s: f32, +} + +/// What the runtime decided for this period. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TickOutcome { + /// Apply this command to the hardware. + Run(Command), + /// Measurement missing; hold the previous operating point. + Hold(Command), + /// The machine is stopped and must not hash. + Stopped(StopReason), +} + +/// Runtime state for one machine. +#[derive(Clone, Debug)] +pub struct MinerRuntime { + plan: HardwarePlan, + faults: FaultSupervisor, + tuning: TuningLoop, + last_command: Command, +} + +impl MinerRuntime { + pub fn new( + plan: HardwarePlan, + policy: FaultPolicy, + target: TuningTarget, + pid: PidConfig, + ceiling_mc: i32, + ) -> Self { + let chains: Vec = plan.chains.iter().map(|chain| chain.index).collect(); + let last_command = Command { + frequency_mhz: plan.operating_point.frequency_mhz, + fan_pwm: None, + }; + Self { + faults: FaultSupervisor::new(&chains, policy), + tuning: TuningLoop::new(target, plan.envelope, pid, ceiling_mc), + plan, + last_command, + } + } + + pub fn plan(&self) -> &HardwarePlan { + &self.plan + } + + pub fn operating_point(&self) -> OperatingPoint { + OperatingPoint { + voltage_mv: self + .plan + .envelope + .voltage_for(self.last_command.frequency_mhz), + frequency_mhz: self.last_command.frequency_mhz, + confirmed: self.plan.operating_point.confirmed, + } + } + + pub fn active_chains(&self) -> Vec { + self.faults.active_chains() + } + + pub fn stop_reason(&self) -> Option { + self.faults.stop_reason() + } + + /// Feed one health observation; returns what the supervisor decided. + pub fn on_event(&mut self, event: FaultEvent) -> FaultAction { + self.faults.observe(event) + } + + /// Advance one control period. + pub fn tick(&mut self, tick: &Tick) -> TickOutcome { + if let Some(reason) = self.faults.stop_reason() { + return TickOutcome::Stopped(reason); + } + let observation = Observation { + power_w: tick.power_w, + hashrate_ths: tick.hashrate_ths, + hottest_mc: tick.hottest_mc, + ambient_mc: tick.ambient_mc, + }; + match self.tuning.step(observation, tick.dt_s) { + Ok(command) => { + self.last_command = command; + TickOutcome::Run(command) + } + Err(TuningError::NoMeasurement) => TickOutcome::Hold(self.last_command), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::detect::{ChainReport, ChipModel, EepromState, Envelope, FanZone}; + + fn plan() -> HardwarePlan { + HardwarePlan { + profile: "s19jpro-bm1362-pic".into(), + chip: ChipModel::Bm1362, + chains: (0..3) + .map(|index| ChainReport { + index, + chip: ChipModel::Bm1362, + chips_found: 126, + eeprom: EepromState::Absent, + response_per_mille: Some(950), + }) + .collect(), + envelope: Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + operating_point: OperatingPoint { + voltage_mv: 1200, + frequency_mhz: 300, + confirmed: false, + }, + psu: "APW12".into(), + fan_zones: vec![FanZone { + fan: 0, + zones: vec![0], + }], + } + } + + fn runtime() -> MinerRuntime { + MinerRuntime::new( + plan(), + FaultPolicy::default(), + TuningTarget::PowerW(2_400.0), + PidConfig { + kp: 0.2, + ki: 0.05, + kd: 0.0, + out_min: 0.0, + out_max: 0.0, + max_step_per_s: 50.0, + deadband: 0.0, + }, + 95_000, + ) + } + + fn tick(power: f32) -> Tick { + Tick { + power_w: Some(power), + hashrate_ths: None, + hottest_mc: Some(70_000), + ambient_mc: None, + dt_s: 1.0, + } + } + + #[test] + fn a_fresh_runtime_exposes_every_chain() { + assert_eq!(runtime().active_chains(), vec![0, 1, 2]); + assert_eq!(runtime().stop_reason(), None); + } + + #[test] + fn ticks_move_frequency_inside_the_envelope() { + let mut runtime = runtime(); + let mut frequency = 300; + for _ in 0..60 { + let power = 4.0 * f32::from(frequency); + if let TickOutcome::Run(command) = runtime.tick(&tick(power)) { + frequency = command.frequency_mhz; + assert!((300..=700).contains(&frequency)); + } + } + assert!(frequency > 300, "frequency never moved: {frequency}"); + } + + #[test] + fn a_missing_measurement_holds_the_last_command() { + let mut runtime = runtime(); + let empty = Tick { + power_w: None, + hashrate_ths: None, + hottest_mc: None, + ambient_mc: None, + dt_s: 1.0, + }; + match runtime.tick(&empty) { + TickOutcome::Hold(command) => assert_eq!(command.frequency_mhz, 300), + other => panic!("unexpected outcome: {other:?}"), + } + } + + #[test] + fn a_dead_chain_is_removed_from_dispatch_without_stopping_the_machine() { + let mut runtime = runtime(); + assert_eq!( + runtime.on_event(FaultEvent::ChainError { chain: 1 }), + FaultAction::Retry { chain: 1 } + ); + assert_eq!( + runtime.on_event(FaultEvent::ChainError { chain: 1 }), + FaultAction::Retry { chain: 1 } + ); + assert_eq!( + runtime.on_event(FaultEvent::ChainError { chain: 1 }), + FaultAction::DisableChain { chain: 1 } + ); + assert_eq!(runtime.active_chains(), vec![0, 2]); + assert!(matches!(runtime.tick(&tick(2_000.0)), TickOutcome::Run(_))); + } + + #[test] + fn a_temperature_fault_stops_the_machine_for_good() { + let mut runtime = runtime(); + assert_eq!( + runtime.on_event(FaultEvent::TemperatureFault { zone: 1 }), + FaultAction::Stop { + reason: StopReason::Temperature + } + ); + assert_eq!( + runtime.tick(&tick(2_400.0)), + TickOutcome::Stopped(StopReason::Temperature) + ); + assert_eq!( + runtime.tick(&tick(2_400.0)), + TickOutcome::Stopped(StopReason::Temperature) + ); + } + + #[test] + fn losing_every_chain_stops_the_machine() { + let mut runtime = MinerRuntime::new( + plan(), + FaultPolicy { + retries: 0, + ..FaultPolicy::default() + }, + TuningTarget::PowerW(2_400.0), + PidConfig::default(), + 95_000, + ); + for chain in 0..3 { + runtime.on_event(FaultEvent::ChainError { chain }); + } + assert_eq!(runtime.stop_reason(), Some(StopReason::NoChainsLeft)); + assert!(runtime.active_chains().is_empty()); + } + + #[test] + fn the_operating_point_reflects_the_last_command() { + let mut runtime = runtime(); + for _ in 0..10 { + runtime.tick(&tick(1_500.0)); + } + let point = runtime.operating_point(); + assert!(point.frequency_mhz > 300); + assert!(!point.confirmed); + // Voltage follows the frequency across the envelope instead of staying at the boot value. + assert_eq!( + point.voltage_mv, + runtime.plan().envelope.voltage_for(point.frequency_mhz) + ); + assert!(point.voltage_mv > 1100); + } +} diff --git a/src/split.rs b/src/split.rs new file mode 100644 index 0000000..b843ae2 --- /dev/null +++ b/src/split.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT +//! Hashrate splitting across pools. +//! +//! Splitting is per work slot: each dispatched job comes from exactly one pool, and the router +//! hands out slots in proportion to the configured weights. Smooth weighted round-robin is used +//! because it keeps the mix correct at every prefix, not just over a long run, which matters when +//! a miner only has a handful of chains. + +/// Why a split configuration was rejected. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SplitError { + Empty, + NoWeight, + InvalidNumber, + TooManyPools, +} + +/// Per-pool weights, `50,50` style. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SplitWeights { + weights: Vec, +} + +impl SplitWeights { + /// Parse a comma-separated weight list such as `"60,40"`. + pub fn parse(text: &str) -> Result { + let mut weights = Vec::new(); + for part in text.split(',') { + let trimmed = part.trim(); + if trimmed.is_empty() { + return Err(SplitError::InvalidNumber); + } + let weight: u32 = trimmed.parse().map_err(|_| SplitError::InvalidNumber)?; + weights.push(weight); + } + Self::new(weights) + } + + pub fn new(weights: Vec) -> Result { + if weights.is_empty() { + return Err(SplitError::Empty); + } + if weights.len() > 16 { + return Err(SplitError::TooManyPools); + } + if weights.iter().all(|weight| *weight == 0) { + return Err(SplitError::NoWeight); + } + Ok(Self { weights }) + } + + pub fn pools(&self) -> usize { + self.weights.len() + } + + pub fn weight(&self, pool: usize) -> u32 { + self.weights.get(pool).copied().unwrap_or(0) + } + + /// Split `slots` work slots across the pools and return how many each receives. + pub fn allocate(&self, slots: usize) -> Vec { + let mut router = WorkRouter::new(self.clone()); + let mut counts = vec![0_usize; self.pools()]; + for _ in 0..slots { + counts[router.next_pool()] += 1; + } + counts + } +} + +/// Smooth weighted round-robin state. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct WorkRouter { + weights: SplitWeights, + current: Vec, + total: i64, +} + +impl WorkRouter { + pub fn new(weights: SplitWeights) -> Self { + let current = vec![0_i64; weights.pools()]; + let total: i64 = weights + .weights + .iter() + .map(|weight| i64::from(*weight)) + .sum(); + Self { + weights, + current, + total, + } + } + + /// Which pool supplies the next work slot. + /// + /// A pool with weight 0 never receives a slot. The winner's running score is reduced by the + /// total weight, which is what keeps the distribution proportional at every prefix. + pub fn next_pool(&mut self) -> usize { + let mut winner = 0; + for pool in 0..self.weights.pools() { + self.current[pool] += i64::from(self.weights.weight(pool)); + if self.current[pool] > self.current[winner] { + winner = pool; + } + } + self.current[winner] -= self.total; + winner + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn equal_weights_split_evenly() { + let weights = SplitWeights::parse("50,50").expect("weights"); + assert_eq!(weights.allocate(10), vec![5, 5]); + assert_eq!(weights.allocate(4), vec![2, 2]); + } + + #[test] + fn unequal_weights_split_proportionally() { + let weights = SplitWeights::parse("1,2").expect("weights"); + assert_eq!(weights.allocate(9), vec![3, 6]); + assert_eq!(weights.allocate(3), vec![1, 2]); + } + + #[test] + fn rounding_is_exact_at_every_prefix() { + let weights = SplitWeights::parse("1,1,1").expect("weights"); + assert_eq!(weights.allocate(10), vec![4, 3, 3]); + assert_eq!(weights.allocate(3), vec![1, 1, 1]); + assert_eq!(weights.allocate(1), vec![1, 0, 0]); + } + + #[test] + fn zero_weight_pools_never_receive_work() { + let weights = SplitWeights::parse("100,0,100").expect("weights"); + assert_eq!(weights.allocate(6), vec![3, 0, 3]); + } + + #[test] + fn a_single_pool_takes_everything() { + let weights = SplitWeights::parse("100").expect("weights"); + assert_eq!(weights.allocate(5), vec![5]); + } + + #[test] + fn malformed_configurations_are_rejected() { + assert_eq!(SplitWeights::parse(""), Err(SplitError::InvalidNumber)); + assert_eq!( + SplitWeights::parse("50,abc"), + Err(SplitError::InvalidNumber) + ); + assert_eq!(SplitWeights::parse("0,0"), Err(SplitError::NoWeight)); + assert_eq!(SplitWeights::new(Vec::new()), Err(SplitError::Empty)); + let many = vec![1_u32; 17]; + assert_eq!(SplitWeights::new(many), Err(SplitError::TooManyPools)); + } + + #[test] + fn the_router_is_deterministic_for_the_same_input() { + let weights = SplitWeights::parse("60,40").expect("weights"); + let first = weights.allocate(50); + let second = weights.allocate(50); + assert_eq!(first, second); + assert_eq!(first.iter().sum::(), 50); + assert_eq!(first[0], 30); + assert_eq!(first[1], 20); + } +} diff --git a/src/stratum_link.rs b/src/stratum_link.rs new file mode 100644 index 0000000..9e398ae --- /dev/null +++ b/src/stratum_link.rs @@ -0,0 +1,385 @@ +// SPDX-License-Identifier: MIT +//! Stratum V2 transport and version selection. +//! +//! `TcpLink` turns a TCP stream into the framed messages the session expects: it buffers partial +//! reads and hands out one frame at a time, so a frame split across packets is not a protocol +//! error. The selection policy decides when a miner may fall back to Stratum V1. + +use crate::stratum_v2::{Frame, V2Error}; +use crate::stratum_v2_session::V2Link; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::time::Duration; + +const READ_CHUNK: usize = 4096; + +/// A framed connection over TCP. +pub struct TcpLink { + stream: TcpStream, + buffer: Vec, +} + +impl TcpLink { + pub fn connect(address: SocketAddr, timeout: Duration) -> io::Result { + let stream = TcpStream::connect_timeout(&address, timeout)?; + stream.set_read_timeout(Some(timeout))?; + stream.set_write_timeout(Some(timeout))?; + stream.set_nodelay(true)?; + Ok(Self { + stream, + buffer: Vec::new(), + }) + } + + pub fn from_stream(stream: TcpStream) -> io::Result { + stream.set_nodelay(true)?; + Ok(Self { + stream, + buffer: Vec::new(), + }) + } + + /// Bytes received but not yet consumed, for diagnostics. + pub fn buffered(&self) -> usize { + self.buffer.len() + } +} + +impl V2Link for TcpLink { + type Error = io::Error; + + fn send(&mut self, frame: &Frame) -> io::Result<()> { + let mut wire = Vec::with_capacity(frame.payload.len() + 6); + frame.encode(&mut wire); + self.stream.write_all(&wire)?; + self.stream.flush() + } + + fn recv(&mut self) -> io::Result { + loop { + if !self.buffer.is_empty() { + match Frame::decode(&self.buffer) { + Ok((frame, consumed)) => { + self.buffer.drain(..consumed); + return Ok(frame); + } + Err(V2Error::Truncated) => {} + Err(error) => { + self.buffer.clear(); + return Err(io::Error::new(io::ErrorKind::InvalidData, error)); + } + } + } + let mut chunk = [0_u8; READ_CHUNK]; + let count = self.stream.read(&mut chunk)?; + if count == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "stratum v2 stream closed", + )); + } + self.buffer.extend_from_slice(&chunk[..count]); + } + } +} + +/// Which protocol the miner speaks. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum StratumVersion { + V1, + V2, +} + +/// Why an attempt failed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum FailureKind { + /// The server refused the connection or the setup message. + Refused, + /// No mutually supported version. + Unsupported, + /// The connection could not be established or dropped. + Transport, + /// The server did not answer in time. + Timeout, +} + +/// Operator preference. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Preference { + pub primary: StratumVersion, + pub allow_v1_fallback: bool, +} + +impl Default for Preference { + fn default() -> Self { + Self { + primary: StratumVersion::V2, + allow_v1_fallback: true, + } + } +} + +/// The protocol to try next, or `None` when there is nothing left. +/// +/// V1 is attempted only when the operator allowed it and the failure is not a transport-level +/// problem: a dead route or a dropped stream will fail identically on V1, so falling back would +/// only delay the operator-visible error. +pub fn fallback( + preference: Preference, + failed: StratumVersion, + kind: FailureKind, +) -> Option { + match (preference.primary, failed) { + (StratumVersion::V2, StratumVersion::V2) + if preference.allow_v1_fallback && kind != FailureKind::Transport => + { + Some(StratumVersion::V1) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::TcpListener; + + #[test] + fn a_frame_arrives_intact_over_tcp() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + let mut wire = Vec::new(); + Frame::new(0x00, vec![1, 2, 3, 4]).encode(&mut wire); + stream.write_all(&wire).expect("write"); + }); + let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect"); + let frame = link.recv().expect("recv"); + assert_eq!(frame.msg_type, 0x00); + assert_eq!(frame.payload, vec![1, 2, 3, 4]); + server.join().expect("join"); + } + + #[test] + fn a_frame_split_across_reads_is_reassembled() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + let mut wire = Vec::new(); + Frame::new(0x10, vec![9; 40]).encode(&mut wire); + stream.write_all(&wire[..5]).expect("first"); + std::thread::sleep(Duration::from_millis(20)); + stream.write_all(&wire[5..]).expect("rest"); + }); + let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect"); + let frame = link.recv().expect("recv"); + assert_eq!(frame.msg_type, 0x10); + assert_eq!(frame.payload.len(), 40); + server.join().expect("join"); + } + + #[test] + fn two_frames_in_one_read_are_returned_one_at_a_time() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + let mut wire = Vec::new(); + Frame::new(0x01, vec![1]).encode(&mut wire); + Frame::new(0x02, vec![2]).encode(&mut wire); + stream.write_all(&wire).expect("write"); + }); + let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect"); + assert_eq!(link.recv().expect("first").msg_type, 0x01); + assert_eq!(link.recv().expect("second").msg_type, 0x02); + server.join().expect("join"); + } + + #[test] + fn a_closed_stream_is_an_error_not_an_empty_frame() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + let server = std::thread::spawn(move || { + let (_stream, _) = listener.accept().expect("accept"); + }); + let mut link = TcpLink::connect(address, Duration::from_secs(2)).expect("connect"); + let error = link.recv().expect_err("closed stream"); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + server.join().expect("join"); + } + + #[test] + fn v1_fallback_requires_permission_and_a_non_transport_failure() { + let allowed = Preference { + primary: StratumVersion::V2, + allow_v1_fallback: true, + }; + assert_eq!( + fallback(allowed, StratumVersion::V2, FailureKind::Refused), + Some(StratumVersion::V1) + ); + assert_eq!( + fallback(allowed, StratumVersion::V2, FailureKind::Unsupported), + Some(StratumVersion::V1) + ); + assert_eq!( + fallback(allowed, StratumVersion::V2, FailureKind::Timeout), + Some(StratumVersion::V1) + ); + assert_eq!( + fallback(allowed, StratumVersion::V2, FailureKind::Transport), + None + ); + } + + #[test] + fn v1_fallback_can_be_disabled_and_v1_failures_do_not_loop() { + let denied = Preference { + primary: StratumVersion::V2, + allow_v1_fallback: false, + }; + assert_eq!( + fallback(denied, StratumVersion::V2, FailureKind::Refused), + None + ); + let allowed = Preference::default(); + assert_eq!( + fallback(allowed, StratumVersion::V1, FailureKind::Refused), + None + ); + } + + fn mock_pool() -> std::net::SocketAddr { + use crate::stratum_v2::{ + NewMiningJob, OpenStandardMiningChannelSuccess, SetNewPrevHash, SetupConnectionSuccess, + OPEN_STANDARD_MINING_CHANNEL, OPEN_STANDARD_MINING_CHANNEL_SUCCESS, SETUP_CONNECTION, + SETUP_CONNECTION_SUCCESS, SET_NEW_PREV_HASH, SUBMIT_SHARES_SUCCESS, + }; + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + // Publish the address through a channel so the test can connect after binding. + let (tx, rx) = std::sync::mpsc::channel(); + tx.send(address).expect("send address"); + std::thread::spawn(move || { + let (stream, _) = listener.accept().expect("accept"); + let mut link = TcpLink::from_stream(stream).expect("link"); + let setup = link.recv().expect("setup"); + assert_eq!(setup.msg_type, SETUP_CONNECTION); + link.send(&Frame::new( + SETUP_CONNECTION_SUCCESS, + SetupConnectionSuccess { + used_version: 2, + flags: 0, + } + .encode(), + )) + .expect("setup success"); + let open = link.recv().expect("open"); + assert_eq!(open.msg_type, OPEN_STANDARD_MINING_CHANNEL); + link.send(&Frame::new( + OPEN_STANDARD_MINING_CHANNEL_SUCCESS, + OpenStandardMiningChannelSuccess { + request_id: 1, + channel_id: 7, + target: [0x7f; 32], + extranonce_prefix: vec![9, 9], + group_channel_id: 0, + } + .encode(), + )) + .expect("channel success"); + link.send(&Frame::new( + SET_NEW_PREV_HASH, + SetNewPrevHash { + channel_id: 7, + job_id: 41, + prev_hash: [0x11; 32], + ntime_start: 1_700_000_000, + nbits: 0x1707_0000, + } + .encode(), + )) + .expect("prev hash"); + link.send(&Frame::new( + NEW_MINING_JOB_TYPE, + NewMiningJob { + channel_id: 7, + job_id: 42, + ntime_start: Some(1_700_000_100), + version: 0x2000_0000, + merkle_root: [0x22; 32], + } + .encode(), + )) + .expect("job"); + let share = link.recv().expect("share"); + assert_eq!(share.msg_type, SUBMIT_SHARES_STANDARD_TYPE); + let mut body = Vec::new(); + body.extend_from_slice(&7_u32.to_le_bytes()); + body.extend_from_slice(&1_u32.to_le_bytes()); + body.extend_from_slice(&1_u32.to_le_bytes()); + body.extend_from_slice(&0_u64.to_le_bytes()); + link.send(&Frame::new(SUBMIT_SHARES_SUCCESS, body)) + .expect("share success"); + }); + rx.recv().expect("address") + } + + const NEW_MINING_JOB_TYPE: u8 = 0x15; + const SUBMIT_SHARES_STANDARD_TYPE: u8 = 0x1a; + + #[test] + fn a_session_runs_against_a_socket_pool() { + use crate::stratum_v2_session::{handshake, V2Config, V2Event, V2Session}; + let address = mock_pool(); + let mut link = TcpLink::connect(address, Duration::from_secs(3)).expect("connect"); + let config = V2Config { + host: "pool.test".into(), + port: 3333, + flags: 0, + user_identity: "worker".into(), + nominal_hash_rate: 1.0e14, + max_target: [0xff; 32], + vendor: "alkane".into(), + hardware: "bench".into(), + firmware: "alkane-os".into(), + device_id: "b1".into(), + }; + let channel = handshake(&mut link, &config).expect("handshake"); + assert_eq!(channel.channel_id, 7); + assert_eq!(channel.extranonce_prefix, vec![9, 9]); + + let mut session = V2Session::new(channel); + let prev = session + .on_frame(&link.recv().expect("prev")) + .expect("prev event"); + assert!(matches!(prev, V2Event::PrevHash { job_id: 41, .. })); + let job = session + .on_frame(&link.recv().expect("job")) + .expect("job event"); + match job { + V2Event::Job(parsed) => { + assert_eq!(parsed.job_id, 42); + assert_eq!(parsed.prev_hash, Some([0x11; 32])); + assert_eq!(parsed.ntime_start, Some(1_700_000_100)); + } + other => panic!("unexpected event: {other:?}"), + } + let sequence = session + .submit(&mut link, 42, 0xdead_beef, 1_700_000_100, 0x2000_0000) + .expect("submit"); + assert_eq!(sequence, 1); + let ack = session + .on_frame(&link.recv().expect("ack")) + .expect("ack event"); + assert_eq!( + ack, + V2Event::ShareAccepted { + last_sequence: 1, + accepted: 1 + } + ); + } +} diff --git a/src/stratum_v2.rs b/src/stratum_v2.rs new file mode 100644 index 0000000..7629850 --- /dev/null +++ b/src/stratum_v2.rs @@ -0,0 +1,631 @@ +// SPDX-License-Identifier: MIT +//! Stratum V2 mining-protocol codec. +//! +//! Covers the client half of the mining sub-protocol: connection setup, opening a standard +//! channel, and the job/share messages that follow. Layouts follow the published specification +//! (framing in 03-Protocol-Overview 3.2, message types in 08-Message-Types, payloads in +//! 05-Mining-Protocol 5.3). +//! +//! Everything is little-endian. `U256` is carried as the raw 32 bytes of the little-endian +//! integer, which for a SHA-256 digest is the digest's own byte order. + +use std::fmt; + +pub const EXTENSION_TYPE_CORE: u16 = 0; + +pub const SETUP_CONNECTION: u8 = 0x00; +pub const SETUP_CONNECTION_SUCCESS: u8 = 0x01; +pub const SETUP_CONNECTION_ERROR: u8 = 0x02; +pub const OPEN_STANDARD_MINING_CHANNEL: u8 = 0x10; +pub const OPEN_STANDARD_MINING_CHANNEL_SUCCESS: u8 = 0x11; +pub const OPEN_MINING_CHANNEL_ERROR: u8 = 0x12; +pub const NEW_MINING_JOB: u8 = 0x15; +pub const SUBMIT_SHARES_STANDARD: u8 = 0x1a; +pub const SUBMIT_SHARES_SUCCESS: u8 = 0x1c; +pub const SUBMIT_SHARES_ERROR: u8 = 0x1d; +pub const SET_NEW_PREV_HASH: u8 = 0x20; +pub const SET_TARGET: u8 = 0x21; + +const HEADER_LEN: usize = 6; +const MAX_FRAME: usize = 1 << 20; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum V2Error { + Truncated, + Length, + String, + NonFiniteRate, + UnknownMessage(u8), +} + +impl fmt::Display for V2Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Truncated => f.write_str("stratum v2 message is truncated"), + Self::Length => f.write_str("stratum v2 length field is invalid"), + Self::String => f.write_str("stratum v2 string field is invalid"), + Self::NonFiniteRate => { + f.write_str("stratum v2 hashrate is not a finite positive number") + } + Self::UnknownMessage(kind) => { + write!(f, "unsupported stratum v2 message type {kind:#x}") + } + } + } +} + +impl std::error::Error for V2Error {} + +/// One framed message: 6-byte header plus payload. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Frame { + pub extension_type: u16, + pub msg_type: u8, + pub payload: Vec, +} + +impl Frame { + pub fn new(msg_type: u8, payload: Vec) -> Self { + Self { + extension_type: EXTENSION_TYPE_CORE, + msg_type, + payload, + } + } + + pub fn encode(&self, out: &mut Vec) { + out.extend_from_slice(&self.extension_type.to_le_bytes()); + out.push(self.msg_type); + let length = self.payload.len() as u32; + out.extend_from_slice(&length.to_le_bytes()[..3]); + out.extend_from_slice(&self.payload); + } + + /// Decode one frame from `buf`, returning it and how many bytes it consumed. + pub fn decode(buf: &[u8]) -> Result<(Self, usize), V2Error> { + if buf.len() < HEADER_LEN { + return Err(V2Error::Truncated); + } + let extension_type = u16::from_le_bytes([buf[0], buf[1]]); + let msg_type = buf[2]; + let length = u32::from_le_bytes([buf[3], buf[4], buf[5], 0]) as usize; + if length > MAX_FRAME { + return Err(V2Error::Length); + } + let end = HEADER_LEN + length; + if buf.len() < end { + return Err(V2Error::Truncated); + } + Ok(( + Self { + extension_type, + msg_type, + payload: buf[HEADER_LEN..end].to_vec(), + }, + end, + )) + } +} + +/// `SetupConnection` for the mining sub-protocol. +#[derive(Clone, Debug, PartialEq)] +pub struct SetupConnection { + pub protocol: u8, + pub min_version: u16, + pub max_version: u16, + pub flags: u32, + pub endpoint_host: String, + pub endpoint_port: u16, + pub vendor: String, + pub hardware_version: String, + pub firmware: String, + pub device_id: String, +} + +impl SetupConnection { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + out.push(self.protocol); + put_u16(&mut out, self.min_version); + put_u16(&mut out, self.max_version); + put_u32(&mut out, self.flags); + put_str(&mut out, &self.endpoint_host); + put_u16(&mut out, self.endpoint_port); + put_str(&mut out, &self.vendor); + put_str(&mut out, &self.hardware_version); + put_str(&mut out, &self.firmware); + put_str(&mut out, &self.device_id); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + Ok(Self { + protocol: reader.u8()?, + min_version: reader.u16()?, + max_version: reader.u16()?, + flags: reader.u32()?, + endpoint_host: reader.string()?, + endpoint_port: reader.u16()?, + vendor: reader.string()?, + hardware_version: reader.string()?, + firmware: reader.string()?, + device_id: reader.string()?, + }) + } +} + +/// `SetupConnection.Success`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SetupConnectionSuccess { + pub used_version: u16, + pub flags: u32, +} + +impl SetupConnectionSuccess { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + put_u16(&mut out, self.used_version); + put_u32(&mut out, self.flags); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + Ok(Self { + used_version: reader.u16()?, + flags: reader.u32()?, + }) + } +} + +/// `OpenStandardMiningChannel`. +#[derive(Clone, Debug, PartialEq)] +pub struct OpenStandardMiningChannel { + pub request_id: u32, + pub user_identity: String, + pub nominal_hash_rate: f32, + pub max_target: [u8; 32], +} + +impl OpenStandardMiningChannel { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + put_u32(&mut out, self.request_id); + put_str(&mut out, &self.user_identity); + out.extend_from_slice(&self.nominal_hash_rate.to_le_bytes()); + out.extend_from_slice(&self.max_target); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + let request_id = reader.u32()?; + let user_identity = reader.string()?; + let nominal_hash_rate = reader.f32()?; + if !nominal_hash_rate.is_finite() || nominal_hash_rate < 0.0 { + return Err(V2Error::NonFiniteRate); + } + Ok(Self { + request_id, + user_identity, + nominal_hash_rate, + max_target: reader.u256()?, + }) + } +} + +/// `OpenStandardMiningChannel.Success`. +#[derive(Clone, Debug, PartialEq)] +pub struct OpenStandardMiningChannelSuccess { + pub request_id: u32, + pub channel_id: u32, + pub target: [u8; 32], + pub extranonce_prefix: Vec, + pub group_channel_id: u32, +} + +impl OpenStandardMiningChannelSuccess { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + put_u32(&mut out, self.request_id); + put_u32(&mut out, self.channel_id); + out.extend_from_slice(&self.target); + put_bytes(&mut out, &self.extranonce_prefix); + put_u32(&mut out, self.group_channel_id); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + Ok(Self { + request_id: reader.u32()?, + channel_id: reader.u32()?, + target: reader.u256()?, + extranonce_prefix: reader.bytes(32)?, + group_channel_id: reader.u32()?, + }) + } +} + +/// `NewMiningJob` on a standard channel. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct NewMiningJob { + pub channel_id: u32, + pub job_id: u32, + /// `None` means a future job, activated by the matching `SetNewPrevHash`. + pub ntime_start: Option, + pub version: u32, + pub merkle_root: [u8; 32], +} + +impl NewMiningJob { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + put_u32(&mut out, self.channel_id); + put_u32(&mut out, self.job_id); + match self.ntime_start { + Some(ntime) => { + out.push(1); + put_u32(&mut out, ntime); + } + None => out.push(0), + } + put_u32(&mut out, self.version); + out.extend_from_slice(&self.merkle_root); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + let channel_id = reader.u32()?; + let job_id = reader.u32()?; + let ntime_start = reader.option_u32()?; + Ok(Self { + channel_id, + job_id, + ntime_start, + version: reader.u32()?, + merkle_root: reader.u256()?, + }) + } +} + +/// `SetNewPrevHash`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SetNewPrevHash { + pub channel_id: u32, + pub job_id: u32, + pub prev_hash: [u8; 32], + pub ntime_start: u32, + pub nbits: u32, +} + +impl SetNewPrevHash { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + put_u32(&mut out, self.channel_id); + put_u32(&mut out, self.job_id); + out.extend_from_slice(&self.prev_hash); + put_u32(&mut out, self.ntime_start); + put_u32(&mut out, self.nbits); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + Ok(Self { + channel_id: reader.u32()?, + job_id: reader.u32()?, + prev_hash: reader.u256()?, + ntime_start: reader.u32()?, + nbits: reader.u32()?, + }) + } +} + +/// `SubmitSharesStandard`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SubmitSharesStandard { + pub channel_id: u32, + pub sequence_number: u32, + pub job_id: u32, + pub nonce: u32, + pub ntime: u32, + pub version: u32, +} + +impl SubmitSharesStandard { + pub fn encode(&self) -> Vec { + let mut out = Vec::new(); + put_u32(&mut out, self.channel_id); + put_u32(&mut out, self.sequence_number); + put_u32(&mut out, self.job_id); + put_u32(&mut out, self.nonce); + put_u32(&mut out, self.ntime); + put_u32(&mut out, self.version); + out + } + + pub fn decode(payload: &[u8]) -> Result { + let mut reader = Reader::new(payload); + Ok(Self { + channel_id: reader.u32()?, + sequence_number: reader.u32()?, + job_id: reader.u32()?, + nonce: reader.u32()?, + ntime: reader.u32()?, + version: reader.u32()?, + }) + } +} + +fn put_u16(out: &mut Vec, value: u16) { + out.extend_from_slice(&value.to_le_bytes()); +} + +fn put_u32(out: &mut Vec, value: u32) { + out.extend_from_slice(&value.to_le_bytes()); +} + +fn put_str(out: &mut Vec, text: &str) { + let bytes = text.as_bytes(); + let length = bytes.len().min(255); + out.push(length as u8); + out.extend_from_slice(&bytes[..length]); +} + +fn put_bytes(out: &mut Vec, bytes: &[u8]) { + let length = bytes.len().min(255); + out.push(length as u8); + out.extend_from_slice(&bytes[..length]); +} + +struct Reader<'a> { + buf: &'a [u8], + at: usize, +} + +impl<'a> Reader<'a> { + fn new(buf: &'a [u8]) -> Self { + Self { buf, at: 0 } + } + + fn take(&mut self, count: usize) -> Result<&'a [u8], V2Error> { + let end = self.at.checked_add(count).ok_or(V2Error::Length)?; + if end > self.buf.len() { + return Err(V2Error::Truncated); + } + let slice = &self.buf[self.at..end]; + self.at = end; + Ok(slice) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u16(&mut self) -> Result { + let bytes = self.take(2)?; + Ok(u16::from_le_bytes([bytes[0], bytes[1]])) + } + + fn u32(&mut self) -> Result { + let bytes = self.take(4)?; + Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + fn f32(&mut self) -> Result { + Ok(f32::from_bits(self.u32()?)) + } + + fn u256(&mut self) -> Result<[u8; 32], V2Error> { + let bytes = self.take(32)?; + let mut out = [0_u8; 32]; + out.copy_from_slice(bytes); + Ok(out) + } + + fn string(&mut self) -> Result { + let length = self.u8()? as usize; + let bytes = self.take(length)?; + String::from_utf8(bytes.to_vec()).map_err(|_| V2Error::String) + } + + fn bytes(&mut self, max: usize) -> Result, V2Error> { + let length = self.u8()? as usize; + if length > max { + return Err(V2Error::Length); + } + Ok(self.take(length)?.to_vec()) + } + + fn option_u32(&mut self) -> Result, V2Error> { + match self.u8()? { + 0 => Ok(None), + 1 => Ok(Some(self.u32()?)), + _ => Err(V2Error::Length), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hash(byte: u8) -> [u8; 32] { + [byte; 32] + } + + #[test] + fn frame_header_matches_the_specification() { + let mut wire = Vec::new(); + Frame::new(SETUP_CONNECTION, vec![1, 2, 3]).encode(&mut wire); + assert_eq!(&wire[..3], &[0x00, 0x00, 0x00]); + assert_eq!(&wire[3..6], &[0x03, 0x00, 0x00]); + let (frame, consumed) = Frame::decode(&wire).expect("frame"); + assert_eq!(consumed, wire.len()); + assert_eq!(frame.msg_type, SETUP_CONNECTION); + assert_eq!(frame.payload, vec![1, 2, 3]); + } + + #[test] + fn a_truncated_frame_is_rejected() { + assert_eq!(Frame::decode(&[0, 0, 0x00]), Err(V2Error::Truncated)); + let mut wire = Vec::new(); + Frame::new(SETUP_CONNECTION, vec![9; 10]).encode(&mut wire); + assert_eq!(Frame::decode(&wire[..8]), Err(V2Error::Truncated)); + } + + #[test] + fn setup_connection_round_trips() { + let message = SetupConnection { + protocol: 0, + min_version: 2, + max_version: 2, + flags: 0b1011, + endpoint_host: "pool.example".into(), + endpoint_port: 3333, + vendor: "alkane".into(), + hardware_version: "s19jpro-bm1362".into(), + firmware: "alkane-os/0.1.0".into(), + device_id: "bench-169".into(), + }; + let wire = message.encode(); + assert_eq!(SetupConnection::decode(&wire).expect("decode"), message); + } + + #[test] + fn setup_connection_success_round_trips() { + let message = SetupConnectionSuccess { + used_version: 2, + flags: 0, + }; + assert_eq!( + SetupConnectionSuccess::decode(&message.encode()).expect("decode"), + message + ); + } + + #[test] + fn open_standard_channel_round_trips() { + let message = OpenStandardMiningChannel { + request_id: 7, + user_identity: "bc1q.example".into(), + nominal_hash_rate: 95_000_000_000_000.0, + max_target: hash(0xff), + }; + assert_eq!( + OpenStandardMiningChannel::decode(&message.encode()).expect("decode"), + message + ); + } + + #[test] + fn a_non_finite_hashrate_is_a_protocol_error() { + let message = OpenStandardMiningChannel { + request_id: 1, + user_identity: "x".into(), + nominal_hash_rate: f32::NAN, + max_target: hash(0), + }; + assert_eq!( + OpenStandardMiningChannel::decode(&message.encode()), + Err(V2Error::NonFiniteRate) + ); + let negative = OpenStandardMiningChannel { + nominal_hash_rate: -1.0, + ..message + }; + assert_eq!( + OpenStandardMiningChannel::decode(&negative.encode()), + Err(V2Error::NonFiniteRate) + ); + } + + #[test] + fn channel_success_carries_the_extranonce_prefix() { + let message = OpenStandardMiningChannelSuccess { + request_id: 7, + channel_id: 11, + target: hash(0x7f), + extranonce_prefix: vec![0xde, 0xad, 0xbe, 0xef], + group_channel_id: 0, + }; + assert_eq!( + OpenStandardMiningChannelSuccess::decode(&message.encode()).expect("decode"), + message + ); + } + + #[test] + fn new_job_round_trips_both_ntime_forms() { + let active = NewMiningJob { + channel_id: 1, + job_id: 2, + ntime_start: Some(1_700_000_000), + version: 0x2000_0000, + merkle_root: hash(0x11), + }; + assert_eq!( + NewMiningJob::decode(&active.encode()).expect("decode"), + active + ); + let future = NewMiningJob { + ntime_start: None, + ..active + }; + assert_eq!( + NewMiningJob::decode(&future.encode()).expect("decode"), + future + ); + } + + #[test] + fn set_new_prev_hash_round_trips() { + let message = SetNewPrevHash { + channel_id: 1, + job_id: 2, + prev_hash: hash(0x22), + ntime_start: 1_700_000_100, + nbits: 0x1707_0000, + }; + assert_eq!( + SetNewPrevHash::decode(&message.encode()).expect("decode"), + message + ); + } + + #[test] + fn submit_shares_round_trips() { + let message = SubmitSharesStandard { + channel_id: 3, + sequence_number: 99, + job_id: 4, + nonce: 0xdead_beef, + ntime: 1_700_000_200, + version: 0x2000_0000, + }; + assert_eq!( + SubmitSharesStandard::decode(&message.encode()).expect("decode"), + message + ); + } + + #[test] + fn a_short_payload_is_rejected_rather_than_padded() { + let wire = SubmitSharesStandard { + channel_id: 3, + sequence_number: 99, + job_id: 4, + nonce: 0, + ntime: 0, + version: 0, + } + .encode(); + assert_eq!( + SubmitSharesStandard::decode(&wire[..8]), + Err(V2Error::Truncated) + ); + } +} diff --git a/src/stratum_v2_session.rs b/src/stratum_v2_session.rs new file mode 100644 index 0000000..4fe931b --- /dev/null +++ b/src/stratum_v2_session.rs @@ -0,0 +1,553 @@ +// SPDX-License-Identifier: MIT +//! Stratum V2 session: handshake, channel, jobs and share submission. +//! +//! The codec in `stratum_v2` owns bytes; this module owns order. It drives the client half of a +//! mining connection and refuses to invent state: a job received before any `SetNewPrevHash` is +//! reported with no previous hash rather than with a zero one, and a rejected setup surfaces the +//! server's code. + +use crate::stratum_v2::{ + Frame, NewMiningJob, OpenStandardMiningChannel, SetNewPrevHash, SetupConnection, + SetupConnectionSuccess, SubmitSharesStandard, NEW_MINING_JOB, OPEN_MINING_CHANNEL_ERROR, + OPEN_STANDARD_MINING_CHANNEL, OPEN_STANDARD_MINING_CHANNEL_SUCCESS, SETUP_CONNECTION, + SETUP_CONNECTION_ERROR, SETUP_CONNECTION_SUCCESS, SET_NEW_PREV_HASH, SET_TARGET, + SUBMIT_SHARES_ERROR, SUBMIT_SHARES_STANDARD, SUBMIT_SHARES_SUCCESS, +}; + +/// A connection that carries whole frames. +pub trait V2Link { + type Error; + + fn send(&mut self, frame: &Frame) -> Result<(), Self::Error>; + fn recv(&mut self) -> Result; +} + +/// What the client declares when it connects. +#[derive(Clone, Debug, PartialEq)] +pub struct V2Config { + pub host: String, + pub port: u16, + pub flags: u32, + pub user_identity: String, + pub nominal_hash_rate: f32, + pub max_target: [u8; 32], + pub vendor: String, + pub hardware: String, + pub firmware: String, + pub device_id: String, +} + +/// An opened standard channel. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct V2Channel { + pub channel_id: u32, + pub target: [u8; 32], + pub extranonce_prefix: Vec, + pub group_channel_id: u32, +} + +/// A job the miner may work on. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct V2Job { + pub job_id: u32, + pub version: u32, + pub merkle_root: [u8; 32], + pub ntime_start: Option, + pub prev_hash: Option<[u8; 32]>, + pub nbits: Option, +} + +/// Something the server told us. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum V2Event { + Job(V2Job), + PrevHash { + job_id: u32, + prev_hash: [u8; 32], + ntime_start: u32, + nbits: u32, + }, + Target { + channel_id: u32, + target: [u8; 32], + }, + ShareAccepted { + last_sequence: u32, + accepted: u32, + }, + ShareRejected { + last_sequence: u32, + }, + Ignored, +} + +/// A protocol-level failure, without a link error inside it. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SessionError { + Protocol(&'static str), + Rejected(String), +} + +/// A failure that may have come from the transport. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ConnectError { + Link(E), + Session(SessionError), +} + +/// Run the client handshake and return the opened channel. +pub fn handshake( + link: &mut L, + config: &V2Config, +) -> Result> { + let setup = SetupConnection { + protocol: 0, + min_version: 2, + max_version: 2, + flags: config.flags, + endpoint_host: config.host.clone(), + endpoint_port: config.port, + vendor: config.vendor.clone(), + hardware_version: config.hardware.clone(), + firmware: config.firmware.clone(), + device_id: config.device_id.clone(), + }; + link.send(&Frame::new(SETUP_CONNECTION, setup.encode())) + .map_err(ConnectError::Link)?; + let reply = link.recv().map_err(ConnectError::Link)?; + match reply.msg_type { + SETUP_CONNECTION_SUCCESS => { + let _ = SetupConnectionSuccess::decode(&reply.payload) + .map_err(|_| ConnectError::Session(SessionError::Protocol("bad setup success")))?; + } + SETUP_CONNECTION_ERROR => { + return Err(ConnectError::Session(SessionError::Rejected( + setup_error_text(&reply.payload), + ))) + } + _ => { + return Err(ConnectError::Session(SessionError::Protocol( + "unexpected message before setup success", + ))) + } + } + + let open = OpenStandardMiningChannel { + request_id: 1, + user_identity: config.user_identity.clone(), + nominal_hash_rate: config.nominal_hash_rate, + max_target: config.max_target, + }; + link.send(&Frame::new(OPEN_STANDARD_MINING_CHANNEL, open.encode())) + .map_err(ConnectError::Link)?; + let reply = link.recv().map_err(ConnectError::Link)?; + match reply.msg_type { + OPEN_STANDARD_MINING_CHANNEL_SUCCESS => { + let success = + crate::stratum_v2::OpenStandardMiningChannelSuccess::decode(&reply.payload) + .map_err(|_| { + ConnectError::Session(SessionError::Protocol("bad channel success")) + })?; + if success.request_id != 1 { + return Err(ConnectError::Session(SessionError::Protocol( + "channel response does not match the request", + ))); + } + Ok(V2Channel { + channel_id: success.channel_id, + target: success.target, + extranonce_prefix: success.extranonce_prefix, + group_channel_id: success.group_channel_id, + }) + } + OPEN_MINING_CHANNEL_ERROR => Err(ConnectError::Session(SessionError::Rejected( + setup_error_text(&reply.payload), + ))), + _ => Err(ConnectError::Session(SessionError::Protocol( + "unexpected message while opening a channel", + ))), + } +} + +fn setup_error_text(payload: &[u8]) -> String { + // Error messages are a U32 flag mask followed by a STR0_255 code. + if payload.len() < 5 { + return String::from("unspecified"); + } + let length = payload[4] as usize; + payload + .get(5..5 + length) + .and_then(|bytes| std::str::from_utf8(bytes).ok()) + .unwrap_or("unspecified") + .to_owned() +} + +/// Session state after the handshake. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct V2Session { + channel: V2Channel, + prev_hash: Option<[u8; 32]>, + nbits: Option, + sequence: u32, +} + +impl V2Session { + pub fn new(channel: V2Channel) -> Self { + Self { + channel, + prev_hash: None, + nbits: None, + sequence: 0, + } + } + + pub fn channel(&self) -> &V2Channel { + &self.channel + } + + /// Interpret one server frame. + pub fn on_frame(&mut self, frame: &Frame) -> Result { + match frame.msg_type { + NEW_MINING_JOB => { + let job = NewMiningJob::decode(&frame.payload) + .map_err(|_| SessionError::Protocol("bad NewMiningJob"))?; + Ok(V2Event::Job(V2Job { + job_id: job.job_id, + version: job.version, + merkle_root: job.merkle_root, + ntime_start: job.ntime_start, + prev_hash: self.prev_hash, + nbits: self.nbits, + })) + } + SET_NEW_PREV_HASH => { + let message = SetNewPrevHash::decode(&frame.payload) + .map_err(|_| SessionError::Protocol("bad SetNewPrevHash"))?; + self.prev_hash = Some(message.prev_hash); + self.nbits = Some(message.nbits); + Ok(V2Event::PrevHash { + job_id: message.job_id, + prev_hash: message.prev_hash, + ntime_start: message.ntime_start, + nbits: message.nbits, + }) + } + SET_TARGET => { + if frame.payload.len() != 4 + 32 { + return Err(SessionError::Protocol("bad SetTarget")); + } + let channel_id = u32::from_le_bytes([ + frame.payload[0], + frame.payload[1], + frame.payload[2], + frame.payload[3], + ]); + let mut target = [0_u8; 32]; + target.copy_from_slice(&frame.payload[4..36]); + Ok(V2Event::Target { channel_id, target }) + } + SUBMIT_SHARES_SUCCESS => { + if frame.payload.len() < 20 { + return Err(SessionError::Protocol("bad SubmitShares.Success")); + } + let last_sequence = u32::from_le_bytes([ + frame.payload[4], + frame.payload[5], + frame.payload[6], + frame.payload[7], + ]); + let accepted = u32::from_le_bytes([ + frame.payload[8], + frame.payload[9], + frame.payload[10], + frame.payload[11], + ]); + Ok(V2Event::ShareAccepted { + last_sequence, + accepted, + }) + } + SUBMIT_SHARES_ERROR => { + let last_sequence = if frame.payload.len() >= 8 { + u32::from_le_bytes([ + frame.payload[0], + frame.payload[1], + frame.payload[2], + frame.payload[3], + ]) + } else { + 0 + }; + Ok(V2Event::ShareRejected { last_sequence }) + } + _ => Ok(V2Event::Ignored), + } + } + + /// Submit one standard share; returns the sequence number used. + pub fn submit( + &mut self, + link: &mut L, + job_id: u32, + nonce: u32, + ntime: u32, + version: u32, + ) -> Result> { + self.sequence = self.sequence.wrapping_add(1); + let share = SubmitSharesStandard { + channel_id: self.channel.channel_id, + sequence_number: self.sequence, + job_id, + nonce, + ntime, + version, + }; + link.send(&Frame::new(SUBMIT_SHARES_STANDARD, share.encode())) + .map_err(ConnectError::Link)?; + Ok(self.sequence) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::VecDeque; + + struct Scripted { + incoming: VecDeque, + sent: Vec, + } + + impl Scripted { + fn new(incoming: Vec) -> Self { + Self { + incoming: incoming.into(), + sent: Vec::new(), + } + } + } + + impl V2Link for Scripted { + type Error = (); + + fn send(&mut self, frame: &Frame) -> Result<(), ()> { + self.sent.push(frame.clone()); + Ok(()) + } + + fn recv(&mut self) -> Result { + self.incoming.pop_front().ok_or(()) + } + } + + fn config() -> V2Config { + V2Config { + host: "pool.example".into(), + port: 3333, + flags: 0, + user_identity: "worker".into(), + nominal_hash_rate: 1.0e14, + max_target: [0xff; 32], + vendor: "alkane".into(), + hardware: "bench".into(), + firmware: "alkane-os".into(), + device_id: "bench-1".into(), + } + } + + fn setup_success() -> Frame { + Frame::new( + SETUP_CONNECTION_SUCCESS, + SetupConnectionSuccess { + used_version: 2, + flags: 0, + } + .encode(), + ) + } + + fn channel_success() -> Frame { + Frame::new( + OPEN_STANDARD_MINING_CHANNEL_SUCCESS, + crate::stratum_v2::OpenStandardMiningChannelSuccess { + request_id: 1, + channel_id: 9, + target: [0x7f; 32], + extranonce_prefix: vec![1, 2], + group_channel_id: 0, + } + .encode(), + ) + } + + #[test] + fn handshake_sends_setup_then_open_and_returns_the_channel() { + let mut link = Scripted::new(vec![setup_success(), channel_success()]); + let channel = handshake(&mut link, &config()).expect("handshake"); + assert_eq!(channel.channel_id, 9); + assert_eq!(channel.extranonce_prefix, vec![1, 2]); + assert_eq!(link.sent.len(), 2); + assert_eq!(link.sent[0].msg_type, SETUP_CONNECTION); + assert_eq!(link.sent[1].msg_type, OPEN_STANDARD_MINING_CHANNEL); + let open = OpenStandardMiningChannel::decode(&link.sent[1].payload).expect("open"); + assert_eq!(open.user_identity, "worker"); + assert_eq!(open.request_id, 1); + } + + #[test] + fn a_setup_error_surfaces_the_server_code() { + let mut payload = 0_u32.to_le_bytes().to_vec(); + payload.push(3); + payload.extend_from_slice(b"bad"); + let mut link = Scripted::new(vec![Frame::new(SETUP_CONNECTION_ERROR, payload)]); + assert_eq!( + handshake(&mut link, &config()), + Err(ConnectError::Session(SessionError::Rejected("bad".into()))) + ); + } + + #[test] + fn an_unexpected_message_during_setup_is_a_protocol_error() { + let mut link = Scripted::new(vec![Frame::new(NEW_MINING_JOB, vec![0; 44])]); + assert_eq!( + handshake(&mut link, &config()), + Err(ConnectError::Session(SessionError::Protocol( + "unexpected message before setup success" + ))) + ); + } + + #[test] + fn a_job_before_any_prev_hash_has_no_prev_hash() { + let mut session = V2Session::new(V2Channel { + channel_id: 9, + target: [0xff; 32], + extranonce_prefix: Vec::new(), + group_channel_id: 0, + }); + let job = NewMiningJob { + channel_id: 9, + job_id: 1, + ntime_start: Some(1_700_000_000), + version: 0x2000_0000, + merkle_root: [0x11; 32], + }; + let event = session + .on_frame(&Frame::new(NEW_MINING_JOB, job.encode())) + .expect("job"); + match event { + V2Event::Job(parsed) => { + assert_eq!(parsed.job_id, 1); + assert_eq!(parsed.prev_hash, None); + assert_eq!(parsed.nbits, None); + } + other => panic!("unexpected event: {other:?}"), + } + } + + #[test] + fn prev_hash_is_remembered_for_later_jobs() { + let mut session = V2Session::new(V2Channel { + channel_id: 9, + target: [0xff; 32], + extranonce_prefix: Vec::new(), + group_channel_id: 0, + }); + let prev = SetNewPrevHash { + channel_id: 9, + job_id: 1, + prev_hash: [0x22; 32], + ntime_start: 1_700_000_100, + nbits: 0x1707_0000, + }; + session + .on_frame(&Frame::new(SET_NEW_PREV_HASH, prev.encode())) + .expect("prev hash"); + let job = NewMiningJob { + channel_id: 9, + job_id: 2, + ntime_start: None, + version: 0x2000_0000, + merkle_root: [0x33; 32], + }; + match session + .on_frame(&Frame::new(NEW_MINING_JOB, job.encode())) + .expect("job") + { + V2Event::Job(parsed) => { + assert_eq!(parsed.prev_hash, Some([0x22; 32])); + assert_eq!(parsed.nbits, Some(0x1707_0000)); + assert_eq!(parsed.ntime_start, None); + } + other => panic!("unexpected event: {other:?}"), + } + } + + #[test] + fn submissions_use_the_channel_and_increasing_sequence_numbers() { + let mut session = V2Session::new(V2Channel { + channel_id: 9, + target: [0xff; 32], + extranonce_prefix: Vec::new(), + group_channel_id: 0, + }); + let mut link = Scripted::new(Vec::new()); + assert_eq!( + session + .submit(&mut link, 1, 0xabcd, 1_700_000_000, 0x2000_0000) + .expect("submit"), + 1 + ); + assert_eq!( + session + .submit(&mut link, 1, 0xabce, 1_700_000_000, 0x2000_0000) + .expect("submit"), + 2 + ); + assert_eq!(link.sent.len(), 2); + let first = SubmitSharesStandard::decode(&link.sent[0].payload).expect("share"); + assert_eq!(first.channel_id, 9); + assert_eq!(first.sequence_number, 1); + assert_eq!(first.nonce, 0xabcd); + } + + #[test] + fn share_success_reports_the_last_sequence() { + let mut session = V2Session::new(V2Channel { + channel_id: 9, + target: [0xff; 32], + extranonce_prefix: Vec::new(), + group_channel_id: 0, + }); + let mut payload = Vec::new(); + payload.extend_from_slice(&9_u32.to_le_bytes()); + payload.extend_from_slice(&7_u32.to_le_bytes()); + payload.extend_from_slice(&3_u32.to_le_bytes()); + payload.extend_from_slice(&0_u64.to_le_bytes()); + assert_eq!( + session + .on_frame(&Frame::new(SUBMIT_SHARES_SUCCESS, payload)) + .expect("event"), + V2Event::ShareAccepted { + last_sequence: 7, + accepted: 3 + } + ); + } + + #[test] + fn an_unknown_message_is_ignored_not_fatal() { + let mut session = V2Session::new(V2Channel { + channel_id: 9, + target: [0xff; 32], + extranonce_prefix: Vec::new(), + group_channel_id: 0, + }); + assert_eq!( + session + .on_frame(&Frame::new(0x7e, vec![0; 4])) + .expect("event"), + V2Event::Ignored + ); + } +} diff --git a/src/tuning.rs b/src/tuning.rs new file mode 100644 index 0000000..48d92e1 --- /dev/null +++ b/src/tuning.rs @@ -0,0 +1,506 @@ +// SPDX-License-Identifier: MIT +//! Adaptive tuning. +//! +//! The miner targets a power draw, a hashrate, or an operating point chosen for the ambient +//! temperature. Rather than picking a preset, a bounded PID moves the chain frequency inside the +//! profile envelope each control period, and a thermal guard can always override it downward. +//! +//! The controller is deliberately conservative: bounded output, rate limit, deadband, derivative +//! on the measurement (no setpoint kick) and conditional integration (no windup while saturated). + +use crate::detect::Envelope; + +/// What the operator asked for. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum TuningTarget { + /// Hold this DC power draw; efficiency follows from the power point. + PowerW(f32), + /// Maximise hashrate up to this value. + HashrateThs(f32), + /// Hold the hottest sensor this far above the measured ambient: efficiency at that ambient. + AmbientC { margin_mc: i32 }, + /// Pin the fan at this duty and maximise hashrate under it. + MaxFan { max_pwm: u8 }, +} + +/// Controller tuning. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PidConfig { + pub kp: f32, + pub ki: f32, + pub kd: f32, + pub out_min: f32, + pub out_max: f32, + /// Maximum output change per second. + pub max_step_per_s: f32, + /// Errors inside this band are ignored. + pub deadband: f32, +} + +impl Default for PidConfig { + fn default() -> Self { + Self { + kp: 0.5, + ki: 0.1, + kd: 0.0, + out_min: 0.0, + out_max: 1_000.0, + max_step_per_s: 50.0, + deadband: 1.0, + } + } +} + +/// A bounded PID with anti-windup and rate limiting. +#[derive(Clone, Debug)] +pub struct Pid { + config: PidConfig, + integral: f32, + last_measurement: Option, + output: f32, +} + +impl Pid { + pub fn new(config: PidConfig, initial_output: f32) -> Self { + Self { + config, + integral: 0.0, + last_measurement: None, + output: initial_output.clamp(config.out_min, config.out_max), + } + } + + pub fn output(&self) -> f32 { + self.output + } + + /// Force the output (used by ramp modes and the thermal guard). + pub fn set_output(&mut self, value: f32) { + self.output = value.clamp(self.config.out_min, self.config.out_max); + } + + /// Advance one control period and return the new output. + pub fn update(&mut self, setpoint: f32, measurement: f32, dt_s: f32) -> f32 { + if !dt_s.is_finite() || dt_s <= 0.0 { + return self.output; + } + let error = setpoint - measurement; + if error.abs() <= self.config.deadband { + self.last_measurement = Some(measurement); + return self.output; + } + let derivative = match self.last_measurement { + Some(previous) => -(measurement - previous) / dt_s, + None => 0.0, + }; + let candidate = self.config.kp * error + self.integral + self.config.kd * derivative; + let saturated = candidate > self.config.out_max || candidate < self.config.out_min; + // Conditional integration: never accumulate while the actuator is pinned in the direction + // of the error, or the loop unwinds slowly after a saturation episode. + let pinning = (candidate > self.config.out_max && error > 0.0) + || (candidate < self.config.out_min && error < 0.0); + if !saturated || !pinning { + self.integral += self.config.ki * error * dt_s; + } + let mut desired = self.config.kp * error + self.integral + self.config.kd * derivative; + desired = desired.clamp(self.config.out_min, self.config.out_max); + let max_step = self.config.max_step_per_s * dt_s; + let step = (desired - self.output).clamp(-max_step, max_step); + self.output = (self.output + step).clamp(self.config.out_min, self.config.out_max); + self.last_measurement = Some(measurement); + self.output + } +} + +/// What the loop needs to know each period. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Observation { + pub power_w: Option, + pub hashrate_ths: Option, + /// Hottest sensor in millidegrees, when telemetry is available. + pub hottest_mc: Option, + /// Intake/enclosure temperature in millidegrees, for the ambient target. + pub ambient_mc: Option, +} + +/// What the loop wants applied this period. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Command { + pub frequency_mhz: u16, + /// `Some` only when the target owns the fan (max-fan mode). + pub fan_pwm: Option, +} + +/// Why the loop could not produce a command. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TuningError { + /// The measurement the target needs is missing this period. + NoMeasurement, +} + +/// The tuning loop: one PID over chain frequency, bounded by the profile envelope. +#[derive(Clone, Debug)] +pub struct TuningLoop { + pid: Pid, + envelope: Envelope, + target: TuningTarget, + ceiling_mc: i32, +} + +impl TuningLoop { + /// Start from the conservative floor of the envelope. + pub fn new(target: TuningTarget, envelope: Envelope, pid: PidConfig, ceiling_mc: i32) -> Self { + let config = PidConfig { + out_min: f32::from(envelope.f_min_mhz), + out_max: f32::from(envelope.f_max_mhz), + ..pid + }; + let start = f32::from(envelope.f_min_mhz); + Self { + pid: Pid::new(config, start), + envelope, + target, + ceiling_mc, + } + } + + pub fn frequency_mhz(&self) -> u16 { + self.pid.output().round() as u16 + } + + /// Fan duty implied by the target, if the target owns the fan. + fn target_fan(&self) -> Option { + match self.target { + TuningTarget::MaxFan { max_pwm } => Some(max_pwm), + _ => None, + } + } + + fn command(&self) -> Command { + Command { + frequency_mhz: self.frequency_mhz(), + fan_pwm: self.target_fan(), + } + } + + /// One control period. Returns the command to apply, inside the envelope. + pub fn step(&mut self, observation: Observation, dt_s: f32) -> Result { + // Thermal guard: a hot sensor always derates, whatever the target says. + if let Some(hottest) = observation.hottest_mc { + if hottest >= self.ceiling_mc { + let derated = (self.pid.output() - 25.0).max(f32::from(self.envelope.f_min_mhz)); + self.pid = Pid::new( + PidConfig { + out_min: f32::from(self.envelope.f_min_mhz), + out_max: f32::from(self.envelope.f_max_mhz), + ..self.pid.config + }, + derated, + ); + return Ok(self.command()); + } + } + match self.target { + TuningTarget::PowerW(setpoint) => { + let measurement = observation.power_w.ok_or(TuningError::NoMeasurement)?; + self.pid.update(setpoint, measurement, dt_s); + } + TuningTarget::HashrateThs(setpoint) => { + let measurement = observation.hashrate_ths.ok_or(TuningError::NoMeasurement)?; + self.pid.update(setpoint, measurement, dt_s); + } + TuningTarget::AmbientC { margin_mc } => { + let ambient = observation.ambient_mc.ok_or(TuningError::NoMeasurement)?; + let hottest = observation.hottest_mc.ok_or(TuningError::NoMeasurement)?; + let setpoint = ambient as f32 + margin_mc as f32; + self.pid.update(setpoint, hottest as f32, dt_s); + } + TuningTarget::MaxFan { .. } => { + // No setpoint loop here: ramp toward the envelope ceiling and let the thermal + // guard be the only thing that stops it. + let step = self.pid.config.max_step_per_s * dt_s; + let next = (self.pid.output() + step).min(f32::from(self.envelope.f_max_mhz)); + self.pid.set_output(next); + } + } + Ok(self.command()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn envelope() -> Envelope { + Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + } + } + + fn observation(hottest: i32) -> Observation { + Observation { + power_w: None, + hashrate_ths: None, + hottest_mc: Some(hottest), + ambient_mc: None, + } + } + + #[test] + fn pid_drives_the_plant_to_the_setpoint() { + let mut pid = Pid::new( + PidConfig { + kp: 0.02, + ki: 0.01, + kd: 0.0, + out_min: 0.0, + out_max: 700.0, + max_step_per_s: 1_000.0, + deadband: 0.0, + }, + 0.0, + ); + // Plant: 5 W per MHz, so 3 kW needs 600 MHz, inside the controller ceiling. + let mut power = 0.0_f32; + for _ in 0..400 { + let freq = pid.update(3_000.0, power, 1.0); + power = 5.0 * freq; + } + assert!((power - 3_000.0).abs() < 50.0, "power settled at {power}"); + } + + #[test] + fn output_is_rate_limited() { + let mut pid = Pid::new( + PidConfig { + kp: 1.0, + ki: 0.0, + kd: 0.0, + out_min: 0.0, + out_max: 1_000.0, + max_step_per_s: 10.0, + deadband: 0.0, + }, + 0.0, + ); + assert!((pid.update(1_000.0, 0.0, 1.0) - 10.0).abs() < f32::EPSILON); + assert!((pid.update(1_000.0, 0.0, 1.0) - 20.0).abs() < f32::EPSILON); + } + + #[test] + fn deadband_holds_the_output() { + let mut pid = Pid::new( + PidConfig { + kp: 1.0, + ki: 0.1, + kd: 0.0, + out_min: 0.0, + out_max: 1_000.0, + max_step_per_s: 100.0, + deadband: 5.0, + }, + 100.0, + ); + let before = pid.output(); + assert!((pid.update(102.0, 100.0, 1.0) - before).abs() < f32::EPSILON); + } + + #[test] + fn saturation_does_not_wind_up_the_integral() { + let mut pid = Pid::new( + PidConfig { + kp: 1.0, + ki: 1.0, + kd: 0.0, + out_min: 0.0, + out_max: 100.0, + max_step_per_s: 1_000.0, + deadband: 0.0, + }, + 0.0, + ); + for _ in 0..100 { + pid.update(1_000.0, 0.0, 1.0); + } + assert!((pid.output() - 100.0).abs() < 0.01); + for _ in 0..5 { + pid.update(0.0, 200.0, 1.0); + } + assert!( + pid.output() < 99.0, + "output stuck at the rail: {}", + pid.output() + ); + } + + #[test] + fn power_target_moves_frequency_inside_the_envelope() { + let mut loop_ = TuningLoop::new( + TuningTarget::PowerW(2_400.0), + envelope(), + PidConfig { + kp: 0.2, + ki: 0.05, + kd: 0.0, + out_min: 0.0, + out_max: 0.0, + max_step_per_s: 50.0, + deadband: 0.0, + }, + 95_000, + ); + let mut freq = loop_.frequency_mhz(); + for _ in 0..100 { + let power = 4.0 * f32::from(freq); + let mut obs = observation(70_000); + obs.power_w = Some(power); + freq = loop_.step(obs, 1.0).expect("step").frequency_mhz; + assert!((300..=700).contains(&freq), "out of envelope: {freq}"); + } + let power = 4.0 * f32::from(freq); + assert!((power - 2_400.0).abs() < 200.0, "power settled at {power}"); + } + + #[test] + fn thermal_guard_derates_regardless_of_target() { + let mut loop_ = TuningLoop::new( + TuningTarget::HashrateThs(200.0), + envelope(), + PidConfig::default(), + 90_000, + ); + for _ in 0..50 { + let mut obs = observation(60_000); + obs.hashrate_ths = Some(10.0); + loop_.step(obs, 1.0).expect("step"); + } + let hot = loop_.frequency_mhz(); + let mut obs = observation(91_000); + obs.hashrate_ths = Some(10.0); + let derated = loop_.step(obs, 1.0).expect("step").frequency_mhz; + assert!( + derated < hot, + "thermal guard did not derate: {derated} vs {hot}" + ); + } + + #[test] + fn missing_measurement_is_an_error() { + let mut loop_ = TuningLoop::new( + TuningTarget::PowerW(3_000.0), + envelope(), + PidConfig::default(), + 95_000, + ); + let mut obs = observation(50_000); + obs.hashrate_ths = Some(1.0); + assert_eq!(loop_.step(obs, 1.0), Err(TuningError::NoMeasurement)); + } + + #[test] + fn zero_dt_holds_the_output() { + let mut pid = Pid::new(PidConfig::default(), 42.0); + assert!((pid.update(100.0, 0.0, 0.0) - 42.0).abs() < f32::EPSILON); + } + + #[test] + fn ambient_target_holds_the_hottest_sensor_near_ambient_plus_margin() { + let mut loop_ = TuningLoop::new( + TuningTarget::AmbientC { margin_mc: 20_000 }, + envelope(), + PidConfig { + kp: 0.5, + ki: 0.05, + kd: 0.0, + out_min: 0.0, + out_max: 0.0, + max_step_per_s: 50.0, + deadband: 0.0, + }, + 200_000, + ); + // Plant: hottest = ambient + 50 mC per MHz. + let ambient = 40_000; + let mut freq = loop_.frequency_mhz(); + for _ in 0..300 { + let hottest = ambient + 50 * i32::from(freq); + let obs = Observation { + power_w: None, + hashrate_ths: None, + hottest_mc: Some(hottest), + ambient_mc: Some(ambient), + }; + freq = loop_.step(obs, 1.0).expect("step").frequency_mhz; + } + let hottest = ambient + 50 * i32::from(freq); + assert!( + (hottest - (ambient + 20_000)).abs() < 2_000, + "hottest settled at {hottest}" + ); + } + + #[test] + fn ambient_target_needs_an_ambient_sensor() { + let mut loop_ = TuningLoop::new( + TuningTarget::AmbientC { margin_mc: 20_000 }, + envelope(), + PidConfig::default(), + 95_000, + ); + assert_eq!( + loop_.step(observation(50_000), 1.0), + Err(TuningError::NoMeasurement) + ); + } + + #[test] + fn max_fan_mode_pins_the_fan_and_ramps_frequency() { + let ramp = PidConfig { + kp: 1.0, + ki: 0.0, + kd: 0.0, + out_min: 0.0, + out_max: 0.0, + max_step_per_s: 50.0, + deadband: 0.0, + }; + let mut loop_ = TuningLoop::new( + TuningTarget::MaxFan { max_pwm: 100 }, + envelope(), + ramp, + 120_000, + ); + let start = loop_.frequency_mhz(); + let mut last = start; + for _ in 0..20 { + let command = loop_.step(observation(70_000), 1.0).expect("step"); + assert_eq!(command.fan_pwm, Some(100)); + last = command.frequency_mhz; + } + assert!(last > start, "frequency did not ramp: {last} vs {start}"); + assert!( + last == 700, + "ramp did not reach the envelope ceiling: {last}" + ); + } + + #[test] + fn max_fan_mode_still_respects_the_temperature_ceiling() { + let mut loop_ = TuningLoop::new( + TuningTarget::MaxFan { max_pwm: 100 }, + envelope(), + PidConfig::default(), + 80_000, + ); + for _ in 0..50 { + loop_.step(observation(70_000), 1.0).expect("step"); + } + let hot = loop_.frequency_mhz(); + let command = loop_.step(observation(85_000), 1.0).expect("step"); + assert!(command.frequency_mhz < hot); + assert_eq!(command.fan_pwm, Some(100)); + } +} diff --git a/src/web.rs b/src/web.rs new file mode 100644 index 0000000..7e9ac54 --- /dev/null +++ b/src/web.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: MIT +//! On-box web UI. +//! +//! A small HTTP surface served by the miner itself: a single page that polls the JSON API, plus +//! the API routes it uses. The API stays the interface of record; the page is a convenience, so a +//! client that only speaks JSON loses nothing. +//! +//! No framework and no dependency: the request parser is bounded, only `GET` is accepted, and every +//! response closes the connection. + +use crate::management::MiningStatus; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::Arc; +use std::time::Duration; + +const MAX_REQUEST_BYTES: usize = 2048; +const CLIENT_TIMEOUT: Duration = Duration::from_millis(500); + +const PAGE: &str = r#" + + + +Alkane miner + + + +

Alkane miner

+
loading
+ + + +"#; + +/// Bind and serve until the listener fails. +pub fn serve(bind: SocketAddr, status: Arc) -> io::Result<()> { + let listener = TcpListener::bind(bind)?; + serve_listener(listener, status) +} + +/// Serve on an already-bound listener. +pub fn serve_listener(listener: TcpListener, status: Arc) -> io::Result<()> { + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let status = Arc::clone(&status); + // Each connection is short, bounded and closes itself. + std::thread::spawn(move || { + let _ = handle(stream, &status); + }); + } + Ok(()) +} + +/// Handle one HTTP request. +pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> { + stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; + stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; + let mut request = Vec::new(); + let mut chunk = [0_u8; 512]; + loop { + let count = stream.read(&mut chunk)?; + if count == 0 { + break; + } + request.extend_from_slice(&chunk[..count]); + if request.len() > MAX_REQUEST_BYTES { + return respond(&mut stream, 431, "text/plain", b"request too large"); + } + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let head = String::from_utf8_lossy(&request); + let mut parts = head.lines().next().unwrap_or("").split_whitespace(); + let method = parts.next().unwrap_or(""); + let path = parts.next().unwrap_or(""); + if method != "GET" { + return respond(&mut stream, 405, "text/plain", b"method not allowed"); + } + match path { + "/" | "/index.html" => respond( + &mut stream, + 200, + "text/html; charset=utf-8", + PAGE.as_bytes(), + ), + "/api/hardware" => { + let body = status.hardware_document().to_string(); + respond(&mut stream, 200, "application/json", body.as_bytes()) + } + "/api/summary" => { + let body = status.summary_document().to_string(); + respond(&mut stream, 200, "application/json", body.as_bytes()) + } + _ => respond(&mut stream, 404, "text/plain", b"not found"), + } +} + +fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> io::Result<()> { + let reason = match code { + 200 => "OK", + 404 => "Not Found", + 405 => "Method Not Allowed", + 431 => "Request Header Fields Too Large", + _ => "Error", + }; + let header = format!( + "HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n", + body.len() + ); + stream.write_all(header.as_bytes())?; + stream.write_all(body)?; + stream.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::detect::{ + ChainReport, ChipModel, EepromState, Envelope, HardwarePlan, OperatingPoint, + }; + use crate::management::HardwareSnapshot; + use std::net::TcpStream as Client; + + fn status() -> Arc { + let status = MiningStatus::new(); + status.set_hardware(HardwareSnapshot { + plan: HardwarePlan { + profile: "s19jpro-bm1362-pic".into(), + chip: ChipModel::Bm1362, + chains: vec![ChainReport { + index: 0, + chip: ChipModel::Bm1362, + chips_found: 126, + eeprom: EepromState::Absent, + response_per_mille: Some(950), + }], + envelope: Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + operating_point: OperatingPoint { + voltage_mv: 1200, + frequency_mhz: 500, + confirmed: false, + }, + psu: "APW12".into(), + fan_zones: Vec::new(), + }, + active_chains: vec![0], + stopped: None, + frequency_mhz: 512, + target: "power:3000".into(), + }); + Arc::new(status) + } + + fn request(path: &str) -> String { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + let status = status(); + let worker = std::thread::spawn(move || { + let (stream, _) = listener.accept().expect("accept"); + handle(stream, &status).expect("handle"); + }); + let mut client = Client::connect(address).expect("connect"); + client + .write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes()) + .expect("write"); + let mut reply = String::new(); + client.read_to_string(&mut reply).expect("read"); + worker.join().expect("join"); + reply + } + + #[test] + fn the_page_is_served_at_root() { + let reply = request("/"); + assert!(reply.starts_with("HTTP/1.1 200 OK")); + assert!(reply.contains("text/html")); + assert!(reply.contains("Alkane miner")); + } + + #[test] + fn the_api_returns_the_hardware_document() { + let reply = request("/api/hardware"); + assert!(reply.starts_with("HTTP/1.1 200 OK")); + assert!(reply.contains("application/json")); + assert!(reply.contains("s19jpro-bm1362-pic")); + assert!(reply.contains("bm1362")); + } + + #[test] + fn unknown_paths_are_404() { + let reply = request("/nope"); + assert!(reply.starts_with("HTTP/1.1 404 Not Found")); + } + + #[test] + fn only_get_is_accepted() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("addr"); + let status = status(); + let worker = std::thread::spawn(move || { + let (stream, _) = listener.accept().expect("accept"); + handle(stream, &status).expect("handle"); + }); + let mut client = Client::connect(address).expect("connect"); + client + .write_all(b"POST / HTTP/1.1\r\nHost: miner\r\nContent-Length: 0\r\n\r\n") + .expect("write"); + let mut reply = String::new(); + client.read_to_string(&mut reply).expect("read"); + worker.join().expect("join"); + assert!(reply.starts_with("HTTP/1.1 405 Method Not Allowed")); + } +}