use crate::error::Result; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct BeaconingInput { pub timestamps: Vec, #[serde(default)] pub proto: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct GridInfo { pub min_period_s: f64, pub max_period_s: f64, pub points: usize, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct WeightsInfo { pub significance: f64, pub regularity: f64, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BeaconingScore { pub score: f64, pub observations: usize, pub period_detected_seconds: f64, pub p_value: f64, pub peak_power: f64, pub madm_normalized: f64, pub skew_bowley: f64, pub degenerate_quartiles: bool, pub method: &'static str, pub grid: GridInfo, pub weights: WeightsInfo, pub formula_version: &'static str, pub status: &'static str, pub span_seconds: f64, pub min_cycles: usize, pub significance: f64, pub regularity: f64, pub significance_gate: f64, pub gate_regularity: f64, pub proto: String, } fn quantile_cont(sorted: &[f64], q: f64) -> f64 { if sorted.is_empty() { return 0.0; } if sorted.len() == 1 { return sorted[0]; } let idx = (sorted.len() - 1) as f64 * q; let lower = idx.floor() as usize; let upper = idx.ceil() as usize; let frac = idx - lower as f64; if lower == upper { sorted[lower] } else { sorted[lower] + frac * (sorted[upper] - sorted[lower]) } } pub fn score(input: &BeaconingInput) -> Result { let n = input.timestamps.len(); let min_cycles = 3; let gate_regularity = 0.25; let weights_info = WeightsInfo { significance: 0.5, regularity: 0.5, }; if n < 20 { let span = if n >= 2 { let mut sorted = input.timestamps.clone(); sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); sorted[n - 1] - sorted[0] } else { 0.0 }; return Ok(BeaconingScore { score: 0.0, observations: n, period_detected_seconds: 0.0, p_value: 1.0, peak_power: 0.0, madm_normalized: 0.0, skew_bowley: 0.0, degenerate_quartiles: false, method: "rayleigh-schuster", grid: GridInfo { min_period_s: 600.0, max_period_s: 43200.0, points: 0, }, weights: weights_info, formula_version: "1.2", status: "insufficient_data", span_seconds: span, min_cycles, significance: 0.0, regularity: 0.0, significance_gate: 0.0, gate_regularity, proto: input.proto.clone(), }); } let mut ts = input.timestamps.clone(); ts.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let span = ts[n - 1] - ts[0]; let mut deltas = Vec::with_capacity(n - 1); for i in 1..n { deltas.push(ts[i] - ts[i - 1]); } let mut sorted_deltas = deltas.clone(); sorted_deltas.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let q1 = quantile_cont(&sorted_deltas, 0.25); let q2 = quantile_cont(&sorted_deltas, 0.50); let q3 = quantile_cont(&sorted_deltas, 0.75); const EPSILON: f64 = 1e-9; let (skew_bowley, degenerate_quartiles) = if (q3 - q1).abs() < EPSILON { (0.0, true) } else { ((q3 + q1 - 2.0 * q2) / (q3 - q1), false) }; let mut abs_devs: Vec = deltas.iter().map(|&d| (d - q2).abs()).collect(); abs_devs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let madm = quantile_cont(&abs_devs, 0.50); // Step 2: degenerate deltas check if q2 <= EPSILON { return Ok(BeaconingScore { score: 0.0, observations: n, period_detected_seconds: 0.0, p_value: 1.0, peak_power: 0.0, madm_normalized: 0.0, skew_bowley, degenerate_quartiles, method: "rayleigh-schuster", grid: GridInfo { min_period_s: 600.0, max_period_s: 0.0, points: 0, }, weights: weights_info, formula_version: "1.2", status: "degenerate_deltas", span_seconds: span, min_cycles, significance: 0.0, regularity: 0.0, significance_gate: 0.0, gate_regularity, proto: input.proto.clone(), }); } let madm_normalized = madm / q2; // Step 3: Effective grid (periods <= span / min_cycles) let max_allowed_period = span / (min_cycles as f64); let num_grid_points = 200; let mut periods = Vec::new(); for j in 0..num_grid_points { let period = 600.0 * 72.0_f64.powf(j as f64 / 199.0); if period <= max_allowed_period { periods.push(period); } } let m_eff = periods.len(); if m_eff == 0 { let regularity = (1.0 - 2.0 * madm_normalized).clamp(0.0, 1.0); return Ok(BeaconingScore { score: 0.0, observations: n, period_detected_seconds: 0.0, p_value: 1.0, peak_power: 0.0, madm_normalized, skew_bowley, degenerate_quartiles, method: "rayleigh-schuster", grid: GridInfo { min_period_s: 600.0, max_period_s: 0.0, points: 0, }, weights: weights_info, formula_version: "1.2", status: "insufficient_span", span_seconds: span, min_cycles, significance: 0.0, regularity, significance_gate: 0.0, gate_regularity, proto: input.proto.clone(), }); } // Step 4: Rayleigh/Schuster periodogram on effective grid let t0 = ts[0]; let mut powers = Vec::with_capacity(m_eff); for &period in &periods { let f = 1.0 / period; let mut sum_cos = 0.0; let mut sum_sin = 0.0; for &t in &ts { let phase = 2.0 * std::f64::consts::PI * f * (t - t0); sum_cos += phase.cos(); sum_sin += phase.sin(); } let power = (sum_cos * sum_cos + sum_sin * sum_sin) / (n as f64); powers.push(power); } let mut p_max = 0.0_f64; for &p in &powers { if p > p_max { p_max = p; } } // Step 9: Harmonic resistance: largest period in effective grid with P >= 0.5 * P_max let threshold_power = 0.5 * p_max; let mut detected_period = periods[0]; for j in (0..m_eff).rev() { if powers[j] >= threshold_power { detected_period = periods[j]; break; } } let m_eff_f64 = m_eff as f64; let p_value = (m_eff_f64 * (-p_max).exp()).min(1.0); // Step 5: Significance let ln_m = m_eff_f64.ln(); let six_ln_10 = 6.0 * 10.0_f64.ln(); let sig = ((p_max - ln_m) / six_ln_10).clamp(0.0, 1.0); // Step 6: Regularity let regularity = (1.0 - 2.0 * madm_normalized).clamp(0.0, 1.0); // Step 7: Gate let gate = (regularity / gate_regularity).min(1.0); // Step 8: Score let score = 0.5 * sig * gate + 0.5 * regularity; let grid_info = GridInfo { min_period_s: periods[0], max_period_s: periods[m_eff - 1], points: m_eff, }; Ok(BeaconingScore { score, observations: n, period_detected_seconds: detected_period, p_value, peak_power: p_max, madm_normalized, skew_bowley, degenerate_quartiles, method: "rayleigh-schuster", grid: grid_info, weights: weights_info, formula_version: "1.2", status: "ok", span_seconds: span, min_cycles, significance: sig, regularity, significance_gate: gate, gate_regularity, proto: input.proto.clone(), }) } #[cfg(test)] mod tests { use super::*; struct SplitMix64 { state: u64, } impl SplitMix64 { fn new(seed: u64) -> Self { Self { state: seed } } fn next_u64(&mut self) -> u64 { self.state = self.state.wrapping_add(0x9e3779b97f4a7c15); let mut z = self.state; z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); z ^ (z >> 31) } fn next_f64(&mut self) -> f64 { (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 } fn uniform(&mut self, low: f64, high: f64) -> f64 { low + (high - low) * self.next_f64() } fn exponential(&mut self, mean: f64) -> f64 { let u = self.next_f64().max(1e-15); -mean * u.ln() } } #[test] fn test_1_perfectly_periodic_series() { let mut timestamps = Vec::with_capacity(42); for k in 0..42 { timestamps.push(k as f64 * 14400.0); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!(res.score >= 0.99, "score: {}", res.score); let rel_err = (res.period_detected_seconds - 14400.0).abs() / 14400.0; assert!( rel_err < 0.02, "period: {}, rel_err: {}", res.period_detected_seconds, rel_err ); assert_eq!(res.status, "ok"); assert_eq!(res.formula_version, "1.2"); } #[test] fn test_2_grid_jitter() { let mut min_score = f64::MAX; let mut max_score = f64::MIN; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let t0 = 1000.0; let mut timestamps = Vec::with_capacity(42); for k in 0..42 { let jitter = rng.uniform(-0.18, 0.18) * 14400.0; timestamps.push(t0 + k as f64 * 14400.0 + jitter); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!(res.score >= 0.80, "seed {seed} score {} < 0.80", res.score); if res.score < min_score { min_score = res.score; } if res.score > max_score { max_score = res.score; } } println!("Test 2 (grid jitter) 50 seeds: min={min_score:.4}, max={max_score:.4}"); } #[test] fn test_3_cumulative_jitter() { let mut min_score = f64::MAX; let mut max_score = f64::MIN; let mut period_within_10pct = 0; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let mut timestamps = Vec::with_capacity(42); let mut curr = 1000.0; timestamps.push(curr); for _ in 1..42 { curr += 14400.0 * (1.0 + rng.uniform(-0.18, 0.18)); timestamps.push(curr); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!(res.score >= 0.40, "seed {seed} score {} < 0.40", res.score); if res.score < min_score { min_score = res.score; } if res.score > max_score { max_score = res.score; } let rel_err = (res.period_detected_seconds - 14400.0).abs() / 14400.0; if rel_err < 0.10 { period_within_10pct += 1; } } println!( "Test 3 (cumulative jitter) 50 seeds: min={min_score:.4}, max={max_score:.4}, period_hits={period_within_10pct}/50" ); assert!( period_within_10pct >= 45, "period hits: {period_within_10pct}/50" ); } #[test] fn test_4_poisson_random() { let mut min_score = f64::MAX; let mut max_score = f64::MIN; let mean = 7.0 * 86400.0 / 40.0; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let mut timestamps = Vec::with_capacity(40); let mut curr = 0.0; for _ in 0..40 { curr += rng.exponential(mean); timestamps.push(curr); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!(res.score < 0.30, "seed {seed} score {} >= 0.30", res.score); if res.score < min_score { min_score = res.score; } if res.score > max_score { max_score = res.score; } } println!("Test 4 (Poisson) 50 seeds: min={min_score:.4}, max={max_score:.4}"); } #[test] fn test_5_sentinel_q3_eq_q1() { let mut timestamps = Vec::with_capacity(25); for k in 0..25 { timestamps.push(k as f64 * 1000.0); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert_eq!(res.skew_bowley, 0.0); assert!(res.degenerate_quartiles); assert!(!res.score.is_nan() && !res.score.is_infinite()); } #[test] fn test_6_median_delta_zero() { let timestamps = vec![1000.0; 25]; let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert_eq!(res.status, "degenerate_deltas"); assert_eq!(res.score, 0.0); assert!(!res.score.is_nan() && !res.score.is_infinite()); } #[test] fn test_7_insufficient_data() { let timestamps: Vec = (0..19).map(|k| k as f64 * 1000.0).collect(); let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert_eq!(res.status, "insufficient_data"); assert_eq!(res.score, 0.0); } #[test] fn test_8_determinism() { let timestamps: Vec = (0..42).map(|k| k as f64 * 14400.0).collect(); let s1 = score(&BeaconingInput { timestamps: timestamps.clone(), proto: "tcp".to_string(), }) .unwrap(); let s2 = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); let j1 = serde_json::to_vec(&s1).unwrap(); let j2 = serde_json::to_vec(&s2).unwrap(); assert_eq!(j1, j2); } fn generate_bursty(rng: &mut SplitMix64, span: f64) -> Vec { let mut out = Vec::new(); let mut t = 1_790_000_000.0; let end = t + span; loop { t += rng.exponential(900.0); if t > end { break; } let mut k = 1; while rng.next_f64() < 0.8 { k += 1; } let mut u = t; for _ in 0..k { out.push(u); u += rng.exponential(2.0); } } out } #[test] fn test_9_bursty_3h() { let mut max_score = f64::MIN; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let timestamps = generate_bursty(&mut rng, 3.0 * 3600.0); let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!( res.score < 0.05, "seed {seed} bursty3h score {} >= 0.05 (status: {})", res.score, res.status ); if res.score > max_score { max_score = res.score; } } println!("Test 9 (bursty 3h) 50 seeds: max={max_score:.4}"); } #[test] fn test_10_bursty_24h() { let mut max_score = f64::MIN; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let timestamps = generate_bursty(&mut rng, 86400.0); let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!( res.score < 0.05, "seed {seed} bursty24h score {} >= 0.05 (status: {})", res.score, res.status ); if res.score > max_score { max_score = res.score; } } println!("Test 10 (bursty 24h) 50 seeds: max={max_score:.4}"); } #[test] fn test_11_fast_short() { let mut min_score = f64::MAX; let mut max_score = f64::MIN; let mut period_within_10pct = 0; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let mut timestamps = Vec::new(); let mut t = 1_790_000_000.0; let end = t + 86400.0; while t < end { timestamps.push(t); t += 900.0 * (1.0 + rng.uniform(-0.1, 0.1)); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert!( res.score >= 0.40, "seed {seed} fast_short score {} < 0.40", res.score ); if res.score < min_score { min_score = res.score; } if res.score > max_score { max_score = res.score; } let rel_err = (res.period_detected_seconds - 900.0).abs() / 900.0; if rel_err < 0.10 { period_within_10pct += 1; } } println!( "Test 11 (fast short) 50 seeds: min={min_score:.4}, max={max_score:.4}, period_hits={period_within_10pct}/50" ); assert!( period_within_10pct >= 45, "period hits: {period_within_10pct}/50" ); } #[test] fn test_12_dropout_30pct() { let mut hits = 0; for seed in 1..=50 { let mut rng = SplitMix64::new(seed); let mut timestamps = Vec::new(); let mut t = 1_790_000_000.0; for _ in 0..60 { if rng.next_f64() > 0.3 { timestamps.push(t); } t += 14400.0 * (1.0 + rng.uniform(-0.1, 0.1)); } let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); if res.score >= 0.40 { hits += 1; } } println!("Test 12 (dropout 30%) 50 seeds: hits={hits}/50"); assert!(hits >= 48, "dropout hits {hits} < 48"); } #[test] fn test_13_insufficient_span() { // 30 events in 25 min (1500s < 1800s) let timestamps: Vec = (0..30).map(|k| 1000.0 + k as f64 * 50.0).collect(); let res = score(&BeaconingInput { timestamps, proto: "tcp".to_string(), }) .unwrap(); assert_eq!(res.status, "insufficient_span"); assert_eq!(res.score, 0.0); } }