diabolical-x5f-engine.txt
"""
DIABOLICAL Engine - Schematic / Research Skeleton
Dual-Intent: Review Fraud (Head A) + Trafficking Risk Referral (Head B)
MODEL ONLY - Synthetic data, no live API, no private data, no accusation.
Manifest: albertlane.net | https://albertlane.net
Safety: Never names a person/business/government as trafficker from score alone.
Referral only to NHTH 1-888-373-7888, DHS 1-866-347-2423, or 911 if emergency.
"""
import hashlib, math, re
from collections import defaultdict, Counter
from dataclasses import dataclass, field
from typing import Dict, List, Set
# Try networkx, fallback to simple dict graph if not available
try:
import networkx as nx
HAS_NX = True
except ImportError:
HAS_NX = False
def salted_hash(value: str, salt: str = "diabolical-salt-v1") -> str:
if not value:
return ""
return hashlib.sha256((salt + value.strip().lower()).encode()).hexdigest()[:16]
def shingles(text: str, k: int = 3) -> Set[str]:
words = re.findall(r"[a-z0-9]+", text.lower())
if len(words) < k:
return set([" ".join(words)])
return set(" ".join(words[i:i+k]) for i in range(len(words)-k+1))
def jaccard(a: Set[str], b: Set[str]) -> float:
if not a or not b:
return 0.0
return len(a & b) / len(a | b)
@dataclass
class Node:
id: str
type: str # ACCOUNT, POST, TEMPLATE, DOMAIN, IP, ASN, NS, CERT, PHONE_HASH, BUSINESS, GOV_CONTRACT, LOCATION
attrs: dict = field(default_factory=dict)
@dataclass
class Post:
id: str
account_id: str
text: str
city: str
timestamp_hour: int
phone: str = ""
domain: str = ""
is_review: bool = False
business_id: str = ""
rating: int = 0
class DiabolicalEngine:
def __init__(self):
self.nodes: Dict[str, Node] = {}
self.edges: List[tuple] = [] # (src, dst, edge_type, weight)
self.posts: List[Post] = []
self.phone_to_accounts = defaultdict(set)
self.template_to_posts = defaultdict(list)
self.domain_to_ip = defaultdict(set)
self.domain_to_cert = defaultdict(set)
self.domain_to_ns = defaultdict(set)
self.domain_to_asn = defaultdict(set)
def add_node(self, nid: str, ntype: str, **attrs):
if nid not in self.nodes:
self.nodes[nid] = Node(nid, ntype, attrs)
return nid
def add_edge(self, src: str, dst: str, etype: str, weight: float = 1.0):
self.edges.append((src, dst, etype, weight))
# ---- Semantic ----
def add_post(self, post: Post):
self.posts.append(post)
self.add_node(post.account_id, "ACCOUNT")
self.add_node(post.id, "POST", text_hash=hashlib.sha256(post.text.encode()).hexdigest()[:12], city=post.city)
self.add_edge(post.id, post.account_id, "POSTED_BY")
# Template fingerprint
sh = shingles(post.text)
# Find existing template with high Jaccard
matched = None
for tid, plist in list(self.template_to_posts.items()):
# compare to first post in template cluster
first = next((p for p in self.posts if p.id == plist[0]), None)
if first and jaccard(sh, shingles(first.text)) > 0.75:
matched = tid
break
if matched is None:
matched = f"TEMPLATE:{len(self.template_to_posts)+1}"
self.add_node(matched, "TEMPLATE", shingles=list(sh)[:5])
self.template_to_posts[matched].append(post.id)
self.add_edge(post.id, matched, "SHARES_TEMPLATE", weight=jaccard(sh, shingles(post.text)))
if post.phone:
ph = salted_hash(post.phone)
ph_node = f"PHONE:{ph}"
self.add_node(ph_node, "PHONE_HASH")
self.add_edge(post.account_id, ph_node, "SHARES_PHONE")
self.phone_to_accounts[ph].add(post.account_id)
if post.domain:
dnode = f"DOMAIN:{post.domain.lower()}"
self.add_node(dnode, "DOMAIN", domain=post.domain)
self.add_edge(post.id, dnode, "LINKS_TO")
if post.business_id:
bnode = f"BUSINESS:{post.business_id}"
self.add_node(bnode, "BUSINESS")
self.add_edge(post.id, bnode, "REVIEWS", weight=post.rating)
return matched
def add_dns(self, domain: str, ip: str, asn: str, ns: str, cert_sha: str):
dnode = f"DOMAIN:{domain.lower()}"
inode = f"IP:{ip}"
anode = f"ASN:{asn}"
nnode = f"NS:{ns.lower()}"
cnode = f"CERT:{cert_sha[:16]}"
self.add_node(dnode, "DOMAIN", domain=domain)
self.add_node(inode, "IP", ip=ip)
self.add_node(anode, "ASN", asn=asn)
self.add_node(nnode, "NS", ns=ns)
self.add_node(cnode, "CERT", cert_sha=cert_sha)
self.add_edge(dnode, inode, "RESOLVES_TO")
self.add_edge(inode, anode, "HOSTED_ON")
self.add_edge(dnode, nnode, "USES_NS")
self.add_edge(dnode, cnode, "USES_CERT")
self.domain_to_ip[domain].add(ip)
self.domain_to_cert[domain].add(cert_sha)
self.domain_to_ns[domain].add(ns)
self.domain_to_asn[domain].add(asn)
def add_gov_contract(self, business_id: str, contract_id: str, amount: float, agency: str):
bnode = f"BUSINESS:{business_id}"
gnode = f"GOV:{contract_id}"
self.add_node(bnode, "BUSINESS")
self.add_node(gnode, "GOV_CONTRACT", amount=amount, agency=agency)
self.add_edge(bnode, gnode, "CONTRACTS_WITH", weight=amount)
# ---- Scores ----
def infrastructure_reuse(self, domains: List[str]) -> float:
# Reuse = D / (C + I + N)
D = len(domains)
if D == 0:
return 0.0
certs = set()
ips = set()
nss = set()
for d in domains:
certs |= self.domain_to_cert.get(d, set())
ips |= self.domain_to_ip.get(d, set())
nss |= self.domain_to_ns.get(d, set())
denom = len(certs) + len(ips) + len(nss)
if denom == 0:
return 0.0
return D / denom
def coordination_score(self, window_hours: int = 1) -> float:
# Synthetic: count accounts sharing same template in same hour bucket
# Real: use X API temporal window + CooRTweet logic
buckets = defaultdict(list)
for p in self.posts:
# find template
for tid, plist in self.template_to_posts.items():
if p.id in plist:
buckets[(tid, p.timestamp_hour // window_hours)].append(p.account_id)
max_cluster = 0
for key, accts in buckets.items():
max_cluster = max(max_cluster, len(set(accts)))
# Normalize: 50 accounts in 1h = 1.0
return min(1.0, max_cluster / 50.0)
def score_review_fraud(self, business_id: str) -> Dict:
# Co-review + template + burst for one business
biz_posts = [p for p in self.posts if p.business_id == business_id]
if not biz_posts:
return {"business": business_id, "score": 0.0, "signals": {}}
# Burst: posts in same hour
hour_counts = Counter(p.timestamp_hour for p in biz_posts)
burst = max(hour_counts.values()) / max(1, len(biz_posts))
# Template reuse
template_reuse = 0.0
for tid, plist in self.template_to_posts.items():
biz_in_template = [pid for pid in plist if any(p.id == pid and p.business_id == business_id for p in biz_posts)]
if len(biz_in_template) > 1:
template_reuse = max(template_reuse, len(biz_in_template) / max(1, len(biz_posts)))
# Single-review accounts
acct_counts = Counter(p.account_id for p in biz_posts)
single = sum(1 for c in acct_counts.values() if c == 1) / max(1, len(acct_counts))
# 5-star bias
five = sum(1 for p in biz_posts if p.rating == 5) / max(1, len(biz_posts))
score = 0.35*burst + 0.30*template_reuse + 0.20*single + 0.15*five
return {
"business": business_id,
"score": round(score, 3),
"signals": {"burst": round(burst,3), "template_reuse": round(template_reuse,3), "single_review_accts": round(single,3), "five_star_rate": round(five,3)},
"action": "LEVEL 0 log" if score < 0.3 else "LEVEL 1 downrank" if score < 0.5 else "LEVEL 2 verify" if score < 0.7 else "LEVEL 3 human review" if score < 0.85 else "LEVEL 4 human + corroboration, no auto-ban"
}
def score_trafficking_risk(self, phone: str, domains: List[str]) -> Dict:
# MODEL ONLY - de-identified, phone is hashed inside
ph = salted_hash(phone)
accounts = self.phone_to_accounts.get(ph, set())
# Movement: distinct cities for posts with this phone
cities = set(p.city for p in self.posts if salted_hash(p.phone) == ph)
movement = min(1.0, len(cities) / 5.0) # 5 cities in window = high
# Shared management: accounts sharing phone
shared = min(1.0, len(accounts) / 5.0)
# Template: control language - simplified: "she is", "manager", "just visiting", "new in town"
control_keywords = ["she is", "manager", "just visiting", "new in town", "available 24", "no questions"]
template_hits = 0
total = 0
for p in self.posts:
if salted_hash(p.phone) == ph:
total += 1
low = p.text.lower()
if any(k in low for k in control_keywords):
template_hits += 1
template_score = (template_hits / total) if total else 0.0
infra = self.infrastructure_reuse(domains)
infra_norm = min(1.0, infra / 2.0) # Reuse >2 = high
risk = 0.30*template_score + 0.25*movement + 0.25*shared + 0.20*infra_norm
return {
"phone_hash": ph,
"risk": round(risk, 3),
"signals": {"template_control": round(template_score,3), "movement_cities": len(cities), "movement_score": round(movement,3), "shared_accounts": len(accounts), "shared_score": round(shared,3), "infra_reuse": round(infra,3), "infra_norm": round(infra_norm,3)},
"action": "No action, log" if risk < 0.5 else "Human review queue, de-identified" if risk < 0.7 else "Human review + corroboration required" if risk < 0.85 else "Referral packet to NHTH/DHS, NO public accusation, NO contact with victim"
}
def score_governance_overlap(self, business_id: str, trafficking_risk: float) -> Dict:
# Count gov contracts for business
gov_edges = [e for e in self.edges if e[0] == f"BUSINESS:{business_id}" and e[2] == "CONTRACTS_WITH"]
G = len(gov_edges)
gov_risk_raw = trafficking_risk * math.log(1+G) if G>0 else 0.0
gov_risk = min(1.0, gov_risk_raw)
return {
"business": business_id,
"gov_links": G,
"trafficking_risk": trafficking_risk,
"governance_risk": round(gov_risk, 3),
"interpretation": "High governance risk = high trafficking risk + public embedding. Priority for human review, NOT proof of guilt. Governance link can be innocent (shared building, license, etc.)."
}
def human_review_packet(self, business_id: str, risk_dict: Dict) -> Dict:
# De-identified packet - never includes names, phones, images, victim data
return {
"packet_id": f"PKT-{hashlib.sha256(business_id.encode()).hexdigest()[:8]}",
"business_hash": hashlib.sha256(business_id.encode()).hexdigest()[:12],
"risk": risk_dict,
"evidence_types": ["template fingerprint", "movement cities count", "shared phone hash count", "infra reuse", "gov contract count"],
"required_corroboration": "2 independent signals + 2 human reviewers (1 anti-trafficking trained, 1 legal) before referral",
"forbidden": ["Do NOT publish", "Do NOT contact victim", "Do NOT name official", "Do NOT post on X"],
"referral_if_confirmed": "NHTH 1-888-373-7888, Text HELP to 233733, DHS 1-866-347-2423, or 911 if emergency"
}
# ---- Demo with synthetic data ----
if __name__ == "__main__":
eng = DiabolicalEngine()
# Synthetic X + Review posts - review fraud cluster
for i in range(12):
eng.add_post(Post(id=f"p{i}", account_id=f"acct_fraud_{i}", text="Best service ever!!! Highly recommend!!! Call now amazing!!!", city="Beaverton", timestamp_hour=10, phone="555-0100", domain="example-reviews.com", is_review=True, business_id="biz_hotel_1", rating=5))
# Synthetic trafficking-risk cluster - MODEL, synthetic, no real victim
for i, city in enumerate(["Portland", "Seattle", "Boise", "Spokane", "Portland"]):
eng.add_post(Post(id=f"t{i}", account_id=f"acct_t_{i}", text="Just visiting, new in town, she is available, call manager, no questions", city=city, timestamp_hour=10+i, phone="555-0199", domain="example-ads.com"))
# DNS
for d in ["example-reviews.com", "example-ads.com", "example-ads2.com"]:
eng.add_dns(d, "203.0.113.10", "AS13335 Cloudflare", "ns1.cloudflare.com", "cert-abc-123")
eng.add_dns("example-ads2.com", "203.0.113.10", "AS13335 Cloudflare", "ns1.cloudflare.com", "cert-abc-123")
# Gov contract overlap - MODEL
eng.add_gov_contract("biz_hotel_1", "CONTRACT-2026-001", 50000, "City Cleaning")
print("Review Fraud:", eng.score_review_fraud("biz_hotel_1"))
print("Coordination:", eng.coordination_score())
print("Infra Reuse:", eng.infrastructure_reuse(["example-reviews.com", "example-ads.com", "example-ads2.com"]))
risk = eng.score_trafficking_risk("555-0199", ["example-ads.com", "example-ads2.com"])
print("Trafficking Risk (MODEL, synthetic):", risk)
print("Governance Overlap:", eng.score_governance_overlap("biz_hotel_1", risk["risk"]))
print("Human Review Packet:", eng.human_review_packet("biz_hotel_1", risk))
print("\nNodes:", len(eng.nodes), "Edges:", len(eng.edges), "Posts:", len(eng.posts))