use alkane_os::bm1362::{ bt8d_for_baud, chain_inactive, encode_job, encode_work as encode_bm1362_work, read_register, read_register_all, set_chip_address, write_register, write_register_all, Job, S19J_PRO, }; use alkane_os::bm1366::{decode_nonce_report, encode_work}; use alkane_os::difficulty::PoolDifficulty; use alkane_os::hal_wire::HalClient; use alkane_os::miner::Bm1366Miner; use alkane_os::pow::verify_sha256_report; use alkane_os::pow::VersionMask; use alkane_os::scrypt_pow::verify_scrypt_header; use alkane_os::stratum_session::PoolSession; use alkane_os::stratum_submit::{format_submission, Submission}; use alkane_os::stratum_v1::{ parse_boolean_response, parse_configure_result, parse_control_notification, parse_notify, parse_subscription, Subscription, }; use alkane_os::stratum_wire::{ authorize_request, configure_request, subscribe_request, StratumWire, }; use alkane_os::stratum_work::Sha256Job; use alkane_os::{power_decision, target_matrix, HardwareBackend}; use std::hint::black_box; use std::io::{Read, Write}; use std::net::TcpListener; use std::os::unix::net::UnixStream; use std::thread; use std::time::{Duration, Instant}; fn sample(iterations: u64, f: &mut impl FnMut()) -> Duration { let started = Instant::now(); for _ in 0..iterations { f(); } started.elapsed() } fn measure(name: &str, minimum_iterations: u64, mut f: impl FnMut()) { for _ in 0..minimum_iterations.min(1000) { f(); } let mut iterations = minimum_iterations.max(1); while sample(iterations, &mut f) < Duration::from_millis(20) && iterations < 100_000_000 { iterations = (iterations * 2).min(100_000_000); } let mut measurements = [0_f64; 7]; for value in &mut measurements { *value = sample(iterations, &mut f).as_nanos() as f64 / iterations as f64; } measurements.sort_by(f64::total_cmp); let ns = measurements[measurements.len() / 2]; println!("BENCH {name} {ns:.3} ns/op"); } #[test] #[ignore = "microbenchmark"] fn bench_target_matrix() { measure("target_matrix", 20_000, || { black_box( target_matrix() .filter(|target| black_box(target.chip.algorithm) == alkane_os::Algorithm::Sha256) .count(), ); }); } #[test] #[ignore = "microbenchmark"] fn bench_power_policy() { measure("power_policy", 100_000, || { 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), )); }); } #[test] #[ignore = "microbenchmark"] fn bench_scrypt_share_verification() { let header = [0_u8; 80]; let target = [0xff_u8; 32]; measure("scrypt_share_verification", 4, || { black_box(verify_scrypt_header(black_box(&header), black_box(&target))); }); } #[test] #[ignore = "microbenchmark"] fn bench_bm1366_work_encoding() { let header = [0_u8; 80]; measure("bm1366_work_encoding", 20_000, || { black_box(encode_work(black_box(&header), black_box(0x18))); }); } #[test] #[ignore = "microbenchmark"] fn bench_bm1362_commands() { measure("bm1362_commands", 20_000, || { black_box(chain_inactive()); black_box(set_chip_address(black_box(8))); black_box(read_register(black_box(0x40), 0x1c)); black_box(read_register_all(0)); black_box(write_register(black_box(0x40), 0x18, 0x7a31)); black_box(write_register_all(0x80, 0)); black_box(bt8d_for_baud(black_box(115_200))); black_box(S19J_PRO.chip_addresses().last()); }); } #[test] #[ignore = "microbenchmark"] fn bench_bm1362_job_encoding() { let job = Job { work_id: 8, num_midstates: 1, start_nonce: 0, nbits: 0x1a1f_2c34, ntime: 0x5e9b_3cd4, merkle_root: [0xa5; 32], previous_hash: [0x5a; 32], version: 0x2000_0000, }; measure("bm1362_job_encoding", 20_000, || { black_box(encode_job(black_box(&job))); }); } #[test] #[ignore = "microbenchmark"] fn bench_bm1362_work_encoding() { let header = [0_u8; 80]; measure("bm1362_work_encoding", 20_000, || { black_box(encode_bm1362_work(black_box(&header), black_box(8))); }); } #[test] #[ignore = "microbenchmark"] fn bench_bm1366_report_decode() { let report = [ 0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94, ]; measure("bm1366_report_decode", 100_000, || { let _ = black_box(decode_nonce_report(black_box(&report))); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_header() { let job = Sha256Job { prevhash_stratum: [0; 32], coinb1: vec![0; 48], coinb2: vec![0; 64], merkle_branches: vec![[0; 32]; 4], version: 0x2000_0000, nbits: 0x1d00_ffff, ntime: 0x6655_4433, extranonce1: vec![0; 4], extranonce2_size: 8, }; measure("stratum_header", 5_000, || { black_box( job.nonce_zero_header(black_box(&[0; 8]), job.ntime) .unwrap(), ); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_submission() { let share = Submission { request_id: 1, worker: "miner.worker", job_id: "job-123", extranonce2: &[0; 8], ntime: 0x680f_6a2e, nonce: 0xedad_ff38, base_version: 0x2000_0000, rolled_version: 0x2096_6000, version_mask: Some(VersionMask::new(0x1fff_e000).unwrap()), }; measure("stratum_submission", 20_000, || { black_box(format_submission(black_box(&share)).unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_authorize_format() { measure("stratum_authorize_format", 20_000, || { black_box(authorize_request(black_box(3), "miner.worker", "password").unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_configure_format() { measure("stratum_configure_format", 20_000, || { black_box(configure_request(black_box(1))); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_subscribe_format() { measure("stratum_subscribe_format", 20_000, || { black_box(subscribe_request(black_box(2), "alkane-os/0.1").unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_subscription_parse() { let line = br#"{"id":1,"result":[[["mining.notify","session"]],"01020304",4],"error":null}"#; measure("stratum_subscription_parse", 20_000, || { black_box(parse_subscription(black_box(line), black_box(1)).unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_accept_parse() { let line = br#"{"id":5,"result":true,"error":null}"#; measure("stratum_accept_parse", 20_000, || { black_box(parse_boolean_response(black_box(line), black_box(5)).unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_notify_parse() { let line = serde_json::json!({ "id": null, "method": "mining.notify", "params": [ "job-1", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "616263", "78797a", [], "20000000", "1d00ffff", "66554433", true ] }) .to_string(); let subscription = Subscription { extranonce1: vec![1, 2, 3, 4], extranonce2_size: 4, }; measure("stratum_notify_parse", 20_000, || { black_box(parse_notify(black_box(line.as_bytes()), &subscription).unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_control_parse() { let line = br#"{"id":null,"method":"mining.set_difficulty","params":[2048.5]}"#; measure("stratum_control_parse", 20_000, || { black_box(parse_control_notification(black_box(line), false, false).unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_configure_parse() { let line = br#"{"id":1,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","subscribe-extranonce":true},"error":null}"#; measure("stratum_configure_parse", 20_000, || { black_box(parse_configure_result(black_box(line), 1).unwrap()); }); } #[test] #[ignore = "microbenchmark"] fn bench_difficulty_target() { let number = serde_json::from_str("2048.5").unwrap(); let difficulty = PoolDifficulty::from_json_number(&number).unwrap(); measure("difficulty_target", 20_000, || { black_box(black_box(difficulty).target_le()); }); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_job_issue() { let line = serde_json::json!({ "id": null, "method": "mining.notify", "params": [ "job-1", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "616263", "78797a", [], "20000000", "1d00ffff", "66554433", true ] }) .to_string(); let mut session = PoolSession::new( Subscription { extranonce1: vec![1, 2, 3, 4], extranonce2_size: 4, }, None, false, ) .unwrap(); session .control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#) .unwrap(); measure("stratum_job_issue", 5_000, || { session.after_hardware_reset(); black_box(session.issue_notify(black_box(line.as_bytes())).unwrap()); }); } struct BenchBackend; impl HardwareBackend for BenchBackend { type Error = (); fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> { black_box(frame); Ok(()) } fn receive_frame(&mut self, _chain: u8, _frame: &mut [u8]) -> Result { Ok(0) } fn set_chain_reset(&mut self, _chain: u8, _asserted: bool) -> Result<(), Self::Error> { Ok(()) } fn set_fan_target(&mut self, _fan: u8, _percent: u8) -> Result<(), Self::Error> { Ok(()) } fn read_temperature_mc(&mut self, _sensor: u8) -> Result { Ok(50_000) } fn set_psu_enabled(&mut self, _enabled: bool) -> Result<(), Self::Error> { Ok(()) } } #[test] #[ignore = "microbenchmark"] fn bench_bm1366_session_cycle() { let header = [0_u8; 80]; let target = [0xff_u8; 32]; measure("bm1366_session_cycle", 20_000, || { let mut backend = BenchBackend; let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap(); miner.start().unwrap(); miner .submit(black_box(header), black_box(target), 0x18) .unwrap(); black_box(miner.poll().unwrap()); miner.stop().unwrap(); }); } #[test] #[ignore = "microbenchmark"] fn bench_hal_socket_exchange() { let (client, mut server) = UnixStream::pair().unwrap(); let worker = thread::spawn(move || { let mut header = [0_u8; 16]; let mut payload = [0_u8; 2]; while server.read_exact(&mut header).is_ok() { assert_eq!(&header[..6], b"ALKH\x01\x04"); assert_eq!(u32::from_le_bytes(header[12..16].try_into().unwrap()), 2); server.read_exact(&mut payload).unwrap(); assert_eq!(payload, [0, 80]); header[6..8].copy_from_slice(&1_u16.to_le_bytes()); header[12..16].copy_from_slice(&1_u32.to_le_bytes()); server.write_all(&header).unwrap(); server.write_all(&[0]).unwrap(); } }); let mut backend = HalClient::from_stream(client).unwrap(); measure("hal_socket_exchange", 100, || { backend.set_fan_target(black_box(0), black_box(80)).unwrap(); }); drop(backend); worker.join().unwrap(); } #[test] #[ignore = "microbenchmark"] fn bench_stratum_socket_round_trip() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let worker = thread::spawn(move || { let (mut server, _) = listener.accept().unwrap(); let mut request = [0_u8; 3]; while server.read_exact(&mut request).is_ok() { assert_eq!(&request, b"{}\n"); server.write_all(b"{}\n").unwrap(); } }); let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap(); measure("stratum_socket_round_trip", 100, || { wire.send_line(black_box(b"{}\n")).unwrap(); black_box(wire.read_line().unwrap()); }); drop(wire); worker.join().unwrap(); }