diff --git a/src/lib.rs b/src/lib.rs index 6a64e2e..73d3909 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,6 +17,7 @@ pub mod miner; pub mod pow; pub mod profiles; pub mod scrypt_pow; +pub mod split; pub mod stratum_client; pub mod stratum_session; pub mod stratum_submit; 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); + } +}