This commit is contained in:
@@ -11,15 +11,14 @@
|
||||

|
||||
|
||||
Mining and tuning core for Alkane control boards. The SDK builds board images
|
||||
and supplies the hardware backend. Management is planned over SSH, a
|
||||
cgminer-compatible port 4028, and a minimal API; no web frontend runs on the
|
||||
board.
|
||||
and supplies the hardware backend. Management uses SSH and an optional local,
|
||||
read-only cgminer-style status endpoint; no web frontend runs on the board.
|
||||
|
||||
## Status
|
||||
|
||||
The CLI lists target obligations with `alkane-os --list-targets`. It can also
|
||||
mine through the SDK simulator HAL and a Stratum V1 pool. No production board
|
||||
backend or network management API is installed.
|
||||
backend is installed.
|
||||
|
||||
The library has a versioned Unix-socket HAL client, BM1362 and BM1366
|
||||
host mining sessions, Stratum V1 job and share handling, SHA-256d share
|
||||
@@ -44,6 +43,12 @@ Select `BM1362` for that chip's captured job format. The optional argument
|
||||
after the chip stops after that many accepted shares. The command
|
||||
uses the simulator's 80 C temperature limit and exits on a pool or hardware
|
||||
fault. The SDK HAL server must cut power when its client stalls or disconnects.
|
||||
Set `ALKANE_API_LISTEN=127.0.0.1:4028` to expose read-only `summary` and
|
||||
`version` commands during simulator mining. The endpoint accepts cgminer
|
||||
JSON requests or plain command names and ends replies with a NUL byte.
|
||||
It binds only to loopback; access from another machine through SSH. The
|
||||
summary reports observed accepted/rejected shares and process state, without
|
||||
an estimated hashrate. Other cgminer API commands are not yet implemented.
|
||||
|
||||
## Release gate
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ pub mod bm1366;
|
||||
pub mod bm13xx;
|
||||
pub mod difficulty;
|
||||
pub mod hal_wire;
|
||||
pub mod management;
|
||||
pub mod miner;
|
||||
pub mod pow;
|
||||
pub mod scrypt_pow;
|
||||
|
||||
+19
-1
@@ -1,11 +1,13 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
use alkane_os::hal_wire::HalClient;
|
||||
use alkane_os::management::{bind_local, serve, MiningStatus};
|
||||
use alkane_os::miner::{Bm1366Miner, ChipModel};
|
||||
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
|
||||
use alkane_os::target_matrix;
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
||||
@@ -23,6 +25,16 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
}
|
||||
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}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Connect to the pool before enabling power. The SDK HAL server owns the
|
||||
// power lease and cuts power if this process stalls or disconnects.
|
||||
@@ -39,6 +51,7 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
let mut miner = Bm1366Miner::new_for_chip(&mut backend, chip, 0, 0, 0, 100, 80_000)
|
||||
.ok_or("invalid simulator safety configuration")?;
|
||||
miner.start()?;
|
||||
status.set_running(true);
|
||||
let mut accepted = 0_u64;
|
||||
loop {
|
||||
let (event, reports) = pool
|
||||
@@ -47,13 +60,18 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
match event {
|
||||
PoolEvent::ShareAccepted(_) => {
|
||||
accepted += 1;
|
||||
status.share_accepted();
|
||||
if max_accepts == Some(accepted) {
|
||||
miner.stop()?;
|
||||
status.set_running(false);
|
||||
println!("simulator shares accepted: {accepted}");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
PoolEvent::ShareRejected(id) => eprintln!("pool rejected share request {id}"),
|
||||
PoolEvent::ShareRejected(id) => {
|
||||
status.share_rejected();
|
||||
eprintln!("pool rejected share request {id}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if matches!(event, PoolEvent::Idle) && reports.is_empty() {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Bounded, read-only cgminer-style status for a local management client.
|
||||
|
||||
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::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
const MAX_REQUEST_BYTES: usize = 2048;
|
||||
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MiningStatus {
|
||||
started: Instant,
|
||||
running: AtomicBool,
|
||||
accepted: AtomicU64,
|
||||
rejected: AtomicU64,
|
||||
}
|
||||
|
||||
impl Default for MiningStatus {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl MiningStatus {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
started: Instant::now(),
|
||||
running: AtomicBool::new(false),
|
||||
accepted: AtomicU64::new(0),
|
||||
rejected: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_running(&self, running: bool) {
|
||||
self.running.store(running, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn share_accepted(&self) {
|
||||
self.accepted.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn share_rejected(&self) {
|
||||
self.rejected.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn response(&self, command: &str) -> Value {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
let (code, description, payload) = match command {
|
||||
"summary" => (
|
||||
"S",
|
||||
"Summary",
|
||||
json!({"SUMMARY": [{
|
||||
"Elapsed": self.started.elapsed().as_secs(),
|
||||
"Accepted": self.accepted.load(Ordering::Relaxed),
|
||||
"Rejected": self.rejected.load(Ordering::Relaxed),
|
||||
"Status": if self.running.load(Ordering::Relaxed) { "Mining" } else { "Stopped" }
|
||||
}]}),
|
||||
),
|
||||
"version" => (
|
||||
"S",
|
||||
"Version",
|
||||
json!({"VERSION": [{
|
||||
"Miner": concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
|
||||
"API": "1.0"
|
||||
}]}),
|
||||
),
|
||||
_ => ("E", "Unknown command", json!({})),
|
||||
};
|
||||
let mut response = json!({"STATUS": [{
|
||||
"STATUS": code,
|
||||
"When": now,
|
||||
"Code": if code == "S" { 0 } else { 14 },
|
||||
"Msg": description,
|
||||
"Description": "alkane-os"
|
||||
}]});
|
||||
response
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(payload.as_object().unwrap().clone());
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
fn request_command(bytes: &[u8]) -> Option<&str> {
|
||||
let request = std::str::from_utf8(bytes).ok()?.trim();
|
||||
if request.starts_with('{') {
|
||||
let value: Value = serde_json::from_str(request).ok()?;
|
||||
let command = value.get("command")?.as_str()?;
|
||||
match command {
|
||||
"summary" => Some("summary"),
|
||||
"version" => Some("version"),
|
||||
_ => Some("unknown"),
|
||||
}
|
||||
} else {
|
||||
match request {
|
||||
"summary" => Some("summary"),
|
||||
"version" => Some("version"),
|
||||
_ => Some("unknown"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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; 256];
|
||||
loop {
|
||||
let count = match stream.read(&mut chunk) {
|
||||
Ok(count) => count,
|
||||
Err(error) if error.kind() == io::ErrorKind::TimedOut && !request.is_empty() => break,
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock && !request.is_empty() => break,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
if request.len() + count > MAX_REQUEST_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"management request too large",
|
||||
));
|
||||
}
|
||||
request.extend_from_slice(&chunk[..count]);
|
||||
if request.contains(&b'\n') || request.contains(&0) {
|
||||
break;
|
||||
}
|
||||
if matches!(request_command(&request), Some("summary" | "version"))
|
||||
|| serde_json::from_slice::<Value>(&request).is_ok()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = request
|
||||
.iter()
|
||||
.position(|byte| *byte == 0 || *byte == b'\n')
|
||||
.unwrap_or(request.len());
|
||||
let command = request_command(&request[..end]).unwrap_or("unknown");
|
||||
let mut reply = serde_json::to_vec(&status.response(command)).map_err(io::Error::other)?;
|
||||
reply.push(0);
|
||||
stream.write_all(&reply)
|
||||
}
|
||||
|
||||
/// Bind only to loopback. The board management plane can be reached through SSH.
|
||||
pub fn bind_local(address: SocketAddr) -> io::Result<TcpListener> {
|
||||
if !address.ip().is_loopback() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"management API requires loopback address",
|
||||
));
|
||||
}
|
||||
TcpListener::bind(address)
|
||||
}
|
||||
|
||||
pub fn serve(listener: TcpListener, status: Arc<MiningStatus>) -> io::Result<()> {
|
||||
for stream in listener.incoming() {
|
||||
let stream = stream?;
|
||||
if let Err(error) = handle(stream, &status) {
|
||||
eprintln!("management request failed: {error}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::TcpStream;
|
||||
|
||||
#[test]
|
||||
fn refuses_nonlocal_bind() {
|
||||
let address = "0.0.0.0:0".parse().unwrap();
|
||||
assert_eq!(
|
||||
bind_local(address).unwrap_err().kind(),
|
||||
io::ErrorKind::InvalidInput
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_only_observed_share_counts() {
|
||||
let status = MiningStatus::new();
|
||||
status.set_running(true);
|
||||
status.share_accepted();
|
||||
status.share_rejected();
|
||||
let reply = status.response("summary");
|
||||
assert_eq!(reply["SUMMARY"][0]["Accepted"], 1);
|
||||
assert_eq!(reply["SUMMARY"][0]["Rejected"], 1);
|
||||
assert_eq!(reply["SUMMARY"][0]["Status"], "Mining");
|
||||
assert!(reply["SUMMARY"][0].get("MHS av").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_socket_uses_nul_terminated_cgminer_envelope() {
|
||||
let listener = bind_local("127.0.0.1:0".parse().unwrap()).unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
let worker = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
handle(stream, &status).unwrap();
|
||||
});
|
||||
let mut client = TcpStream::connect(address).unwrap();
|
||||
client.write_all(b"{\"command\":\"summary\"}\n").unwrap();
|
||||
let mut reply = Vec::new();
|
||||
client.read_to_end(&mut reply).unwrap();
|
||||
assert_eq!(reply.pop(), Some(0));
|
||||
let parsed: Value = serde_json::from_slice(&reply).unwrap();
|
||||
assert_eq!(parsed["STATUS"][0]["STATUS"], "S");
|
||||
assert_eq!(parsed["SUMMARY"][0]["Status"], "Stopped");
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user