use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use time::Duration;
use crate::cdrtime::{CdrTimestamp, Seconds};
use crate::numbering::NumberRange;
use crate::numbering::NumberRangeSet;
use crate::party::ChargedParty;
use crate::plmn::Mcc;
use crate::record::{RecordType, UsageRecord};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Signal {
ImpossibleTravel,
PremiumDestination,
WangiriPattern,
BypassSignature,
AitSignature,
}
impl Signal {
pub const ALL: &'static [Self] = &[
Self::ImpossibleTravel,
Self::PremiumDestination,
Self::WangiriPattern,
Self::BypassSignature,
Self::AitSignature,
];
pub const CODES: &'static [&'static str] = &[
"IMPOSSIBLE_TRAVEL",
"PREMIUM_DESTINATION",
"WANGIRI_PATTERN",
"BYPASS_SIGNATURE",
"AIT_SIGNATURE",
];
#[must_use]
pub const fn is_arithmetic(self) -> bool {
matches!(self, Self::ImpossibleTravel)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::ImpossibleTravel => "IMPOSSIBLE_TRAVEL",
Self::PremiumDestination => "PREMIUM_DESTINATION",
Self::WangiriPattern => "WANGIRI_PATTERN",
Self::BypassSignature => "BYPASS_SIGNATURE",
Self::AitSignature => "AIT_SIGNATURE",
}
}
}
impl fmt::Display for Signal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Indication {
pub signal: Signal,
pub records: Vec<usize>,
pub detail: String,
}
impl Indication {
#[must_use]
pub fn new(signal: Signal, records: Vec<usize>, detail: impl Into<String>) -> Self {
Self {
signal,
records,
detail: detail.into(),
}
}
}
impl fmt::Display for Indication {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} over {} record(s): {}",
self.signal,
self.records.len(),
self.detail
)
}
}
pub trait TransitTimes {
fn minimum_transit(&self, from: Mcc, to: Mcc) -> Option<Duration>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UniformTransit(Duration);
impl UniformTransit {
#[must_use]
pub const fn new(minimum: Duration) -> Self {
Self(minimum)
}
#[must_use]
pub const fn get(self) -> Duration {
self.0
}
}
impl TransitTimes for UniformTransit {
fn minimum_transit(&self, from: Mcc, to: Mcc) -> Option<Duration> {
if from.same_country(to) {
None
} else {
Some(self.0)
}
}
}
impl<F> TransitTimes for F
where
F: Fn(Mcc, Mcc) -> Option<Duration>,
{
fn minimum_transit(&self, from: Mcc, to: Mcc) -> Option<Duration> {
self(from, to)
}
}
struct Sighting {
index: usize,
country: Mcc,
arrived: CdrTimestamp,
departed: CdrTimestamp,
}
#[must_use]
pub fn impossible_travel(records: &[UsageRecord], transit: &impl TransitTimes) -> Vec<Indication> {
let mut by_party: BTreeMap<&ChargedParty, Vec<Sighting>> = BTreeMap::new();
for (index, record) in records.iter().enumerate() {
if let Some(plmn) = record.serving_plmn {
by_party.entry(&record.party).or_default().push(Sighting {
index,
country: plmn.mcc(),
arrived: record.opened,
departed: record.closed.unwrap_or(record.opened),
});
}
}
let mut found = Vec::new();
for placed in by_party.values_mut() {
placed.sort_by(|a, b| CdrTimestamp::cmp_instant(&a.arrived, &b.arrived));
for pair in placed.windows(2) {
let (first, second) = (&pair[0], &pair[1]);
let (first_index, first_country) = (first.index, first.country);
let (second_index, second_country) = (second.index, second.country);
if first_country.same_country(second_country) {
continue;
}
let Some(minimum) = transit.minimum_transit(first_country, second_country) else {
continue;
};
let elapsed = second.arrived.to_utc() - first.departed.to_utc();
if elapsed >= minimum {
continue;
}
let mut involved = [first_index, second_index];
involved.sort_unstable();
found.push(Indication::new(
Signal::ImpossibleTravel,
involved.to_vec(),
if elapsed.is_negative() {
format!(
"{first_country} and {second_country} overlap by {}",
-elapsed
)
} else {
format!("{first_country} to {second_country} in {elapsed}")
},
));
}
}
found
}
#[must_use]
pub fn premium_destination<T>(
records: &[UsageRecord],
high_risk: &NumberRangeSet<T>,
) -> Vec<Indication> {
records
.iter()
.enumerate()
.filter_map(|(index, record)| {
let called = record.called?.as_number()?;
let (range, _) = high_risk.longest_match(called)?;
Some(Indication::new(
Signal::PremiumDestination,
vec![index],
format!("destination in flagged range {range}"),
))
})
.collect()
}
#[must_use]
pub fn wangiri_pattern(
records: &[UsageRecord],
ring_ceiling: Seconds,
min_calls: usize,
within: Duration,
) -> Vec<Indication> {
if min_calls == 0 || within.is_negative() || within.is_zero() {
return Vec::new();
}
let mut by_party: BTreeMap<&ChargedParty, Vec<(CdrTimestamp, usize)>> = BTreeMap::new();
for (index, record) in records.iter().enumerate() {
if record.record_type == RecordType::TerminatedCall
&& record
.duration
.is_some_and(|duration| duration <= ring_ceiling)
{
by_party
.entry(&record.party)
.or_default()
.push((record.opened, index));
}
}
let mut found = Vec::new();
for calls in by_party.values_mut() {
calls.sort_by(|a, b| CdrTimestamp::cmp_instant(&a.0, &b.0).then(a.1.cmp(&b.1)));
let (mut best_start, mut best_len, mut first) = (0usize, 0usize, 0usize);
for last in 0..calls.len() {
while calls[last].0.to_utc() - calls[first].0.to_utc() > within {
first += 1;
}
if last + 1 - first > best_len {
(best_start, best_len) = (first, last + 1 - first);
}
}
if best_len < min_calls {
continue;
}
let window = &calls[best_start..best_start + best_len];
let mut involved: Vec<usize> = window.iter().map(|(_, index)| *index).collect();
involved.sort_unstable();
found.push(Indication::new(
Signal::WangiriPattern,
involved,
format!("{best_len} inbound call(s) of at most {ring_ceiling} s within {within}"),
));
}
found
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TrafficShape {
pub outbound_calls: u64,
pub inbound_calls: u64,
pub distinct_networks: u64,
}
impl TrafficShape {
#[must_use]
pub fn of(records: &[UsageRecord]) -> Self {
let mut shape = Self::default();
let mut networks = BTreeSet::new();
for record in records {
match record.record_type {
RecordType::OriginatedCall => shape.outbound_calls += 1,
RecordType::TerminatedCall => shape.inbound_calls += 1,
_ => continue,
}
if let Some(plmn) = record.serving_plmn {
networks.insert(plmn);
}
}
shape.distinct_networks = networks.len() as u64;
shape
}
#[must_use]
pub const fn calls(self) -> u64 {
self.outbound_calls + self.inbound_calls
}
#[must_use]
pub const fn outbound_percent(self) -> Option<u64> {
match self.calls() {
0 => None,
calls => Some(self.outbound_calls * 100 / calls),
}
}
}
#[must_use]
pub fn bypass_signature(
records: &[UsageRecord],
min_calls: u64,
outbound_ratio_percent: u64,
) -> Option<Indication> {
let shape = TrafficShape::of(records);
let ratio = shape.outbound_percent()?;
if shape.calls() < min_calls || shape.calls() == 0 {
return None;
}
if ratio < outbound_ratio_percent || shape.distinct_networks > 1 {
return None;
}
let involved: Vec<usize> = records
.iter()
.enumerate()
.filter(|(_, record)| {
matches!(
record.record_type,
RecordType::OriginatedCall | RecordType::TerminatedCall
)
})
.map(|(index, _)| index)
.collect();
Some(Indication::new(
Signal::BypassSignature,
involved,
format!(
"{ratio}% of {} call(s) outbound on {} network(s)",
shape.calls(),
shape.distinct_networks
),
))
}
#[must_use]
pub fn ait_signature<T>(
records: &[UsageRecord],
ranges: &NumberRangeSet<T>,
min_messages: usize,
concentration_percent: u64,
) -> Option<Indication> {
let mut by_range: BTreeMap<NumberRange, Vec<usize>> = BTreeMap::new();
let mut messages = 0usize;
for (index, record) in records.iter().enumerate() {
if record.record_type != RecordType::SmsOriginated {
continue;
}
messages += 1;
if let Some(called) = record.called.and_then(|d| d.as_number())
&& let Some((range, _)) = ranges.longest_match(called)
{
by_range.entry(range).or_default().push(index);
}
}
if messages < min_messages || messages == 0 {
return None;
}
let (range, involved) = by_range.into_iter().max_by_key(|(_, v)| v.len())?;
let share = (involved.len() as u128 * 100 / messages as u128) as u64;
if share < concentration_percent {
return None;
}
let count = involved.len();
Some(Indication::new(
Signal::AitSignature,
involved,
format!("{count} of {messages} message(s) ({share}%) to range {range}"),
))
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{Indication, Signal, TrafficShape};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
impl Serialize for Signal {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Signal {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = Signal;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a fraud signal code")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Signal, E> {
Signal::ALL
.iter()
.find(|s| s.as_str() == v)
.copied()
.ok_or_else(|| de::Error::custom(format!("unknown signal {v:?}")))
}
}
deserializer.deserialize_str(V)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "Indication")]
struct IndicationRepr {
signal: Signal,
records: Vec<usize>,
detail: String,
}
impl Serialize for Indication {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
IndicationRepr {
signal: self.signal,
records: self.records.clone(),
detail: self.detail.clone(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Indication {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = IndicationRepr::deserialize(deserializer)?;
Ok(Indication::new(r.signal, r.records, r.detail))
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "TrafficShape")]
struct ShapeRepr {
outbound_calls: u64,
inbound_calls: u64,
distinct_networks: u64,
}
impl Serialize for TrafficShape {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
ShapeRepr {
outbound_calls: self.outbound_calls,
inbound_calls: self.inbound_calls,
distinct_networks: self.distinct_networks,
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for TrafficShape {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = ShapeRepr::deserialize(deserializer)?;
Ok(TrafficShape {
outbound_calls: r.outbound_calls,
inbound_calls: r.inbound_calls,
distinct_networks: r.distinct_networks,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::identity::Msisdn;
use crate::numbering::NumberRange;
use crate::party::SubscriberRef;
use crate::record::SourceRef;
fn resolve(
records: &[UsageRecord],
called: &impl Fn(usize, &UsageRecord) -> Option<Msisdn>,
) -> Vec<UsageRecord> {
records
.iter()
.enumerate()
.map(|(i, r)| match called(i, r) {
Some(n) => r.clone().with_called(n.into()),
None => r.clone(),
})
.collect()
}
fn call(kind: RecordType, opened: &str, serving: &str) -> UsageRecord {
UsageRecord::new(
kind,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
opened.parse().unwrap(),
SourceRef::new("msc-01".parse().unwrap(), 0),
)
.with_networks(serving.parse().unwrap(), "262-02".parse().unwrap())
}
fn subscriber(imsi: &str) -> ChargedParty {
ChargedParty::Subscriber(SubscriberRef::new(imsi.parse().unwrap()))
}
fn high_risk() -> NumberRangeSet<&'static str> {
let mut set = NumberRangeSet::new();
set.insert("88216".parse::<NumberRange>().unwrap(), "satellite");
set.insert("23928".parse::<NumberRange>().unwrap(), "flagged");
set
}
#[test]
fn two_countries_too_close_together_is_arithmetically_impossible() {
let records = vec![
call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
),
call(
RecordType::OriginatedCall,
"2026-07-28T10:20:00+02:00",
"310-260",
),
];
let found = impossible_travel(&records, &UniformTransit::new(Duration::hours(4)));
assert_eq!(found.len(), 1);
assert_eq!(found[0].signal, Signal::ImpossibleTravel);
assert_eq!(found[0].records, vec![0, 1]);
assert!(Signal::ImpossibleTravel.is_arithmetic());
}
#[test]
fn a_plausible_journey_does_not_fire() {
let records = vec![
call(
RecordType::OriginatedCall,
"2026-07-28T02:00:00+02:00",
"262-02",
),
call(
RecordType::OriginatedCall,
"2026-07-28T14:00:00+02:00",
"310-260",
),
];
assert!(impossible_travel(&records, &UniformTransit::new(Duration::hours(4))).is_empty());
}
#[test]
fn staying_in_one_country_never_fires() {
let records = vec![
call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
),
call(
RecordType::OriginatedCall,
"2026-07-28T10:01:00+02:00",
"262-01",
),
];
assert!(impossible_travel(&records, &UniformTransit::new(Duration::hours(4))).is_empty());
}
#[test]
fn two_subscribers_are_not_one_journey() {
let mut here = call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
);
here.party = subscriber("imsi-262021111111111");
let mut there = call(
RecordType::OriginatedCall,
"2026-07-28T10:20:00+02:00",
"310-260",
);
there.party = subscriber("imsi-262022222222222");
assert!(
impossible_travel(
&[here.clone(), there.clone()],
&UniformTransit::new(Duration::hours(4))
)
.is_empty(),
"different parties are never compared against each other"
);
there.party = here.party.clone();
let found = impossible_travel(&[here, there], &UniformTransit::new(Duration::hours(4)));
assert_eq!(found.len(), 1);
}
#[test]
fn interleaved_parties_do_not_hide_a_journey() {
let mut records = Vec::new();
for minute in 0..6 {
let mut other = call(
RecordType::OriginatedCall,
&format!("2026-07-28T10:0{minute}:00+02:00"),
"440-10",
);
other.party = subscriber("imsi-262029999999999");
records.push(other);
}
records.insert(
0,
call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
),
);
records.push(call(
RecordType::OriginatedCall,
"2026-07-28T10:20:00+02:00",
"310-260",
));
let found = impossible_travel(&records, &UniformTransit::new(Duration::hours(4)));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].records, vec![0, 7]);
}
#[test]
fn detection_is_order_independent() {
let a = call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
);
let b = call(
RecordType::OriginatedCall,
"2026-07-28T10:20:00+02:00",
"310-260",
);
let forward = impossible_travel(
&[a.clone(), b.clone()],
&UniformTransit::new(Duration::hours(4)),
);
let reversed = impossible_travel(&[b, a], &UniformTransit::new(Duration::hours(4)));
assert_eq!(forward.len(), reversed.len());
assert_eq!(forward[0].signal, reversed[0].signal);
assert_eq!(forward[0].records.len(), 2);
}
#[test]
fn records_without_a_serving_network_are_skipped() {
let mut unplaced = call(
RecordType::OriginatedCall,
"2026-07-28T10:10:00+02:00",
"310-260",
);
unplaced.serving_plmn = None;
let records = vec![
call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
),
unplaced,
call(
RecordType::OriginatedCall,
"2026-07-28T18:00:00+02:00",
"262-02",
),
];
assert!(impossible_travel(&records, &UniformTransit::new(Duration::hours(4))).is_empty());
}
#[test]
fn traffic_to_a_flagged_range_is_reported() {
let records = vec![
call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
),
call(
RecordType::OriginatedCall,
"2026-07-28T11:00:00+02:00",
"262-02",
),
];
let called = |index: usize, _: &UsageRecord| -> Option<Msisdn> {
if index == 0 {
"882161234567".parse().ok()
} else {
"491701234567".parse().ok()
}
};
let found = premium_destination(&resolve(&records, &called), &high_risk());
assert_eq!(found.len(), 1);
assert_eq!(found[0].records, vec![0]);
assert!(found[0].detail.contains("88216"), "{}", found[0].detail);
assert!(!Signal::PremiumDestination.is_arithmetic());
}
#[test]
fn one_short_call_is_not_a_pattern() {
let one = vec![
call(
RecordType::TerminatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
)
.with_duration(Seconds::new(2)),
];
assert!(wangiri_pattern(&one, Seconds::new(5), 10, Duration::hours(1)).is_empty());
let many: Vec<UsageRecord> = (0..12)
.map(|i| {
call(
RecordType::TerminatedCall,
&format!("2026-07-28T10:{i:02}:00+02:00"),
"262-02",
)
.with_duration(Seconds::new(2))
})
.collect();
let found = wangiri_pattern(&many, Seconds::new(5), 10, Duration::hours(1));
assert_eq!(found.len(), 1, "twelve short inbound");
let found = &found[0];
assert_eq!(found.signal, Signal::WangiriPattern);
assert_eq!(found.records.len(), 12);
}
#[test]
fn outbound_calls_are_not_wangiri() {
let outbound: Vec<UsageRecord> = (0..20)
.map(|i| {
call(
RecordType::OriginatedCall,
&format!("2026-07-28T10:{i:02}:00+02:00"),
"262-02",
)
.with_duration(Seconds::new(1))
})
.collect();
assert!(wangiri_pattern(&outbound, Seconds::new(5), 10, Duration::hours(1)).is_empty());
}
#[test]
fn a_rack_of_sims_terminating_traffic_shows_a_shape() {
let records: Vec<UsageRecord> = (0..50)
.map(|i| {
call(
RecordType::OriginatedCall,
&format!("2026-07-28T{:02}:00:00+02:00", i % 24),
"262-02",
)
})
.collect();
let shape = TrafficShape::of(&records);
assert_eq!(shape.outbound_calls, 50);
assert_eq!(shape.inbound_calls, 0);
assert_eq!(shape.distinct_networks, 1);
assert_eq!(shape.calls(), 50);
assert_eq!(shape.outbound_percent(), Some(100));
let found = bypass_signature(&records, 20, 90).unwrap();
assert_eq!(found.signal, Signal::BypassSignature);
assert!(found.detail.contains("100%"), "{}", found.detail);
}
#[test]
fn simulated_human_behaviour_defeats_the_signature() {
let balanced: Vec<UsageRecord> = (0..50)
.map(|i| {
call(
if i % 2 == 0 {
RecordType::OriginatedCall
} else {
RecordType::TerminatedCall
},
&format!("2026-07-28T{:02}:00:00+02:00", i % 24),
"262-02",
)
})
.collect();
assert!(bypass_signature(&balanced, 20, 90).is_none());
let mobile: Vec<UsageRecord> = (0..50)
.map(|i| {
call(
RecordType::OriginatedCall,
&format!("2026-07-28T{:02}:00:00+02:00", i % 24),
if i % 2 == 0 { "262-02" } else { "262-01" },
)
})
.collect();
assert!(
bypass_signature(&mobile, 20, 90).is_none(),
"fabricated mobility defeats the signature, as the module documents"
);
}
#[test]
fn a_handful_of_calls_never_fires() {
let few: Vec<UsageRecord> = (0..3)
.map(|i| {
call(
RecordType::OriginatedCall,
&format!("2026-07-28T1{i}:00:00+02:00"),
"262-02",
)
})
.collect();
assert!(bypass_signature(&few, 20, 90).is_none());
assert!(bypass_signature(&[], 1, 90).is_none());
}
#[test]
fn the_outbound_ratio_is_computed_in_the_right_order() {
let mixed = vec![
call(
RecordType::OriginatedCall,
"2026-07-28T10:00:00+02:00",
"262-02",
),
call(
RecordType::OriginatedCall,
"2026-07-28T11:00:00+02:00",
"262-02",
),
call(
RecordType::TerminatedCall,
"2026-07-28T12:00:00+02:00",
"262-02",
),
];
let found = bypass_signature(&mixed, 3, 60).unwrap();
assert!(found.detail.contains("66%"), "{}", found.detail);
assert!(bypass_signature(&mixed, 3, 70).is_none());
}
#[test]
fn messages_concentrated_on_one_range_are_reported() {
let records: Vec<UsageRecord> = (0..20)
.map(|i| {
call(
RecordType::SmsOriginated,
&format!("2026-07-28T10:{i:02}:00+02:00"),
"262-02",
)
})
.collect();
let called = |index: usize, _: &UsageRecord| -> Option<Msisdn> {
if index < 18 {
"882161234567".parse().ok()
} else {
"491701234567".parse().ok()
}
};
let found = ait_signature(&resolve(&records, &called), &high_risk(), 10, 80).unwrap();
assert_eq!(found.signal, Signal::AitSignature);
assert_eq!(found.records.len(), 18);
assert!(found.detail.contains("90%"), "{}", found.detail);
assert!(ait_signature(&resolve(&records, &called), &high_risk(), 10, 95).is_none());
}
#[test]
fn a_small_number_of_messages_never_fires() {
let records: Vec<UsageRecord> = (0..3)
.map(|i| {
call(
RecordType::SmsOriginated,
&format!("2026-07-28T10:0{i}:00+02:00"),
"262-02",
)
})
.collect();
let called = |_: usize, _: &UsageRecord| "882161234567".parse::<Msisdn>().ok();
assert!(ait_signature(&resolve(&records, &called), &high_risk(), 10, 50).is_none());
}
#[test]
fn signal_codes_round_trip() {
assert_eq!(Signal::ALL.len(), 5);
assert_eq!(Signal::ALL.len(), Signal::CODES.len());
for (signal, code) in Signal::ALL.iter().zip(Signal::CODES) {
assert_eq!(signal.to_string(), signal.as_str());
assert_eq!(signal.as_str(), *code);
}
assert_eq!(Signal::ALL.iter().filter(|s| s.is_arithmetic()).count(), 1);
}
}