1use std::collections::{HashMap, HashSet};
15
16const MIN_SKELETON_LEN: usize = 8;
19
20const COHORT_PAYLOAD_LEN: usize = 12;
23
24pub fn skeleton(text: &str) -> String {
33 skeleton_with(text, &HashSet::new())
34}
35
36pub fn skeleton_with(text: &str, known: &HashSet<String>) -> String {
40 strip_shortcodes(text, known)
41 .chars()
42 .filter(|c| c.is_alphanumeric() && !c.is_numeric())
43 .flat_map(|c| c.to_lowercase())
44 .collect()
45}
46
47fn strip_shortcodes(text: &str, known: &HashSet<String>) -> String {
52 let mut out = String::with_capacity(text.len());
53 let mut rest = text;
54 while let Some(open) = rest.find(':') {
55 out.push_str(&rest[..open]);
56 let after = &rest[open + 1..];
57 let close = after.find(':').filter(|end| {
58 *end > 0 && after[..*end].chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '+')
59 });
60 match close {
61 Some(end) => {
62 let name = &after[..end];
63 if !known.contains(name) && name.chars().count() >= MIN_SKELETON_LEN {
64 out.push_str(name);
65 }
66 rest = &after[end + 1..];
67 }
68 None => {
69 out.push(':');
70 rest = after;
71 }
72 }
73 }
74 out.push_str(rest);
75 out
76}
77
78#[derive(Debug, Clone)]
81pub struct RaidParams {
82 pub fresh_join_secs: u64,
84 pub trusted_tenure_secs: u64,
86 pub trusted_messages: u64,
88 pub trusted_distinct: u64,
90 pub quiet_messages: u64,
92 pub min_cohort: usize,
94 pub short_text_factor: usize,
96 pub burst_gap_secs: u64,
98 pub cohort_span_secs: u64,
101 pub min_burst: usize,
103 pub known_shortcodes: HashSet<String>,
105}
106
107impl Default for RaidParams {
108 fn default() -> Self {
109 Self {
110 fresh_join_secs: 24 * 60 * 60,
111 trusted_tenure_secs: 7 * 24 * 60 * 60,
112 trusted_messages: 5,
113 trusted_distinct: 3,
114 quiet_messages: 2,
115 min_cohort: 3,
116 short_text_factor: 3,
117 burst_gap_secs: 10 * 60,
118 cohort_span_secs: 15 * 60,
119 min_burst: 5,
120 known_shortcodes: HashSet::new(),
121 }
122 }
123}
124
125#[derive(Debug, Clone, Default)]
127pub struct MemberSignals {
128 pub npub: String,
129 pub joined_at_ms: u64,
131 pub invite_label: Option<String>,
133 pub messages: u64,
134 pub first_secs: u64,
136 pub last_secs: u64,
137 pub texts: Vec<String>,
139 pub text_secs: Vec<u64>,
142 pub is_owner: bool,
143 pub is_admin: bool,
144 pub is_me: bool,
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
149#[serde(rename_all = "lowercase")]
150pub enum Verdict {
151 Protected,
153 Trusted,
155 Neutral,
157 Suspect,
159}
160
161#[derive(Debug, Clone, serde::Serialize)]
163pub struct MemberAssessment {
164 pub npub: String,
165 pub verdict: Verdict,
166 pub score: u32,
168 pub reasons: Vec<String>,
169 pub joined_at_ms: u64,
170 pub invite_label: Option<String>,
171 pub messages: u64,
172 pub distinct: u64,
174 pub cohort: u64,
176 pub tenure_secs: u64,
178 pub last_secs: u64,
179 pub is_owner: bool,
180 pub is_admin: bool,
181 pub is_me: bool,
182}
183
184const COHORT_SAMPLE_CAP: usize = 24;
188
189#[derive(Debug, Clone, serde::Serialize)]
191pub struct Cohort {
192 pub sample: String,
194 pub size: usize,
196 pub members: Vec<String>,
197}
198
199#[derive(Debug, Clone, serde::Serialize)]
201pub struct RaidReport {
202 pub members: Vec<MemberAssessment>,
203 pub suspects: usize,
204 pub trusted: usize,
205 pub protected: usize,
206 pub cohorts: Vec<Cohort>,
207 pub burst_size: usize,
209 pub burst_from_ms: u64,
211 pub burst_to_ms: u64,
212 pub raid_detected: bool,
215}
216
217fn densest_senders(mut at: Vec<(u64, &str)>, span_secs: u64) -> HashSet<String> {
220 let unknown: Vec<&str> = at.iter().filter(|(t, _)| *t == 0).map(|(_, n)| *n).collect();
221 at.retain(|(t, _)| *t != 0);
222 at.sort();
223 let mut inside: HashMap<&str, usize> = HashMap::new();
224 let (mut best, mut best_len, mut start) = ((0usize, 0usize), 0usize, 0usize);
225 for end in 0..at.len() {
226 *inside.entry(at[end].1).or_insert(0) += 1;
227 while at[end].0.saturating_sub(at[start].0) > span_secs {
228 if let Some(n) = inside.get_mut(at[start].1) {
229 *n -= 1;
230 if *n == 0 {
231 inside.remove(at[start].1);
232 }
233 }
234 start += 1;
235 }
236 if inside.len() > best_len {
237 best_len = inside.len();
238 best = (start, end + 1);
239 }
240 }
241 at[best.0..best.1].iter().map(|(_, n)| *n).chain(unknown).map(str::to_string).collect()
242}
243
244pub fn assess(signals: &[MemberSignals], now_secs: u64, p: &RaidParams) -> RaidReport {
247 let mut said: HashMap<String, Vec<(u64, &str)>> = HashMap::new();
249 let mut sample_of: HashMap<String, String> = HashMap::new();
250 let mut repeats: HashMap<(&str, String), u64> = HashMap::new();
253 for s in signals {
254 for (i, t) in s.texts.iter().enumerate() {
255 let sk = skeleton_with(t, &p.known_shortcodes);
256 if sk.is_empty() {
257 continue;
258 }
259 said.entry(sk.clone()).or_default().push((s.text_secs.get(i).copied().unwrap_or(0), s.npub.as_str()));
260 *repeats.entry((s.npub.as_str(), sk.clone())).or_insert(0) += 1;
261 sample_of.entry(sk).or_insert_with(|| t.clone());
262 }
263 }
264 let by_skeleton: HashMap<String, HashSet<String>> =
265 said.into_iter().map(|(sk, at)| (sk, densest_senders(at, p.cohort_span_secs))).collect();
266 let volume: HashMap<&str, u64> = signals.iter().map(|s| (s.npub.as_str(), s.messages)).collect();
267 let convicting = |sk: &str, members: &HashSet<String>| -> bool {
273 let need = if sk.chars().count() < COHORT_PAYLOAD_LEN {
274 p.min_cohort.saturating_mul(p.short_text_factor)
275 } else {
276 p.min_cohort
277 };
278 if members.len() < need {
279 return false;
280 }
281 let thin = members
282 .iter()
283 .filter(|n| volume.get(n.as_str()).copied().unwrap_or(0) <= p.quiet_messages)
284 .count();
285 thin * 2 >= members.len()
286 };
287
288 let mut cohorts: Vec<Cohort> = Vec::new();
289 let mut cohort_of: HashMap<String, u64> = HashMap::new();
291 for (sk, members) in &by_skeleton {
292 if !convicting(sk, members) {
293 continue;
294 }
295 let peers = members.len().saturating_sub(1) as u64;
296 for m in members {
297 let own = repeats.get(&(m.as_str(), sk.clone())).copied().unwrap_or(0);
298 if own.saturating_mul(2) < volume.get(m.as_str()).copied().unwrap_or(0) {
299 continue;
300 }
301 let e = cohort_of.entry(m.clone()).or_insert(0);
302 *e = (*e).max(peers);
303 }
304 let mut list: Vec<String> = members.iter().cloned().collect();
305 list.sort();
306 let size = list.len();
307 list.truncate(COHORT_SAMPLE_CAP);
308 cohorts.push(Cohort { sample: sample_of.get(sk).cloned().unwrap_or_default(), size, members: list });
309 }
310 cohorts.sort_by_key(|c| std::cmp::Reverse(c.size));
311
312 let mut joins: Vec<(u64, &str)> = signals
314 .iter()
315 .filter(|s| s.joined_at_ms > 0 && !s.is_owner)
316 .map(|s| (s.joined_at_ms, s.npub.as_str()))
317 .collect();
318 joins.sort_by_key(|(at, _)| *at);
319 let gap_ms = p.burst_gap_secs.saturating_mul(1000);
320 let mut best: (usize, usize) = (0, 0); let mut start = 0usize;
322 for end in 0..joins.len() {
323 while joins[end].0.saturating_sub(joins[start].0) > gap_ms {
324 start += 1;
325 }
326 if end + 1 - start > best.1 - best.0 {
327 best = (start, end + 1);
328 }
329 }
330 let burst: HashSet<&str> = if best.1 - best.0 >= p.min_burst {
331 joins[best.0..best.1].iter().map(|(_, n)| *n).collect()
332 } else {
333 HashSet::new()
334 };
335 let (burst_from_ms, burst_to_ms) = if burst.is_empty() {
336 (0, 0)
337 } else {
338 (joins[best.0].0, joins[best.1 - 1].0)
339 };
340 let burst_convicted = burst.iter().filter(|n| cohort_of.contains_key(**n)).count() >= p.min_cohort;
343
344 let now_ms = now_secs.saturating_mul(1000);
346 let mut members: Vec<MemberAssessment> = Vec::with_capacity(signals.len());
347 for s in signals {
348 let distinct: u64 = s.texts.iter().map(|t| skeleton_with(t, &p.known_shortcodes)).filter(|sk| !sk.is_empty()).collect::<HashSet<_>>().len() as u64;
349 let cohort = cohort_of.get(&s.npub).copied().unwrap_or(0);
350 let in_burst = burst.contains(s.npub.as_str());
351 let first_seen_secs = match (s.joined_at_ms / 1000, s.first_secs) {
353 (0, f) => f,
354 (j, 0) => j,
355 (j, f) => j.min(f),
356 };
357 let tenure_secs = if first_seen_secs == 0 { 0 } else { now_secs.saturating_sub(first_seen_secs) };
358 let fresh = s.joined_at_ms > 0 && now_ms.saturating_sub(s.joined_at_ms) <= p.fresh_join_secs.saturating_mul(1000);
359
360 let mut reasons: Vec<String> = Vec::new();
361 let mut score: u32 = 0;
362
363 let verdict = if s.is_owner || s.is_me || s.is_admin {
364 if s.is_owner {
365 reasons.push("Community owner".into());
366 } else if s.is_me {
367 reasons.push("You".into());
368 } else {
369 reasons.push("Holds a role".into());
370 }
371 Verdict::Protected
372 } else {
373 if cohort > 0 {
374 score += 40 + (cohort.min(50) as u32);
375 reasons.push(format!("Posted the same message as {cohort} other member{}", if cohort == 1 { "" } else { "s" }));
376 }
377 if in_burst && burst_convicted {
378 score += 15;
379 reasons.push(format!("Joined in a burst of {}", burst.len()));
380 }
381 if fresh {
382 score += 10;
383 reasons.push("Joined in the last 24h".into());
384 }
385 if s.messages == 0 {
386 score += 5;
387 reasons.push("Has never posted".into());
388 } else if s.messages <= p.quiet_messages {
389 score += 5;
390 reasons.push(format!("Only {} message{}", s.messages, if s.messages == 1 { "" } else { "s" }));
391 }
392 if s.messages >= 2 && distinct == 1 {
393 score += 10;
394 reasons.push("Repeats one message".into());
395 }
396
397 let long_tenure = tenure_secs >= p.trusted_tenure_secs;
398 let talks = s.messages >= p.trusted_messages;
399 let varied = distinct >= p.trusted_distinct;
400
401 if talks && (long_tenure || varied) {
405 reasons.clear();
407 reasons.push(if long_tenure && talks {
408 "Long-standing, active member".to_string()
409 } else {
410 "Varied conversation history".to_string()
411 });
412 Verdict::Trusted
413 } else if cohort > 0 || (in_burst && burst_convicted && s.messages == 0) {
414 Verdict::Suspect
415 } else {
416 Verdict::Neutral
417 }
418 };
419
420 members.push(MemberAssessment {
421 npub: s.npub.clone(),
422 verdict,
423 score,
424 reasons,
425 joined_at_ms: s.joined_at_ms,
426 invite_label: s.invite_label.clone(),
427 messages: s.messages,
428 distinct,
429 cohort,
430 tenure_secs,
431 last_secs: s.last_secs,
432 is_owner: s.is_owner,
433 is_admin: s.is_admin,
434 is_me: s.is_me,
435 });
436 }
437
438 members.sort_by(|a, b| {
441 let rank = |v: Verdict| match v {
442 Verdict::Suspect => 0,
443 Verdict::Neutral => 1,
444 Verdict::Trusted => 2,
445 Verdict::Protected => 3,
446 };
447 rank(a.verdict).cmp(&rank(b.verdict)).then(b.score.cmp(&a.score)).then(a.npub.cmp(&b.npub))
448 });
449
450 let suspects = members.iter().filter(|m| m.verdict == Verdict::Suspect).count();
451 let trusted = members.iter().filter(|m| m.verdict == Verdict::Trusted).count();
452 let protected = members.iter().filter(|m| m.verdict == Verdict::Protected).count();
453 RaidReport {
454 raid_detected: suspects >= p.min_cohort && !cohorts.is_empty(),
455 members,
456 suspects,
457 trusted,
458 protected,
459 cohorts,
460 burst_size: burst.len(),
461 burst_from_ms,
462 burst_to_ms,
463 }
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469
470 const HOUR: u64 = 3_600;
471 const DAY: u64 = 86_400;
472
473 fn member(npub: &str) -> MemberSignals {
474 MemberSignals { npub: npub.to_string(), ..Default::default() }
475 }
476
477 const NOW: u64 = 1_700_000_000;
479
480 fn raider(npub: &str, at_secs: u64, text: &str) -> MemberSignals {
481 MemberSignals {
482 npub: npub.to_string(),
483 joined_at_ms: at_secs * 1000,
484 messages: 1,
485 first_secs: at_secs,
486 last_secs: at_secs,
487 texts: vec![text.to_string()],
488 ..Default::default()
489 }
490 }
491
492 fn regular(npub: &str, joined_days_ago: u64, messages: u64, texts: &[&str]) -> MemberSignals {
493 let joined = NOW - joined_days_ago * DAY;
494 MemberSignals {
495 npub: npub.to_string(),
496 joined_at_ms: joined * 1000,
497 messages,
498 first_secs: joined,
499 last_secs: NOW - HOUR,
500 texts: texts.iter().map(|t| t.to_string()).collect(),
501 ..Default::default()
502 }
503 }
504
505 #[test]
506 fn skeleton_ignores_the_cheap_variations() {
507 assert_eq!(skeleton("Hello World!"), skeleton("hello, world"));
508 assert_eq!(skeleton("hello world 123"), skeleton("HELLO WORLD 4567"));
509 assert_ne!(skeleton("hello world"), skeleton("goodbye world"));
510 }
511
512 #[test]
513 fn a_payload_wrapped_in_colons_still_has_a_skeleton() {
514 assert_eq!(skeleton(":buycheapcoinsnow:"), "buycheapcoinsnow");
515 assert!(skeleton(":fire:").is_empty());
517 assert!(skeleton(":+1:").is_empty());
518 assert_eq!(skeleton("nice one :fire:"), skeleton("nice one"));
519 let known = HashSet::from(["buycheapcoinsnow".to_string()]);
520 assert!(skeleton_with(":buycheapcoinsnow:", &known).is_empty());
521 }
522
523 #[test]
524 fn a_cohort_hiding_behind_shortcode_colons_still_convicts() {
525 let mut signals: Vec<MemberSignals> = (0..40)
526 .map(|i| raider(&format!("npub_raider_{i}"), NOW - 60, ":freeairdropclaimnow:"))
527 .collect();
528 signals.push(regular("npub_owner", 400, 900, &["morning all", "shipping today", "nice one"]));
529 signals[40].is_owner = true;
530
531 let r = assess(&signals, NOW, &RaidParams::default());
532 assert!(r.raid_detected, "colons must not blind the cohort");
533 assert_eq!(r.suspects, 40);
534 }
535
536 #[test]
537 fn a_hundred_fresh_npubs_saying_one_thing_is_a_raid() {
538 let mut signals: Vec<MemberSignals> = (0..100)
539 .map(|i| raider(&format!("npub_raider_{i}"), NOW - 60, "hello world"))
540 .collect();
541 signals.push(regular("npub_owner", 400, 900, &["morning all", "shipping today", "nice one"]));
542 signals[100].is_owner = true;
543
544 let r = assess(&signals, NOW, &RaidParams::default());
545 assert!(r.raid_detected, "cohort of 100 identical posts must convict");
546 assert_eq!(r.suspects, 100, "every raider, and only the raiders");
547 assert_eq!(r.members.iter().filter(|m| m.verdict == Verdict::Protected).count(), 1);
548 assert_eq!(r.cohorts.len(), 1);
549 assert_eq!(r.cohorts[0].size, 100, "the true size survives the display cap");
550 }
551
552 #[test]
553 fn a_quiet_newcomer_alone_is_not_convicted() {
554 let signals = vec![
555 regular("npub_old", 400, 900, &["morning all", "shipping today", "nice one"]),
556 MemberSignals {
557 npub: "npub_new".into(),
558 joined_at_ms: (NOW - 600) * 1000,
559 messages: 1,
560 first_secs: NOW - 500,
561 last_secs: NOW - 500,
562 texts: vec!["hey everyone, glad to be here".into()],
563 ..Default::default()
564 },
565 ];
566 let r = assess(&signals, NOW, &RaidParams::default());
567 assert_eq!(r.suspects, 0, "freshness alone must never convict");
568 assert_eq!(r.members.iter().find(|m| m.npub == "npub_new").unwrap().verdict, Verdict::Neutral);
569 }
570
571 #[test]
572 fn an_invite_link_burst_of_real_people_is_not_a_raid() {
573 let greetings = [
575 "hi there", "glad to join", "hello from berlin", "whats up", "found this via nostr",
576 "hey all", "good to be here", "long time lurker", "anyone here into rust", "morning",
577 "just joined, what is this about", "greetings", "hello hello", "howdy folks",
578 "nice community", "reading the pins now", "is there a channel for dev talk",
579 "coming over from the other group", "hola", "yo",
580 ];
581 let signals: Vec<MemberSignals> = (0..20)
582 .map(|i| {
583 let at = NOW - 300 + i * 10;
584 MemberSignals {
585 npub: format!("npub_person_{i}"),
586 joined_at_ms: at * 1000,
587 messages: 1,
588 first_secs: at,
589 last_secs: at,
590 texts: vec![greetings[i as usize].to_string()],
591 ..Default::default()
592 }
593 })
594 .collect();
595 let r = assess(&signals, NOW, &RaidParams::default());
596 assert_eq!(r.suspects, 0, "a burst with no duplicate text is just a busy afternoon");
597 assert!(!r.raid_detected);
598 }
599
600 #[test]
601 fn silent_members_of_a_convicted_burst_are_caught_too() {
602 let mut signals: Vec<MemberSignals> = (0..10)
603 .map(|i| raider(&format!("npub_loud_{i}"), NOW - 120 + i, "buy cheap coins now"))
604 .collect();
605 for i in 0..5 {
607 let at = NOW - 100 + i;
608 signals.push(MemberSignals {
609 npub: format!("npub_silent_{i}"),
610 joined_at_ms: at * 1000,
611 ..Default::default()
612 });
613 }
614 let r = assess(&signals, NOW, &RaidParams::default());
615 assert_eq!(r.suspects, 15, "the whole wave, loud and silent");
616 }
617
618 #[test]
619 fn short_shared_text_needs_a_bigger_cohort() {
620 let signals: Vec<MemberSignals> =
622 (0..4).map(|i| raider(&format!("npub_{i}"), NOW - 60 + i, "gm")).collect();
623 let r = assess(&signals, NOW, &RaidParams::default());
624 assert_eq!(r.suspects, 0, "min_cohort * short_text_factor = 9 needed for a 2-char skeleton");
625
626 let many: Vec<MemberSignals> =
627 (0..12).map(|i| raider(&format!("npub_{i}"), NOW - 60 + i, "gm")).collect();
628 assert_eq!(assess(&many, NOW, &RaidParams::default()).suspects, 12);
629 }
630
631 #[test]
632 fn tenure_and_variety_earn_trust_that_survives_a_raid() {
633 let mut signals: Vec<MemberSignals> = (0..20)
634 .map(|i| raider(&format!("npub_raider_{i}"), NOW - 60, "hello world"))
635 .collect();
636 signals.push(regular("npub_veteran", 90, 400, &["morning", "on it", "shipped", "hello world"]));
639 let r = assess(&signals, NOW, &RaidParams::default());
640 let vet = r.members.iter().find(|m| m.npub == "npub_veteran").unwrap();
641 assert_eq!(vet.verdict, Verdict::Trusted, "cohort membership must not outrank real history");
642 assert_eq!(vet.cohort, 0, "one line in four hundred is a member echoing the room, not the wave");
643 assert!(vet.reasons.iter().any(|s| s.contains("Long-standing")));
644 assert_eq!(r.suspects, 20, "the raiders, and only the raiders");
645 }
646
647 #[test]
648 fn role_holders_and_self_are_never_selectable() {
649 let mut admin = member("npub_admin");
650 admin.is_admin = true;
651 admin.joined_at_ms = (NOW - 60) * 1000;
652 admin.texts = vec!["hello world".into()];
653 admin.messages = 1;
654 let mut me = member("npub_me");
655 me.is_me = true;
656 let mut signals = vec![admin, me];
657 signals.extend((0..10).map(|i| raider(&format!("npub_r{i}"), NOW - 60, "hello world")));
658
659 let r = assess(&signals, NOW, &RaidParams::default());
660 assert_eq!(r.members.iter().find(|m| m.npub == "npub_admin").unwrap().verdict, Verdict::Protected);
661 assert_eq!(r.members.iter().find(|m| m.npub == "npub_me").unwrap().verdict, Verdict::Protected);
662 assert_eq!(r.suspects, 10, "protection wins over cohort evidence");
663 }
664
665 #[test]
666 fn the_same_thank_you_hours_apart_is_not_a_cohort() {
667 let mut signals: Vec<MemberSignals> = (0..3)
668 .map(|i| {
669 let mut r = raider(&format!("npub_new_{i}"), NOW - 12 * HOUR + i * 60, "thank you");
670 r.text_secs = vec![NOW - 12 * HOUR + i * 60];
671 r
672 })
673 .collect();
674 let mut chatty = regular("npub_chatty", 2, 60, &["Thank you", "piano", "violin", "python"]);
675 chatty.text_secs = vec![NOW - HOUR, NOW - 2 * HOUR, NOW - 2 * HOUR, NOW - 2 * HOUR];
676 signals.push(chatty);
677 let r = assess(&signals, NOW, &RaidParams::default());
678 assert_eq!(r.suspects, 0);
679 assert!(!r.raid_detected);
680 }
681
682 #[test]
683 fn one_payload_spread_over_hours_is_not_a_cohort() {
684 let signals: Vec<MemberSignals> = (0..6)
685 .map(|i| {
686 let at = NOW - 20 * HOUR + i * 3 * HOUR;
687 let mut r = raider(&format!("npub_r{i}"), at, "free airdrop claim it now");
688 r.text_secs = vec![at];
689 r
690 })
691 .collect();
692 assert_eq!(assess(&signals, NOW, &RaidParams::default()).suspects, 0);
693 }
694
695 #[test]
696 fn a_burst_of_one_payload_is_still_a_cohort() {
697 let signals: Vec<MemberSignals> = (0..6)
698 .map(|i| {
699 let at = NOW - HOUR + i * 30;
700 let mut r = raider(&format!("npub_r{i}"), at, "free airdrop claim it now");
701 r.text_secs = vec![at];
702 r
703 })
704 .collect();
705 assert_eq!(assess(&signals, NOW, &RaidParams::default()).suspects, 6);
706 }
707
708 #[test]
709 fn suspects_sort_ahead_of_everyone_else() {
710 let mut signals = vec![regular("npub_old", 400, 900, &["a", "b", "c", "d", "e"])];
711 signals.extend((0..5).map(|i| raider(&format!("npub_r{i}"), NOW - 60, "free airdrop here")));
712 let r = assess(&signals, NOW, &RaidParams::default());
713 assert!(r.members[0].verdict == Verdict::Suspect);
714 assert_eq!(r.members.last().unwrap().npub, "npub_old");
715 }
716
717 #[test]
718 fn a_community_catchphrase_shared_by_regulars_is_not_a_cohort() {
719 let signals: Vec<MemberSignals> = (0..5)
722 .map(|i| regular(&format!("npub_regular_{i}"), 200, 400, &["gm vectorians", "on it", "shipped it", "nice"]))
723 .collect();
724 let r = assess(&signals, NOW, &RaidParams::default());
725 assert!(r.cohorts.is_empty(), "a shared phrase between chatty members is not evidence");
726 assert_eq!(r.suspects, 0);
727 }
728
729 #[test]
730 fn one_line_identities_still_convict_beside_a_chatty_member() {
731 let mut signals: Vec<MemberSignals> = (0..30)
734 .map(|i| raider(&format!("npub_r{i}"), NOW - 90 + i, "claim your free airdrop"))
735 .collect();
736 signals.push(regular("npub_regular", 200, 400, &["claim your free airdrop", "lol", "sure", "ok"]));
737 let r = assess(&signals, NOW, &RaidParams::default());
738 assert_eq!(r.suspects, 30);
739 assert_eq!(r.members.iter().find(|m| m.npub == "npub_regular").unwrap().verdict, Verdict::Trusted);
740 }
741
742 #[test]
743 fn shared_emoji_reactions_never_form_a_cohort() {
744 let signals: Vec<MemberSignals> = (0..6)
746 .map(|i| raider(&format!("npub_{i}"), NOW - 300 + i, ":vector_logo:"))
747 .collect();
748 let p = RaidParams { known_shortcodes: HashSet::from(["vector_logo".to_string()]), ..Default::default() };
749 let r = assess(&signals, NOW, &p);
750 assert_eq!(r.suspects, 0);
751 assert!(r.cohorts.is_empty(), "an emoji-only message carries no convicting content");
752 }
753
754 #[test]
755 fn a_shortcode_does_not_hide_the_text_around_it() {
756 assert_eq!(skeleton("free airdrop :fire: click here"), skeleton("free airdrop click here"));
757 assert_eq!(skeleton(":smile:"), "");
758 assert_eq!(skeleton("note: buy now"), skeleton("note buy now"));
760 assert!(!skeleton("ratio 3:1 wins").is_empty());
761 }
762
763 #[test]
764 fn an_empty_community_assesses_cleanly() {
765 let r = assess(&[], NOW, &RaidParams::default());
766 assert_eq!(r.suspects, 0);
767 assert!(!r.raid_detected);
768 assert_eq!(r.burst_size, 0);
769 }
770}