File size: 8,323 Bytes
8308777
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""
ObservationGenerator — derives partial, role-specific observations from
the hidden world state.

Defender observation (partial + noisy):
  - Transaction velocity per account
  - Refund ratio per account
  - Device reuse count
  - Merchant anomaly scores
  - Freeze/flag status
  - Active alerts
  - Noisy risk signals (ground truth hidden)

Fraudster observation (partial + operational):
  - Available fraud routes (not frozen)
  - Detection pressure per route
  - Account balances on mule accounts
  - Cashout readiness signal
  - Frozen/blocked status of their resources
"""
from __future__ import annotations

import random
from typing import Any, Dict, List

from scam_detection.constants import OBSERVATION_NOISE_LEVEL
from scam_detection.hidden_world_state import HiddenWorldState


class ObservationGenerator:
    """
    Produces role-specific partial observations from the hidden world state.

    Neither observation reveals ground-truth fraud labels directly.
    The defender sees noisy risk signals; the fraudster sees the
    operational state of their own resources.
    """

    def __init__(self, noise_level: float = OBSERVATION_NOISE_LEVEL) -> None:
        self._noise = noise_level

    # =========================================================================
    # Defender observation
    # =========================================================================

    def defender_observation(self, world: HiddenWorldState) -> Dict[str, Any]:
        """
        Build the defender's partial, noisy observation.

        Returns a dict with graph-like features derived from recent
        transactions, account history, and device usage.
        """
        rng = random.Random(world.seed ^ world.step ^ 0xDEF)

        # Per-account transaction velocity (last 5 steps)
        recent_cutoff = max(0, world.step - 5)
        velocity: Dict[str, int] = {}
        refund_counts: Dict[str, int] = {}
        for tx in world.transactions:
            if tx.timestamp >= recent_cutoff:
                velocity[tx.from_user_id] = velocity.get(tx.from_user_id, 0) + 1
                if tx.is_refunded:
                    refund_counts[tx.from_user_id] = (
                        refund_counts.get(tx.from_user_id, 0) + 1
                    )

        # Account-level features (noisy risk scores)
        accounts = []
        for uid, user in world.users.items():
            v = velocity.get(uid, 0)
            r = refund_counts.get(uid, 0)
            dev = world.devices.get(user.device_id)
            dev_reuse = dev.reuse_count if dev else 0
            # Add noise to risk_score to prevent direct leakage of ground truth
            noisy_risk = self._add_noise(user.risk_score, rng)
            accounts.append({
                "id": uid,
                "transaction_velocity": v,
                "refund_count": r,
                "refund_ratio": round(r / max(1, user.transaction_count), 3),
                "device_reuse_count": dev_reuse,
                "is_frozen": user.is_frozen,
                "is_challenged": user.is_challenged,
                "is_monitored": user.is_monitored,
                "risk_score": round(noisy_risk, 3),
                "balance_range": self._bucket_balance(user.balance),
            })

        # Merchant-level features
        merchants = []
        for mid, merchant in world.merchants.items():
            noisy_anomaly = self._add_noise(merchant.anomaly_score, rng)
            merchants.append({
                "id": mid,
                "transaction_count": merchant.transaction_count,
                "refund_rate": round(merchant.refund_rate, 3),
                "anomaly_score": round(noisy_anomaly, 3),
                "is_blocked": merchant.is_blocked,
                "is_monitored": merchant.is_monitored,
            })

        # Active alerts generated by the environment
        alerts = list(world.defender_alerts[-10:])  # show last 10 alerts

        # Step budget and aggregate stats
        return {
            "step": world.step,
            "fraud_family_hint": self._family_hint(world.fraud_family, rng),
            "accounts": accounts,
            "merchants": merchants,
            "alerts": alerts,
            "aggregate": {
                "total_frozen": sum(1 for u in world.users.values() if u.is_frozen),
                "total_monitored": len(world.monitored_accounts),
                "total_flagged": len(world.flagged_accounts),
                "blocked_merchants": sum(
                    1 for m in world.merchants.values() if m.is_blocked
                ),
                "recent_transaction_count": sum(velocity.values()),
            },
        }

    # =========================================================================
    # Fraudster observation
    # =========================================================================

    def fraudster_observation(self, world: HiddenWorldState) -> Dict[str, Any]:
        """
        Build the fraudster's partial operational observation.

        The fraudster knows about their own routes, mule accounts, and
        resources, but sees the defender's detection pressure as a signal.
        """
        routes_obs = []
        for route in world.fraud_routes:
            if not route.is_active:
                continue
            mule_status = []
            for mid in route.mule_ids:
                user = world.users.get(mid)
                if user:
                    mule_status.append({
                        "id": mid,
                        "is_frozen": user.is_frozen,
                        "is_challenged": user.is_challenged,
                        "balance": round(user.balance, 2),
                        "device_id": user.device_id,
                    })

            merchant_blocked = False
            if route.merchant_id:
                m = world.merchants.get(route.merchant_id)
                merchant_blocked = m.is_blocked if m else False

            cashout_ready = (
                any(not s["is_frozen"] for s in mule_status)
                and not merchant_blocked
                and world.fraudster_delayed_steps == 0
            )

            routes_obs.append({
                "id": route.id,
                "family": route.family,
                "detection_pressure": round(route.detection_pressure, 3),
                "mule_status": mule_status,
                "merchant_blocked": merchant_blocked,
                "total_laundered": round(route.total_laundered, 2),
                "cashout_ready": cashout_ready,
                "steps_active": route.steps_active,
            })

        # Available actions summary
        any_route_ready = any(r["cashout_ready"] for r in routes_obs)
        active_mules = [
            uid for uid, u in world.users.items()
            if u.is_mule and not u.is_frozen and u.is_fraudster_controlled
        ]

        return {
            "step": world.step,
            "alert_level": round(world.fraudster_alert_level, 3),
            "delayed_steps_remaining": world.fraudster_delayed_steps,
            "active_routes": routes_obs,
            "available_mule_ids": active_mules,
            "any_cashout_ready": any_route_ready,
            "total_laundered_so_far": round(world.total_laundered, 2),
            "available_fraud_families": [world.fraud_family],
        }

    # =========================================================================
    # Helpers
    # =========================================================================

    def _add_noise(self, value: float, rng: random.Random) -> float:
        noise = rng.gauss(0, self._noise)
        return max(0.0, min(1.0, value + noise))

    def _bucket_balance(self, balance: float) -> str:
        if balance < 100:
            return "very_low"
        if balance < 500:
            return "low"
        if balance < 2000:
            return "medium"
        return "high"

    def _family_hint(self, family: str, rng: random.Random) -> str:
        """Return a noisy hint about the fraud family type."""
        families = ["refund_abuse", "mule_cashout", "merchant_collusion", "account_takeover"]
        if rng.random() < 0.8:
            return family  # correct hint 80% of the time
        return rng.choice([f for f in families if f != family])