diff --git a/README.md b/README.md index f8de511..a4092d4 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,15 @@ now includes a versioned local Unix-socket client for the SDK hardware backend, with bounded frames, two-second I/O timeouts, and fail-closed response validation. The matching SDK server framing library exists, but no board adapter is installed in an image yet. +The library can also verify an ASIC-reported SHA-256d share against an exact +pool target, including BM13xx version rolling. A test checks a BM1366 nonce +captured from real silicon at difficulty 1588. This verifies reports only; +work distribution, pool communication, and mining control are still pending. +The `simulator_replay_probe` example sends that captured job through the Rust +HAL client to the SDK's host-only C/Python replay server, then verifies the +returned nonce. From this repository, run it with +`cargo run --example simulator_replay_probe -- SOCKET_PATH` after starting +the SDK server. It is a simulator check and sends work to the named socket. The `main` branch has full tests and a conformance gate; releases are created only after every required cell passes. `next` runs a build check and produces diff --git a/examples/simulator_replay_probe.rs b/examples/simulator_replay_probe.rs new file mode 100644 index 0000000..2cbc6b7 --- /dev/null +++ b/examples/simulator_replay_probe.rs @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MIT +//! Exercise the SDK's host-only BM1366 HAL simulator with a captured job. + +use alkane_os::hal_wire::HalClient; +use alkane_os::pow::verify_sha256_report; +use alkane_os::HardwareBackend; +use std::error::Error; + +const HEADER: [u8; 80] = [ + 0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, 0x38, 0x9d, + 0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, 0x57, 0xb6, 0xc2, 0x25, + 0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78, + 0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38, + 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, +]; + +fn crc16(bytes: &[u8]) -> u16 { + let mut value = 0xffff_u16; + for byte in bytes { + value ^= u16::from(*byte) << 8; + for _ in 0..8 { + value = if value & 0x8000 != 0 { + (value << 1) ^ 0x1021 + } else { + value << 1 + }; + } + } + value +} + +fn reverse_words(input: &[u8]) -> [u8; 32] { + let mut output = [0_u8; 32]; + for index in 0..8 { + output[index * 4..index * 4 + 4].copy_from_slice(&input[(7 - index) * 4..(8 - index) * 4]); + } + output +} + +fn captured_job() -> [u8; 88] { + let mut frame = [0_u8; 88]; + frame[..4].copy_from_slice(&[0x55, 0xaa, 0x21, 0x54]); + frame[4] = 0x18; + frame[10..14].copy_from_slice(&HEADER[72..76]); + frame[14..18].copy_from_slice(&HEADER[68..72]); + frame[18..50].copy_from_slice(&reverse_words(&HEADER[36..68])); + frame[50..82].copy_from_slice(&reverse_words(&HEADER[4..36])); + frame[82..86].copy_from_slice(&HEADER[..4]); + let crc = crc16(&frame[2..86]); + frame[86..88].copy_from_slice(&crc.to_be_bytes()); + frame +} + +fn main() -> Result<(), Box> { + let path = std::env::args() + .nth(1) + .ok_or("usage: simulator_replay_probe SOCKET_PATH")?; + let mut backend = HalClient::connect(path)?; + backend.set_psu_enabled(true)?; + backend.set_chain_reset(0, true)?; + backend.set_chain_reset(0, false)?; + backend.send_frame(0, &captured_job())?; + let mut buffer = [0_u8; 11]; + let length = backend.receive_frame(0, &mut buffer)?; + if length != 11 || buffer[..2] != [0xaa, 0x55] || buffer[10] & 0x80 == 0 { + return Err("missing BM1366 nonce report".into()); + } + let nonce = u32::from_le_bytes(buffer[2..6].try_into()?); + let version_field = u16::from_be_bytes(buffer[8..10].try_into()?); + let mut target = [0_u8; 32]; + target[26..28].fill(0xff); + let result = verify_sha256_report(&HEADER, nonce, version_field, &target); + backend.set_psu_enabled(false)?; + if !result.meets_target { + return Err("captured nonce does not meet difficulty 1".into()); + } + println!("BM1366 captured report verified at difficulty 1"); + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index 0bf0a79..41902a0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ //! the pairing already mines. Hardware backends are supplied by SDK images. pub mod hal_wire; +pub mod pow; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Vendor { diff --git a/src/pow.rs b/src/pow.rs new file mode 100644 index 0000000..b4efd33 --- /dev/null +++ b/src/pow.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT +//! Verify reported SHA-256d shares. This module does not search for nonces. + +const BM1366_VERSION_BITS: u32 = 0x1FFF_E000; + +const ROUND: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +const INITIAL: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]; + +fn compress(state: &mut [u32; 8], block: &[u8]) { + let mut words = [0_u32; 64]; + for (index, part) in block.chunks_exact(4).enumerate() { + words[index] = u32::from_be_bytes(part.try_into().expect("four-byte word")); + } + for index in 16..64 { + let a = words[index - 15]; + let b = words[index - 2]; + let small_zero = a.rotate_right(7) ^ a.rotate_right(18) ^ (a >> 3); + let small_one = b.rotate_right(17) ^ b.rotate_right(19) ^ (b >> 10); + words[index] = words[index - 16] + .wrapping_add(small_zero) + .wrapping_add(words[index - 7]) + .wrapping_add(small_one); + } + + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; + for index in 0..64 { + let choose = (e & f) ^ (!e & g); + let majority = (a & b) ^ (a & c) ^ (b & c); + let big_one = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let big_zero = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let first = h + .wrapping_add(big_one) + .wrapping_add(choose) + .wrapping_add(ROUND[index]) + .wrapping_add(words[index]); + let second = big_zero.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(first); + d = c; + c = b; + b = a; + a = first.wrapping_add(second); + } + for (current, result) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *current = current.wrapping_add(result); + } +} + +/// Compute SHA-256 for a message whose length fits the standard 64-bit field. +pub fn sha256(message: &[u8]) -> [u8; 32] { + let mut state = INITIAL; + let chunks = message.chunks_exact(64); + let remainder = chunks.remainder(); + for chunk in chunks { + compress(&mut state, chunk); + } + let final_size = if remainder.len() >= 56 { 128 } else { 64 }; + let mut final_blocks = [0_u8; 128]; + final_blocks[..remainder.len()].copy_from_slice(remainder); + final_blocks[remainder.len()] = 0x80; + final_blocks[final_size - 8..final_size] + .copy_from_slice(&((message.len() as u64).wrapping_mul(8)).to_be_bytes()); + for chunk in final_blocks[..final_size].chunks_exact(64) { + compress(&mut state, chunk); + } + let mut digest = [0_u8; 32]; + for (word, bytes) in state.into_iter().zip(digest.chunks_exact_mut(4)) { + bytes.copy_from_slice(&word.to_be_bytes()); + } + digest +} + +/// Compute one double hash for verification, never for nonce search. +pub fn sha256d(message: &[u8]) -> [u8; 32] { + sha256(&sha256(message)) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ShareCheck { + pub rolled_version: u32, + pub hash_le: [u8; 32], + pub meets_target: bool, +} + +/// Decode the raw BM1366 version extension against the version sent to the ASIC. +/// The chip reports additional set bits; pool submission uses a separate mask. +pub fn decode_bm1366_version(job_version: u32, version_field: u16) -> u32 { + job_version | ((u32::from(version_field) << 13) & BM1366_VERSION_BITS) +} + +/// The BIP310 mask negotiated with a pool, limited to BM1366 rolling bits. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct VersionMask(u32); + +impl VersionMask { + pub fn new(mask: u32) -> Option { + (mask & !BM1366_VERSION_BITS == 0).then_some(Self(mask)) + } + + pub fn apply_submission_bits(self, base_version: u32, version_bits: u32) -> Option { + (version_bits & !self.0 == 0).then_some((base_version & !self.0) | version_bits) + } +} + +/// Check one ASIC-reported nonce against a little-endian 256-bit pool target. +pub fn verify_sha256_report( + nonce_zero_header: &[u8; 80], + nonce: u32, + version_field: u16, + target_le: &[u8; 32], +) -> ShareCheck { + let mut header = *nonce_zero_header; + let base_version = u32::from_le_bytes(header[..4].try_into().expect("version field")); + let rolled_version = decode_bm1366_version(base_version, version_field); + header[..4].copy_from_slice(&rolled_version.to_le_bytes()); + header[76..80].copy_from_slice(&nonce.to_le_bytes()); + let hash_le = sha256d(&header); + let meets_target = hash_le.iter().rev().cmp(target_le.iter().rev()).is_le(); + ShareCheck { + rolled_version, + hash_le, + meets_target, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + + #[test] + fn sha256_matches_standard_padding_vectors() { + let vectors: [(&[u8], &str); 6] = [ + ( + b"", + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ), + ( + b"abc", + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ), + ( + &(0_u8..55).collect::>(), + "463eb28e72f82e0a96c0a4cc53690c571281131f672aa229e0d45ae59b598b59", + ), + ( + &(0_u8..56).collect::>(), + "da2ae4d6b36748f2a318f23e7ab1dfdf45acdc9d049bd80e59de82a60895f562", + ), + ( + &(0_u8..64).collect::>(), + "fdeab9acf3710362bd2658cdc9a29e8f9c757fcf9811603a8c447cd1d9151108", + ), + ( + &(0_u8..100).collect::>(), + "bce0aff19cf5aa6a7469a30d61d04e4376e4bbf6381052ee9e7f33925c954d52", + ), + ]; + for (message, expected) in vectors { + assert_eq!(hex(&sha256(message)), expected); + } + } + + #[test] + fn captured_bm1366_report_meets_diff_one_only_with_rolled_version() { + let header = [ + 0x00, 0x00, 0x00, 0x20, 0xfc, 0x3a, 0xb8, 0xd4, 0x30, 0x21, 0xf4, 0x5e, 0xb6, 0x62, + 0x38, 0x9d, 0x0f, 0x79, 0x1f, 0x65, 0x7d, 0xbf, 0x75, 0xa5, 0xcb, 0x93, 0x67, 0x0b, + 0x57, 0xb6, 0xc2, 0x25, 0x03, 0xb4, 0x21, 0x3a, 0x43, 0xae, 0x10, 0x52, 0xeb, 0xd4, + 0x44, 0x43, 0x06, 0x8f, 0xe1, 0x78, 0xe2, 0xc6, 0x1c, 0xa4, 0x99, 0x48, 0x46, 0xfd, + 0x13, 0x3a, 0xdd, 0xb0, 0x4a, 0xab, 0x2b, 0x38, 0x2c, 0x5b, 0x4c, 0x74, 0xc1, 0x01, + 0x2e, 0x6a, 0x8f, 0x06, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, + ]; + let mut diff_one = [0_u8; 32]; + diff_one[26..28].fill(0xff); + let result = verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &diff_one); + assert_eq!(result.rolled_version, 0x2096_6000); + assert_eq!( + hex(&result.hash_le), + "4b5e00850cf9de9809f822f8858eda39e49996d9d40f634f1043290000000000" + ); + assert!(result.meets_target); + assert!(!verify_sha256_report(&header, 0xEDAD_FF38, 0, &diff_one).meets_target); + assert!(!verify_sha256_report(&header, 0xEDAD_FF39, 0x04B3, &diff_one).meets_target); + assert!(verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &[0xff; 32]).meets_target); + assert!(!verify_sha256_report(&header, 0xEDAD_FF38, 0x04B3, &[0; 32]).meets_target); + } + + #[test] + fn raw_asic_version_preserves_bits_sent_to_chip() { + assert_eq!(decode_bm1366_version(0x2100_0004, 1), 0x2100_2004); + assert_eq!(decode_bm1366_version(0x2000_0000, 0), 0x2000_0000); + } + + #[test] + fn pool_version_bits_replace_only_negotiated_mask() { + let mask = VersionMask::new(0x0060_0000).expect("valid restricted mask"); + assert_eq!( + mask.apply_submission_bits(0x2160_0004, 0x0020_0000), + Some(0x2120_0004) + ); + assert_eq!(mask.apply_submission_bits(0x2160_0004, 0x0080_0000), None); + assert_eq!( + VersionMask::new(0) + .unwrap() + .apply_submission_bits(0x2100_0004, 0), + Some(0x2100_0004) + ); + assert_eq!( + VersionMask::new(BM1366_VERSION_BITS) + .unwrap() + .apply_submission_bits(0x2160_0004, 0), + Some(0x2000_0004) + ); + assert!(VersionMask::new(0x8000_0000).is_none()); + } +} diff --git a/tests/bench.rs b/tests/bench.rs index 2b8551b..f898eca 100644 --- a/tests/bench.rs +++ b/tests/bench.rs @@ -1,3 +1,4 @@ +use alkane_os::pow::verify_sha256_report; use alkane_os::{power_decision, target_matrix}; use std::hint::black_box; use std::time::Instant; @@ -30,3 +31,18 @@ fn bench_power_policy() { black_box(power_decision(black_box(Some(64_000)), 80_000)); }); } + +#[test] +#[ignore = "microbenchmark"] +fn bench_share_verification() { + let header = [0_u8; 80]; + let target = [0xff_u8; 32]; + measure("share_verification", 20_000, || { + black_box(verify_sha256_report( + black_box(&header), + black_box(0xEDAD_FF38), + black_box(0x04B3), + black_box(&target), + )); + }); +}