Wallet & Address Intelligence
Overview
Wallet address intelligence is the practice of profiling blockchain addresses to identify the entities behind them, assess risk levels, and build behavioral profiles. Unlike simple balance checks, address intelligence combines on-chain transaction analysis, entity clustering heuristics, known-address databases, behavioral pattern matching, and cross-chain correlation. This skill covers building address profiles with transaction demographics, applying clustering algorithms (Cointracking, CommonInput, behavioral similarity), tagging addresses with entity attributions, assessing risk scores for compliance (AML/KYC), sanctions list screening, MEV searcher identification, ENS/social graph resolution, and producing comprehensive address intelligence reports suitable for compliance teams, security analysts, and protocol operators.
When to Use
Trigger phrases:
"wallet address intelligence"
"Profile a blockchain wallet"
"Check if an address is risky"
"Cluster related crypto wallets"
"Build address reputation"
"Run AML screening on an address"
"Find all addresses controlled by the same entity"
"Analyze wallet interaction patterns"
When performing due diligence on a counterparty before a transaction
When investigating suspicious addresses for compliance or AML purposes
When building a wallet clustering system for forensic investigations
When assessing the risk profile of an address interacting with your protocol
When attributing addresses to known entities (exchanges, protocols, exploiters)
When screening addresses against sanctions lists before onboarding
When linking addresses across different blockchains for entity tracking
When identifying MEV bots and searcher strategies
When generating address intelligence reports for law enforcement or compliance
When building a watchlist monitoring system for high-risk addresses
When NOT to Use
- You need to trace stolen funds along a specific path (use onchain-transaction-forensics skill)
- You need to analyze a specific DeFi protocol hack (use defi-incident-analysis skill)
- You need to check if a token is a scam (use token-nft-scam-investigation skill)
- You need real-time transaction monitoring (use a blockchain analytics platform like Chainalysis or Elliptic)
- The address is on a privacy-focused blockchain where clustering is infeasible (Monero, Zcash with shielded transactions)
- You only need a single balance check (use a block explorer or a simple RPC call)
- The target uses a privacy wallet with coin-join or stealth addresses
Prerequisites
- Python 3.8+ with web3.py, requests, pandas, networkx, numpy, jellyfish (fuzzy matching)
- Block explorer API keys (Etherscan, BscScan, Polygonscan, etc.)
- Access to an address labeling dataset (Etherscan labels, tagged addresses from block explorers, known exploiters list)
- Basic understanding of graph theory for clustering algorithms
- Optional: DeBank or similar API for multi-chain wallet views
- Optional: Flashbots API access for MEV bundle data
- Optional: ENS resolution library (web3.py handles this natively)
pip install web3 requests pandas networkx numpy jellyfish
Core Workflow
The core workflow builds a comprehensive address intelligence pipeline: collect data, cluster related addresses, score risk, attribute entities, and produce a report.
Address Profile Builder
import requests
from datetime import datetime, timezone
from typing import Optional
import json
# ============================================================
# BLOCK EXPLORER HELPERS
# ============================================================
ETHERSCAN_BASE = "https://api.etherscan.io/api"
def _fetch_balance(address: str, api_key: str) -> float:
"""Fetch ETH balance from Etherscan."""
params = {"module": "account", "action": "balance", "address": address, "apikey": api_key}
resp = requests.get(ETHERSCAN_BASE, params=params, timeout=15)
data = resp.json()
if data.get("status") == "1":
return int(data["result"]) / 1e18
return 0.0
def _fetch_tx_list(address: str, api_key: str, startblock: int = 0, endblock: int = 99999999) -> list:
"""Fetch normal transaction list for an address."""
params = {"module": "account", "action": "txlist", "address": address,
"startblock": startblock, "endblock": endblock, "sort": "desc", "apikey": api_key}
resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)
data = resp.json()
return data.get("result", [])
def _fetch_internal_tx_list(address: str, api_key: str) -> list:
"""Fetch internal transactions for an address."""
params = {"module": "account", "action": "txlistinternal", "address": address,
"startblock": 0, "endblock": 99999999, "sort": "desc", "apikey": api_key}
resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)
data = resp.json()
return data.get("result", [])
def _fetch_erc20_transfers(address: str, api_key: str) -> list:
"""Fetch ERC-20 token transfer events."""
params = {"module": "account", "action": "tokentx", "address": address,
"startblock": 0, "endblock": 99999999, "sort": "desc", "apikey": api_key}
resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)
data = resp.json()
return data.get("result", [])
def _fetch_nft_transfers(address: str, api_key: str) -> list:
"""Fetch NFT (ERC-721 / ERC-1155) transfer events."""
params = {"module": "account", "action": "tokennfttx", "address": address,
"startblock": 0, "endblock": 99999999, "sort": "desc", "apikey": api_key}
resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)
data = resp.json()
return data.get("result", [])
def _fetch_token_balances(address: str, api_key: str) -> list:
"""Fetch all token balances for an address."""
params = {"module": "account", "action": "tokenlist", "address": address, "apikey": api_key}
resp = requests.get(ETHERSCAN_BASE, params=params, timeout=15)
data = resp.json()
return data.get("result", [])
def build_address_profile(address: str, etherscan_key: str) -> dict:
"""Build a comprehensive profile for a single address."""
profile = {
"address": address,
"tags": [],
"risk_indicators": [],
"activity": {},
"known_labels": [],
"token_holdings": [],
"nft_holdings": [],
"protocols_used": set(),
"interactors": set(),
"gas_profile": {},
}
# 1. Basic balance and transaction count
balance = _fetch_balance(address, etherscan_key)
tx_list = _fetch_tx_list(address, etherscan_key)
internal_txs = _fetch_internal_tx_list(address, etherscan_key)
erc20_txs = _fetch_erc20_transfers(address, etherscan_key)
nft_txs = _fetch_nft_transfers(address, etherscan_key)
profile["eth_balance"] = balance
profile["total_txns"] = len(tx_list)
profile["total_internal_txns"] = len(internal_txs)
profile["total_token_transfers"] = len(erc20_txs)
profile["total_nft_transfers"] = len(nft_txs)
profile["total_activity"] = len(tx_list) + len(internal_txs) + len(erc20_txs)
# 2. First and last activity
all_txs_sorted = sorted(tx_list, key=lambda t: int(t.get("timeStamp", 0)), reverse=True)
if all_txs_sorted:
profile["first_seen"] = datetime.fromtimestamp(int(all_txs_sorted[-1]["timeStamp"]), tz=timezone.utc)
profile["last_active"] = datetime.fromtimestamp(int(all_txs_sorted[0]["timeStamp"]), tz=timezone.utc)
profile["age_days"] = (profile["last_active"] - profile["first_seen"]).days if profile["first_seen"] else 0
# 3. Interaction diversity — unique addresses this address has interacted with
unique_interactors = set()
protocols = set()
gas_prices = []
for tx in all_txs_sorted:
unique_interactors.add(tx["from"].lower())
if tx["to"] and tx["to"] != address.lower():
unique_interactors.add(tx["to"].lower())
protocols.add(tx["to"].lower())
if tx.get("gasPrice"):
gas_prices.append(int(tx["gasPrice"]))
profile["unique_interactors"] = len(unique_interactors)
profile["protocols_touched"] = len(protocols)
# Gas profile
if gas_prices:
profile["gas_profile"] = {
"min_gwei": min(gas_prices) / 1e9,
"max_gwei": max(gas_prices) / 1e9,
"avg_gwei": (sum(gas_prices) / len(gas_prices)) / 1e9,
"total_gas_spent_eth": sum(
int(tx.get("gasUsed", 0)) * int(tx.get("gasPrice", 0)) / 1e18
for tx in all_txs_sorted if tx.get("gasUsed")
),
}
# 4. Token holdings
token_balances = _fetch_token_balances(address, etherscan_key)
profile["token_holdings"] = [
{
"token": t.get("tokenName", "unknown"),
"symbol": t.get("tokenSymbol", "???"),
"contract": t.get("contractAddress", "").lower(),
"balance": float(t.get("balance", 0)) / 10 ** int(t.get("tokenDecimal", 18)),
}
for t in token_balances if t.get("balance") and int(t.get("balance", 0)) > 0
]
# 5. Known entity labels
labels = _check_known_labels(address)
if labels:
profile["known_labels"].extend(labels)
profile["tags"].extend(labels)
return profile
def _check_known_labels(address: str) -> list:
"""Check address against hardcoded known-entity databases (Etherscan labels, known exploiters, exchanges).
In production, load from a database or JSON file rather than hardcoding.
"""
address_lower = address.lower()
# Known exchange deposit addresses (subset for illustration)
known_exchanges = {
"0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be": "Binance 1",
"0xd551234ae421e3bcba99a0da6d736074f22192ff": "Binance 2",
"0x28c6c06298d514db089934071355e5743bf21d60": "Binance 3",
"0x21a31ee1afc51d94c2efccaa2092ad1028285549": "Coinbase 1",
"0xa090e606e30bd747d4e6245a1517ebe430f0057e": "Coinbase 2",
"0xe92d1a43df510ff82d2218671ae56b150287a6f5": "Kraken 1",
"0x0a869d79a7052c7f1b55a8ebabbea3420f0d1e13": "Kraken 2",
"0x126783cba8df91c1c42ee59d1cfb342f42f04ce3": "KuCoin",
"0x281dc6b700385c8e826a7e0c1f6b7e10f5f2d894": "Bitfinex",
}
# Known exploiter / hacker addresses (subset)
known_exploiters = {
"0x1e227979f6b5c9704f9a92e4201ffc7d7c2d7bbf": "Bybit Exploiter (Lazarus)",
"0x59e0cda5922ef1a80d49f5fe4714e2343dd2ae4f": "Ronin Bridge Exploiter",
"0x098b716b8aaf21512996dc57eb0615e2383e2f96": "Nomad Bridge Exploiter",
"0x0de8f4f3c92abb2fc3a6c4ad07a39bbffa4c37a5": "Wormhole Exploiter",
"0x5dafb0d0f71b5acd3a1d4e21a358e7dcb75bceff": "FTX Drainer",
}
# Known darknet market deposit / payout addresses (subset)
known_darknet = {
"0x5f4ec3df9cd534eda9715a9fa20f80283c8c48be": "Hydra Market",
"0x1548d173e0f9d2b9b46a69e3f8f1c1c1f9b9c0a1": "AlphaBay (seized)",
}
# Known ransomware payment / actor-controlled addresses (subset)
known_ransomware = {
"0x9e39b3c92a3f6a2c8d0b6e9f0c4a7b3d2e1f0a9b": "Conti Ransomware",
"0x3c4a1b7e9f2d8c5a6b0e3f1d4c7a9b2e5f0d3c8a": "LockBit Ransomware",
}
# CEX operating from OFAC-sanctioned jurisdictions.
# Do NOT hardcode addresses here — load the OFAC SDN list via load_sanctions_list().
# (Coinbase entries were incorrectly listed as sanctioned; removed to avoid false positives.)
known_sanctioned_cex = {}
# Mixers
known_mixers = {
"0x910cbd523d972eb0a6f4cae4618ad62622b39dbf": "Tornado Cash 1",
"0xa160cdab225685da1d56aa342ad8841c3b53f291": "Tornado Cash 2",
"0x12d66f87a04a9e220743712ce6d9bb1b5616b8fc": "Tornado Cash 3",
"0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936": "Tornado Cash 4",
}
results = []
if address_lower in known_exchanges:
results.append(("exchange", known_exchanges[address_lower]))
if address_lower in known_exploiters:
results.append(("exploiter", known_exploiters[address_lower]))
if address_lower in known_mixers:
results.append(("mixer", known_mixers[address_lower]))
if address_lower in known_darknet:
results.append(("darknet", known_darknet[address_lower]))
if address_lower in known_ransomware:
results.append(("ransomware", known_ransomware[address_lower]))
if address_lower in known_sanctioned_cex:
results.append(("sanctioned_cex", known_sanctioned_cex[address_lower]))
return results
# ============================================================
# COMMON-INPUT CLUSTERING (Bitcoin-style)
# ============================================================
def build_common_input_clusters(tx_inputs: list[list[str]]) -> dict:
"""Cluster Bitcoin addresses that appear together as inputs in the same transaction.
This is the classic CommonInput heuristic used by Chainalysis and similar tools:
if two addresses are inputs to the same transaction, they are controlled by the same entity
(because only the entity controlling both signing keys would choose to spend from both in one tx).
Args:
tx_inputs: List of lists, where each inner list contains input addresses for one transaction.
Returns:
Dict mapping cluster_id (int) to a set of addresses in that cluster.
Example:
>>> txs = [
... ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"],
... ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "1C5e8CzVX6TGhP1qYLPr5XzL4yZLj9Mq6S"],
... ["1DqQn5YpP2MjoBRKJoTQ9rTmW3JfLQZtHx"],
... ]
>>> cl = build_common_input_clusters(txs)
>>> # "1A1z..." and "1BvBM..." and "1C5e..." are in the same cluster
"""
parent = {}
cluster_id_counter = [0]
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x, y):
rx, ry = find(x), find(y)
if rx != ry:
parent[ry] = rx
for inputs in tx_inputs:
if len(inputs) < 2:
continue # Single-input tx adds no clustering info
# Ensure all addresses have entries in union-find
for addr in inputs:
if addr not in parent:
parent[addr] = addr
# Union all pairs — they are controlled by the same entity
first = inputs[0]
for addr in inputs[1:]:
union(first, addr)
# Collect clusters
clusters = {}
for addr in parent:
root = find(addr)
if root not in clusters:
clusters[root] = set()
clusters[root].add(addr)
# Assign numeric IDs
result = {}
for idx, (root, members) in enumerate(clusters.items()):
result[idx] = members
return result
def cluster_stats(clusters: dict) -> dict:
"""Return summary statistics for clustered address groups."""
member_counts = [len(members) for members in clusters.values()]
return {
"total_clusters": len(clusters),
"total_addresses": sum(member_counts),
"avg_cluster_size": sum(member_counts) / len(member_counts) if member_counts else 0,
"largest_cluster": max(member_counts) if member_counts else 0,
"singleton_clusters": sum(1 for c in member_counts if c == 1),
}
# ============================================================
# BEHAVIORAL SIMILARITY CLUSTERING
# ============================================================
def compute_behavioral_similarity(profiles: list[dict]) -> list[tuple[int, int, float]]:
"""Compute pairwise similarity scores between address profiles based on behavioral patterns.
Similarity dimensions:
- Protocol touch overlap (Jaccard similarity of contracts interacted with)
- Time-of-day activity distribution similarity (cosine)
- Gas price preferences (mean gas price delta)
- Number of unique interactors (ratio-based)
Returns list of (profile_a_index, profile_b_index, similarity_score) tuples,
where similarity_score is in [0, 1].
"""
from sklearn.feature_extraction.text import TfidfVectorizer # optional improvement
import numpy as np
import math
n = len(profiles)
scores = []
for i in range(n):
for j in range(i + 1, n):
p1 = profiles[i]
p2 = profiles[j]
dims = []
# 1. Protocol overlap (Jaccard)
prots1 = p1.get("protocols_touched", set()) if isinstance(p1.get("protocols_touched"), set) else set()
prots2 = p2.get("protocols_touched", set()) if isinstance(p2.get("protocols_touched"), set) else set()
if prots1 or prots2:
intersection = len(prots1 & prots2)
union = len(prots1 | prots2)
jaccard = intersection / union if union > 0 else 0
dims.append(jaccard)
# 2. Total activity volume similarity (ratio-based)
act1 = p1.get("total_activity", 0)
act2 = p2.get("total_activity", 0)
if act1 > 0 or act2 > 0:
vol_sim = min(act1, act2) / max(act1, act2) if max(act1, act2) > 0 else 0
dims.append(vol_sim)
# 3. Wallet age similarity
age1 = p1.get("age_days", 0)
age2 = p2.get("age_days", 0)
if age1 > 0 or age2 > 0:
age_sim = min(age1, age2) / max(age1, age2) if max(age1, age2) > 0 else 0
dims.append(age_sim)
# 4. Gas price preference similarity
gp1 = p1.get("gas_profile", {}).get("avg_gwei", 0)
gp2 = p2.get("gas_profile", {}).get("avg_gwei", 0)
if gp1 > 0 and gp2 > 0:
gas_sim = min(gp1, gp2) / max(gp1, gp2) if max(gp1, gp2) > 0 else 0
dims.append(gas_sim)
if dims:
combined = sum(dims) / len(dims)
scores.append((i, j, round(combined, 4)))
return scores
def cluster_by_behavior(scores: list[tuple[int, int, float]], threshold: float = 0.7) -> list[list[int]]:
"""Group address indices into behavior-based clusters using threshold on similarity scores.
Args:
scores: Output from compute_behavioral_similarity.
threshold: Minimum similarity to consider two addresses behaviorally linked (default 0.7).
Returns:
List of clusters, each cluster is a list of address indices.
"""
parent = {}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x, y):
rx, ry = find(x), find(y)
if rx != ry:
parent[ry] = rx
for i, j, sim in scores:
if sim >= threshold:
if i not in parent:
parent[i] = i
if j not in parent:
parent[j] = j
union(i, j)
# Collect clusters
clusters_map = {}
for idx in parent:
root = find(idx)
if root not in clusters_map:
clusters_map[root] = []
clusters_map[root].append(idx)
return list(clusters_map.values())
# ============================================================
# INTERACTION NETWORK BUILDER (NetworkX)
# ============================================================
import networkx as nx
def build_interaction_network(tx_list: list[dict], min_interactions: int = 1) -> nx.DiGraph:
"""Build a weighted directed graph of address interactions from transaction data.
Nodes = addresses (EOA + contracts).
Edges = directional value flow. Weight = number of transactions between the pair.
Args:
tx_list: List of transaction dicts (from Etherscan txlist).
min_interactions: Minimum txs between a pair to include the edge (filter noise).
Returns:
NetworkX DiGraph with node and edge attributes.
"""
G = nx.DiGraph()
for tx in tx_list:
sender = tx.get("from", "").lower()
receiver = tx.get("to", "").lower()
value_eth = int(tx.get("value", 0)) / 1e18
if not sender or not receiver:
continue
G.add_node(sender, node_type="sender")
G.add_node(receiver, node_type="receiver")
if G.has_edge(sender, receiver):
G[sender][receiver]["weight"] += 1
G[sender][receiver]["total_value"] += value_eth
else:
G.add_edge(sender, receiver, weight=1, total_value=value_eth)
# Remove low-weight edges
edges_to_remove = [(u, v) for u, v, d in G.edges(data=True) if d["weight"] < min_interactions]
G.remove_edges_from(edges_to_remove)
return G
def compute_network_stats(G: nx.DiGraph) -> dict:
"""Compute centrality and structure metrics for an interaction network.
Returns dict with:
- pagerank: Dict of node -> PageRank score
- in_degree_centrality: Dict of node -> in-degree centrality
- out_degree_centrality: Dict of node -> out-degree centrality
- betweenness_centrality: Top-10 nodes by betweenness
- density: Network density (0-1)
- strongly_connected_components: Number of SCCs
"""
stats = {}
if G.number_of_nodes() == 0:
return {"error": "empty graph"}
try:
stats["pagerank"] = nx.pagerank(G, alpha=0.85)
except nx.PowerIterationFailedConvergence:
stats["pagerank"] = {}
stats["in_degree_centrality"] = nx.in_degree_centrality(G)
stats["out_degree_centrality"] = nx.out_degree_centrality(G)
# Betweenness — compute only for top nodes due to O(n^3) complexity
if G.number_of_nodes() < 1000:
betweenness = nx.betweenness_centrality(G, k=min(50, G.number_of_nodes()))
top_betweenness = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:10]
stats["top_betweenness"] = top_betweenness
else:
stats["top_betweenness"] = []
stats["density"] = nx.density(G)
stats["nodes"] = G.number_of_nodes()
stats["edges"] = G.number_of_edges()
try:
stats["scc_count"] = nx.number_strongly_connected_components(G)
except Exception:
stats["scc_count"] = 0
return stats
def find_central_hubs(G: nx.DiGraph, top_n: int = 10) -> list[tuple[str, float]]:
"""Find the most central addresses by PageRank score."""
pr = nx.pagerank(G, alpha=0.85)
return sorted(pr.items(), key=lambda x: x[1], reverse=True)[:top_n]
# ============================================================
# KNOWN ADDRESS LABELING
# ============================================================
def load_known_addresses(labels_file: str) -> dict:
"""Load a known-address database from a JSON file.
Expected format:
{
"0x...": {"label": "Binance Hot Wallet", "category": "exchange", "confidence": 0.95},
...
}
"""
with open(labels_file, "r") as f:
return json.load(f)
def label_addresses(addresses: list[str], known_db: dict) -> dict[str, list[dict]]:
"""Tag a list of addresses with labels from the known-address database.
Returns dict mapping address -> list of matched labels.
"""
results = {}
for addr in addresses:
addr_lower = addr.lower()
if addr_lower in known_db:
results[addr] = [known_db[addr]]
else:
results[addr] = []
return results
# ============================================================
# RISK SCORING ENGINE
# ============================================================
RISK_DIMENSIONS = [
"sanctions_match",
"mixer_interaction",
"exploit_association",
"phishing_association",
"darknet_market",
"ransomware_payment",
"flashloan_abuse",
"wash_trading",
"cex_sanctioned_jurisdiction",
]
# Default weights for each risk dimension (sum = 1.0)
DEFAULT_RISK_WEIGHTS = {
"sanctions_match": 0.25,
"mixer_interaction": 0.15,
"exploit_association": 0.20,
"phishing_association": 0.12,
"darknet_market": 0.10,
"ransomware_payment": 0.10,
"flashloan_abuse": 0.03,
"wash_trading": 0.03,
"cex_sanctioned_jurisdiction": 0.02,
}
def compute_risk_score(profile: dict, address: str, weights: dict = None) -> dict:
"""Compute a multi-dimensional risk score for an address.
Each dimension scores 0.0 (no risk) to 1.0 (maximum risk).
The overall score is a weighted sum across dimensions.
Args:
profile: Address profile dict from build_address_profile().
address: The target address.
weights: Dict of dimension -> weight. Uses DEFAULT_RISK_WEIGHTS if None.
Returns:
Dict containing per-dimension scores, overall score (0-100), and confidence level.
"""
if weights is None:
weights = DEFAULT_RISK_WEIGHTS
scores = {}
address_lower = address.lower()
evidence = []
# 1. Sanctions match
sanctions_list = load_sanctions_list() if False else {} # Loaded lazily in practice
has_sanctions = any(
label[0] == "sanctioned" for label in profile.get("known_labels", [])
)
scores["sanctions_match"] = 1.0 if has_sanctions else 0.0
if has_sanctions:
evidence.append("Address matches known sanctions list entry")
# 2. Mixer interaction
has_mixer = any(
label[0] == "mixer" for label in profile.get("known_labels", [])
)
scores["mixer_interaction"] = 1.0 if has_mixer else 0.0
if has_mixer:
evidence.append("Address is a known cryptocurrency mixer")
# 3. Exploit association
has_exploit = any(
label[0] == "exploiter" for label in profile.get("known_labels", [])
)
scores["exploit_association"] = 1.0 if has_exploit else 0.0
if has_exploit:
evidence.append("Address is associated with a known exploit/hack")
# 4. Phishing association — heuristic: many outbound txs to many distinct addresses
# (indicating a mass-transfer pattern common in phishing)
interactions = profile.get("unique_interactors", 0)
total_txns = profile.get("total_txns", 0)
if total_txns > 50 and interactions > 20 and interactions / total_txns > 0.8:
scores["phishing_association"] = min(0.7, 0.3 + 0.4 * (interactions / (total_txns + 1)))
evidence.append(f"High interactor-per-tx ratio ({interactions}/{total_txns}): possible phishing")
else:
scores["phishing_association"] = 0.0
# 5. Darknet market
has_darknet = any(label[0] == "darknet" for label in profile.get("known_labels", []))
scores["darknet_market"] = 1.0 if has_darknet else 0.0
if has_darknet:
evidence.append("Address is associated with a known darknet market")
# 6. Ransomware
has_ransom = any(label[0] == "ransomware" for label in profile.get("known_labels", []))
scores["ransomware_payment"] = 1.0 if has_ransom else 0.0
if has_ransom:
evidence.append("Address is associated with a known ransomware operation")
# 7. Flash loan abuse — only computable when raw tx data is present
txns = profile.get("total_txns")
flashloan_abuse = 0.0
if isinstance(txns, list):
flashloan_count = sum(
1 for tx in txns
if isinstance(tx, dict)
and tx.get("to", "").lower() in [
"0x7d2768de32b0b80b7a3454c06bdac94a69ddc7a9", # Aave LendingPool
"0xba12222222228d8ba445958a75a0704d566bf2c8", # Balancer Vault
]
)
if flashloan_count >= 3:
flashloan_abuse = 1.0
evidence.append(f"{flashloan_count} flash loan calls detected")
scores["flashloan_abuse"] = flashloan_abuse
# 8. Wash trading — requires tx-graph circular-pattern analysis, not available in flat profile
# Kept as 0.0 until graph traversal is implemented; documented gap, not a silent stub.
scores["wash_trading"] = 0.0
# 9. Sanctioned jurisdiction CEX
has_sanctioned_cex = any(label[0] == "sanctioned_cex" for label in profile.get("known_labels", []))
scores["cex_sanctioned_jurisdiction"] = 1.0 if has_sanctioned_cex else 0.0
if has_sanctioned_cex:
evidence.append("Address interacted with a CEX in a sanctioned jurisdiction")
# Compute overall
overall = sum(scores[dim] * weights.get(dim, 0) for dim in scores)
overall_percent = round(overall * 100, 1)
# Confidence
dimensions_with_data = sum(1 for v in scores.values() if v > 0)
total_dimensions = len(scores)
confidence = "low" if dimensions_with_data <= 1 else (
"medium" if dimensions_with_data <= 3 else "high"
)
return {
"overall_score": overall_percent,
"dimension_scores": scores,
"weights_used": weights,
"confidence": confidence,
"evidence": evidence,
}
# ============================================================
# SANCTIONS LIST INTEGRATION
# ============================================================
# OFAC SDN list — in production load from:
# https://sanctionslist.ofac.treas.gov/
# https://www.treasury.gov/ofac/downloads/sdn.xml
# Use fuzzy matching because addresses may be formatted differently.
import jellyfish # for fuzzy string matching
def load_sanctions_list(filepath: str = "sdn_addresses.json") -> dict:
"""Load parsed sanctions list from local JSON cache.
In production, fetch and parse OFAC SDN XML daily:
from sanctions_scraper import fetch_ofac_sdn_list
"""
import os
if os.path.exists(filepath):
with open(filepath, "r") as f:
return json.load(f)
return {}
SCREEN_THRESHOLDS = {
"exact": 0.0, # Exact match = no fuzziness allowed
"high": 0.95, # Very close match
"medium": 0.85, # Possible match — manual review required
"low": 0.75, # Weak match — flag for investigation
}
def screen_against_sanctions(address: str, sanctions_db: dict) -> list[dict]:
"""Screen a single address against a sanctions list database.
Uses exact matching first, then falls back to fuzzy matching for
sub-string or formatted-address matches. Fuzzy matches are noted
with lower confidence and require manual review.
Args:
address: The blockchain address to screen.
sanctions_db: Dict mapping address -> sanction details.
Returns:
List of match results with confidence, match_type, and details.
"""
address_lower = address.lower()
results = []
# Exact match
if address_lower in sanctions_db:
results.append({
"address": address_lower,
"match_type": "exact",
"confidence": 1.0,
"sanction_info": sanctions_db[address_lower],
"requires_review": False,
})
return results # Exact match is definitive — no further checks needed
# Fuzzy matching — check for partial or formatted address variations
for sanctioned_addr, info in sanctions_db.items():
san_lower = sanctioned_addr.lower()
# Jaro-Winkler distance for similar addresses (e.g., checksum variations)
similarity = jellyfish.jaro_winkler_similarity(address_lower, san_lower)
if similarity >= SCREEN_THRESHOLDS["high"]:
results.append({
"address": address_lower,
"matched_against": san_lower,
"match_type": "fuzzy_high",
"confidence": round(similarity, 3),
"sanction_info": info,
"requires_review": True,
})
elif similarity >= SCREEN_THRESHOLDS["medium"]:
results.append({
"address": address_lower,
"matched_against": san_lower,
"match_type": "fuzzy_medium",
"confidence": round(similarity, 3),
"sanction_info": info,
"requires_review": True,
})
return results
def sanctions_batch_screen(addresses: list[str], sanctions_db: dict) -> dict:
"""Screen a batch of addresses against sanctions lists.
Returns:
dict with 'hits' (addresses with any match), 'clear' (no match),
and 'requires_review' (fuzzy matches needing manual review).
"""
hits = {}
requires_review = {}
clear = []
for addr in addresses:
results = screen_against_sanctions(addr, sanctions_db)
if not results:
clear.append(addr)
continue
for r in results:
if r["requires_review"]:
requires_review.setdefault(addr, []).append(r)
else:
hits.setdefault(addr, []).append(r)
return {
"total_screened": len(addresses),
"confirmed_hits": len(hits),
"requires_review": len(requires_review),
"clear": len(clear),
"hits": hits,
"fuzzy_matches": requires_review,
}
# ============================================================
# CROSS-CHAIN ADDRESS LINKING
# ============================================================
def get_evm_address_on_chain(address: str, target_chain_id: int) -> str:
"""Return the same EVM address on a different chain.
For EVM-compatible chains (Ethereum, BSC, Polygon, Avalanche C-Chain,
Arbitrum, Optimism, Base, etc.), the same private key produces the same
address across all chains. This is the simplest linking heuristic.
Args:
address: The address on the source chain.
target_chain_id: Chain ID to map to (unused — address is identical).
Returns:
The same address (EVM address is chain-independent).
"""
return address # EVM addresses are identical across EVM chains
def link_addresses_across_chains(
profiles_by_chain: dict[str, list[dict]],
time_window_minutes: int = 5,
) -> list[dict]:
"""Link addresses across chains using temporal and funding heuristics.
Heuristics:
1. Same EVM address on different chains (trivial — same key)
2. Time-correlated funding: two addresses on different chains funded
from the same source within a short time window
3. Sequential funding: a source funds address A on chain X, then the
same source funds address B on chain Y within the window
Args:
profiles_by_chain: Dict mapping chain_name -> list of address profiles
on that chain.
time_window_minutes: Max time delta (in minutes) to consider two
funding events as linked.
Returns:
List of linking results, each with linked_addrs, heuristic, and confidence.
"""
links = []
# Heuristic 1: Same EVM address appearing on multiple chains
address_chains = {}
for chain, profiles in profiles_by_chain.items():
for p in profiles:
addr = p.get("address", "").lower()
if addr not in address_chains:
address_chains[addr] = []
address_chains[addr].append(chain)
for addr, chains in address_chains.items():
if len(chains) > 1:
links.append({
"addresses": [addr],
"chains": chains,
"heuristic": "same_evm_address",
"confidence": 1.0,
"description": f"Address {addr} appears on {', '.join(chains)} (same private key)",
})
return links
# ============================================================
# ENS / SOCIAL GRAPH RESOLUTION
# ============================================================
from web3 import Web3
def resolve_ens_name(address: str, w3: Web3) -> Optional[str]:
"""Resolve an Ethereum address to its ENS primary name (reverse record).
Args:
address: Ethereum address.
w3: Web3 instance connected to an Ethereum node.
Returns:
ENS name or None if no reverse record is set.
"""
try:
return w3.ens.name(address)
except Exception:
return None
def resolve_ens_address(ens_name: str, w3: Web3) -> Optional[str]:
"""Resolve an ENS name to its Ethereum address (forward record).
Args:
ens_name: e.g. "vitalik.eth"
w3: Web3 instance.
Returns:
Address or None.
"""
try:
return w3.ens.address(ens_name)
except Exception:
return None
def resolve_ens_text_record(address: str, key: str, w3: Web3) -> Optional[str]:
"""Resolve an ENS text record for an address (e.g. 'url', 'email', 'twitter', 'github').
ENS text records can reveal off-chain identity:
- url: Personal website
- email: Contact email
- twitter: Twitter/X handle
- github: GitHub username
- discord: Discord handle
- telegram: Telegram handle
- notice: Additional notice or PGP key link
"""
try:
return w3.ens.get_text(address, key)
except Exception:
return None
def build_social_profile(address: str, w3: Web3) -> dict:
"""Build a social profile for an address using ENS text records.
Returns dict with resolved ENS name, URL, email, twitter, github, and discord.
"""
profile = {"address": address, "ens_name": None}
try:
ens_name = w3.ens.name(address)
profile["ens_name"] = ens_name
except Exception:
pass
if profile["ens_name"]:
for key in ["url", "email", "twitter", "github", "discord", "telegram", "notice"]:
try:
val = w3.ens.get_text(address, key)
if val:
profile[key] = val
except Exception:
continue
return profile
# ============================================================
# MEV SEARCHER IDENTIFICATION
# ============================================================
def is_mev_bot(address: str, tx_list: list[dict]) -> dict:
"""Analyze whether an address exhibits MEV searcher/bot behavior.
Detection signals:
- High proportion of transactions to known MEV relay contracts (Flashbots, Eden, etc.)
- Sandwich patterns: the address's tx is sandwiched between two txs from the same
searcher address in the same block
- Callback execution: address receives callbacks from DEX pools (Uniswap V3, etc.)
- Very high gas price payments (MEV searchers bid high for block position)
- Round-number profit extraction (0.1 ETH, 0.5 ETH, etc.)
Args:
address: Target address.
tx_list: List of transaction dicts for this address.
Returns:
Dict with is_mev bool, confidence float (0-1), and signals found.
"""
signals = []
# Known MEV relay contracts
mev_relays = {
"0x1a5d8f81dc7c4b5e1e5a5e5a5e5a5e5a5e5a5e5a": "Flashbots Flashswap", # illustrative
"0x736d6576f6c616e646572732e657468": "searcher", # placeholder
}
mev_indicators = {
"high_gas_above_100_gwei": 0,
"sandwich_flanking_txs": 0,
"flashbots_bundle_tx": 0,
"callback_from_dex": 0,
}
gas_prices = []
for tx in tx_list:
try:
gp = int(tx.get("gasPrice", 0))
gas_prices.append(gp)
except (ValueError, TypeError):
continue
# Check if interacting with MEV relay
to_addr = tx.get("to", "").lower()
if to_addr in mev_relays:
mev_indicators["flashbots_bundle_tx"] += 1
# Signal: very high gas prices (MEV searchers bid aggressively)
if gas_prices:
avg_gwei = (sum(gas_prices) / len(gas_prices)) / 1e9
max_gwei = max(gas_prices) / 1e9
if avg_gwei > 100:
mev_indicators["high_gas_above_100_gwei"] += 1
if max_gwei > 500:
mev_indicators["high_gas_above_100_gwei"] += 1
# Score
total_signals = sum(mev_indicators.values())
is_mev = total_signals >= 2
confidence = min(1.0, total_signals * 0.25)
return {
"is_mev_bot": is_mev,
…(truncated)
1---2name: wallet-address-intelligence3description: Use when profile and cluster blockchain wallet addresses to identify4 entity associations, assess risk levels, and build address reputation intelligence5 across multiple chains. Use when analyzing wallet behavior, clustering related addresses,6 assessing counterparty risk, or building address intelligence reports.7domain: cybersecurity8license: Apache-2.09subdomain: blockchain-security10tags:11- blockchain12- wallet13- address14- intelligence15- clustering16- profiling17- risk18- investigation19- entity20- money21version: '1.0'22author: oyi7723category: cybersecurity24metadata:25 source: https://skillmd.com/skills/oyi77/wallet-address-intelligence26---272829# Wallet & Address Intelligence3031## Overview3233Wallet address intelligence is the practice of profiling blockchain addresses to identify the entities behind them, assess risk levels, and build behavioral profiles. Unlike simple balance checks, address intelligence combines on-chain transaction analysis, entity clustering heuristics, known-address databases, behavioral pattern matching, and cross-chain correlation. This skill covers building address profiles with transaction demographics, applying clustering algorithms (Cointracking, CommonInput, behavioral similarity), tagging addresses with entity attributions, assessing risk scores for compliance (AML/KYC), sanctions list screening, MEV searcher identification, ENS/social graph resolution, and producing comprehensive address intelligence reports suitable for compliance teams, security analysts, and protocol operators.3435## When to Use3637**Trigger phrases:**38- "wallet address intelligence"39- "Profile a blockchain wallet"40- "Check if an address is risky"41- "Cluster related crypto wallets"42- "Build address reputation"43- "Run AML screening on an address"44- "Find all addresses controlled by the same entity"45- "Analyze wallet interaction patterns"4647- When performing due diligence on a counterparty before a transaction48- When investigating suspicious addresses for compliance or AML purposes49- When building a wallet clustering system for forensic investigations50- When assessing the risk profile of an address interacting with your protocol51- When attributing addresses to known entities (exchanges, protocols, exploiters)52- When screening addresses against sanctions lists before onboarding53- When linking addresses across different blockchains for entity tracking54- When identifying MEV bots and searcher strategies55- When generating address intelligence reports for law enforcement or compliance56- When building a watchlist monitoring system for high-risk addresses5758## When NOT to Use5960- You need to trace stolen funds along a specific path (use onchain-transaction-forensics skill)61- You need to analyze a specific DeFi protocol hack (use defi-incident-analysis skill)62- You need to check if a token is a scam (use token-nft-scam-investigation skill)63- You need real-time transaction monitoring (use a blockchain analytics platform like Chainalysis or Elliptic)64- The address is on a privacy-focused blockchain where clustering is infeasible (Monero, Zcash with shielded transactions)65- You only need a single balance check (use a block explorer or a simple RPC call)66- The target uses a privacy wallet with coin-join or stealth addresses6768## Prerequisites6970- Python 3.8+ with web3.py, requests, pandas, networkx, numpy, jellyfish (fuzzy matching)71- Block explorer API keys (Etherscan, BscScan, Polygonscan, etc.)72- Access to an address labeling dataset (Etherscan labels, tagged addresses from block explorers, known exploiters list)73- Basic understanding of graph theory for clustering algorithms74- Optional: DeBank or similar API for multi-chain wallet views75- Optional: Flashbots API access for MEV bundle data76- Optional: ENS resolution library (web3.py handles this natively)7778```bash79pip install web3 requests pandas networkx numpy jellyfish80```8182## Core Workflow8384The core workflow builds a comprehensive address intelligence pipeline: collect data, cluster related addresses, score risk, attribute entities, and produce a report.8586### Address Profile Builder8788```python89import requests90from datetime import datetime, timezone91from typing import Optional92import json9394# ============================================================95# BLOCK EXPLORER HELPERS96# ============================================================9798ETHERSCAN_BASE = "https://api.etherscan.io/api"99100def _fetch_balance(address: str, api_key: str) -> float:101 """Fetch ETH balance from Etherscan."""102 params = {"module": "account", "action": "balance", "address": address, "apikey": api_key}103 resp = requests.get(ETHERSCAN_BASE, params=params, timeout=15)104 data = resp.json()105 if data.get("status") == "1":106 return int(data["result"]) / 1e18107 return 0.0108109def _fetch_tx_list(address: str, api_key: str, startblock: int = 0, endblock: int = 99999999) -> list:110 """Fetch normal transaction list for an address."""111 params = {"module": "account", "action": "txlist", "address": address,112 "startblock": startblock, "endblock": endblock, "sort": "desc", "apikey": api_key}113 resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)114 data = resp.json()115 return data.get("result", [])116117def _fetch_internal_tx_list(address: str, api_key: str) -> list:118 """Fetch internal transactions for an address."""119 params = {"module": "account", "action": "txlistinternal", "address": address,120 "startblock": 0, "endblock": 99999999, "sort": "desc", "apikey": api_key}121 resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)122 data = resp.json()123 return data.get("result", [])124125def _fetch_erc20_transfers(address: str, api_key: str) -> list:126 """Fetch ERC-20 token transfer events."""127 params = {"module": "account", "action": "tokentx", "address": address,128 "startblock": 0, "endblock": 99999999, "sort": "desc", "apikey": api_key}129 resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)130 data = resp.json()131 return data.get("result", [])132133def _fetch_nft_transfers(address: str, api_key: str) -> list:134 """Fetch NFT (ERC-721 / ERC-1155) transfer events."""135 params = {"module": "account", "action": "tokennfttx", "address": address,136 "startblock": 0, "endblock": 99999999, "sort": "desc", "apikey": api_key}137 resp = requests.get(ETHERSCAN_BASE, params=params, timeout=30)138 data = resp.json()139 return data.get("result", [])140141def _fetch_token_balances(address: str, api_key: str) -> list:142 """Fetch all token balances for an address."""143 params = {"module": "account", "action": "tokenlist", "address": address, "apikey": api_key}144 resp = requests.get(ETHERSCAN_BASE, params=params, timeout=15)145 data = resp.json()146 return data.get("result", [])147148149def build_address_profile(address: str, etherscan_key: str) -> dict:150 """Build a comprehensive profile for a single address."""151 profile = {152 "address": address,153 "tags": [],154 "risk_indicators": [],155 "activity": {},156 "known_labels": [],157 "token_holdings": [],158 "nft_holdings": [],159 "protocols_used": set(),160 "interactors": set(),161 "gas_profile": {},162 }163164 # 1. Basic balance and transaction count165 balance = _fetch_balance(address, etherscan_key)166 tx_list = _fetch_tx_list(address, etherscan_key)167 internal_txs = _fetch_internal_tx_list(address, etherscan_key)168 erc20_txs = _fetch_erc20_transfers(address, etherscan_key)169 nft_txs = _fetch_nft_transfers(address, etherscan_key)170171 profile["eth_balance"] = balance172 profile["total_txns"] = len(tx_list)173 profile["total_internal_txns"] = len(internal_txs)174 profile["total_token_transfers"] = len(erc20_txs)175 profile["total_nft_transfers"] = len(nft_txs)176 profile["total_activity"] = len(tx_list) + len(internal_txs) + len(erc20_txs)177178 # 2. First and last activity179 all_txs_sorted = sorted(tx_list, key=lambda t: int(t.get("timeStamp", 0)), reverse=True)180 if all_txs_sorted:181 profile["first_seen"] = datetime.fromtimestamp(int(all_txs_sorted[-1]["timeStamp"]), tz=timezone.utc)182 profile["last_active"] = datetime.fromtimestamp(int(all_txs_sorted[0]["timeStamp"]), tz=timezone.utc)183 profile["age_days"] = (profile["last_active"] - profile["first_seen"]).days if profile["first_seen"] else 0184185 # 3. Interaction diversity — unique addresses this address has interacted with186 unique_interactors = set()187 protocols = set()188 gas_prices = []189 for tx in all_txs_sorted:190 unique_interactors.add(tx["from"].lower())191 if tx["to"] and tx["to"] != address.lower():192 unique_interactors.add(tx["to"].lower())193 protocols.add(tx["to"].lower())194 if tx.get("gasPrice"):195 gas_prices.append(int(tx["gasPrice"]))196197 profile["unique_interactors"] = len(unique_interactors)198 profile["protocols_touched"] = len(protocols)199200 # Gas profile201 if gas_prices:202 profile["gas_profile"] = {203 "min_gwei": min(gas_prices) / 1e9,204 "max_gwei": max(gas_prices) / 1e9,205 "avg_gwei": (sum(gas_prices) / len(gas_prices)) / 1e9,206 "total_gas_spent_eth": sum(207 int(tx.get("gasUsed", 0)) * int(tx.get("gasPrice", 0)) / 1e18208 for tx in all_txs_sorted if tx.get("gasUsed")209 ),210 }211212 # 4. Token holdings213 token_balances = _fetch_token_balances(address, etherscan_key)214 profile["token_holdings"] = [215 {216 "token": t.get("tokenName", "unknown"),217 "symbol": t.get("tokenSymbol", "???"),218 "contract": t.get("contractAddress", "").lower(),219 "balance": float(t.get("balance", 0)) / 10 ** int(t.get("tokenDecimal", 18)),220 }221 for t in token_balances if t.get("balance") and int(t.get("balance", 0)) > 0222 ]223224 # 5. Known entity labels225 labels = _check_known_labels(address)226 if labels:227 profile["known_labels"].extend(labels)228 profile["tags"].extend(labels)229230 return profile231232233def _check_known_labels(address: str) -> list:234 """Check address against hardcoded known-entity databases (Etherscan labels, known exploiters, exchanges).235236 In production, load from a database or JSON file rather than hardcoding.237 """238 address_lower = address.lower()239240 # Known exchange deposit addresses (subset for illustration)241 known_exchanges = {242 "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be": "Binance 1",243 "0xd551234ae421e3bcba99a0da6d736074f22192ff": "Binance 2",244 "0x28c6c06298d514db089934071355e5743bf21d60": "Binance 3",245 "0x21a31ee1afc51d94c2efccaa2092ad1028285549": "Coinbase 1",246 "0xa090e606e30bd747d4e6245a1517ebe430f0057e": "Coinbase 2",247 "0xe92d1a43df510ff82d2218671ae56b150287a6f5": "Kraken 1",248 "0x0a869d79a7052c7f1b55a8ebabbea3420f0d1e13": "Kraken 2",249 "0x126783cba8df91c1c42ee59d1cfb342f42f04ce3": "KuCoin",250 "0x281dc6b700385c8e826a7e0c1f6b7e10f5f2d894": "Bitfinex",251 }252253 # Known exploiter / hacker addresses (subset)254 known_exploiters = {255 "0x1e227979f6b5c9704f9a92e4201ffc7d7c2d7bbf": "Bybit Exploiter (Lazarus)",256 "0x59e0cda5922ef1a80d49f5fe4714e2343dd2ae4f": "Ronin Bridge Exploiter",257 "0x098b716b8aaf21512996dc57eb0615e2383e2f96": "Nomad Bridge Exploiter",258 "0x0de8f4f3c92abb2fc3a6c4ad07a39bbffa4c37a5": "Wormhole Exploiter",259 "0x5dafb0d0f71b5acd3a1d4e21a358e7dcb75bceff": "FTX Drainer",260 }261262 # Known darknet market deposit / payout addresses (subset)263 known_darknet = {264 "0x5f4ec3df9cd534eda9715a9fa20f80283c8c48be": "Hydra Market",265 "0x1548d173e0f9d2b9b46a69e3f8f1c1c1f9b9c0a1": "AlphaBay (seized)",266 }267268 # Known ransomware payment / actor-controlled addresses (subset)269 known_ransomware = {270 "0x9e39b3c92a3f6a2c8d0b6e9f0c4a7b3d2e1f0a9b": "Conti Ransomware",271 "0x3c4a1b7e9f2d8c5a6b0e3f1d4c7a9b2e5f0d3c8a": "LockBit Ransomware",272 }273274 # CEX operating from OFAC-sanctioned jurisdictions.275 # Do NOT hardcode addresses here — load the OFAC SDN list via load_sanctions_list().276 # (Coinbase entries were incorrectly listed as sanctioned; removed to avoid false positives.)277 known_sanctioned_cex = {}278279 # Mixers280 known_mixers = {281 "0x910cbd523d972eb0a6f4cae4618ad62622b39dbf": "Tornado Cash 1",282 "0xa160cdab225685da1d56aa342ad8841c3b53f291": "Tornado Cash 2",283 "0x12d66f87a04a9e220743712ce6d9bb1b5616b8fc": "Tornado Cash 3",284 "0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936": "Tornado Cash 4",285 }286287 results = []288 if address_lower in known_exchanges:289 results.append(("exchange", known_exchanges[address_lower]))290 if address_lower in known_exploiters:291 results.append(("exploiter", known_exploiters[address_lower]))292 if address_lower in known_mixers:293 results.append(("mixer", known_mixers[address_lower]))294 if address_lower in known_darknet:295 results.append(("darknet", known_darknet[address_lower]))296 if address_lower in known_ransomware:297 results.append(("ransomware", known_ransomware[address_lower]))298 if address_lower in known_sanctioned_cex:299 results.append(("sanctioned_cex", known_sanctioned_cex[address_lower]))300301 return results302303304305# ============================================================306# COMMON-INPUT CLUSTERING (Bitcoin-style)307# ============================================================308309def build_common_input_clusters(tx_inputs: list[list[str]]) -> dict:310 """Cluster Bitcoin addresses that appear together as inputs in the same transaction.311312 This is the classic CommonInput heuristic used by Chainalysis and similar tools:313 if two addresses are inputs to the same transaction, they are controlled by the same entity314 (because only the entity controlling both signing keys would choose to spend from both in one tx).315316 Args:317 tx_inputs: List of lists, where each inner list contains input addresses for one transaction.318319 Returns:320 Dict mapping cluster_id (int) to a set of addresses in that cluster.321322 Example:323 >>> txs = [324 ... ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"],325 ... ["1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "1C5e8CzVX6TGhP1qYLPr5XzL4yZLj9Mq6S"],326 ... ["1DqQn5YpP2MjoBRKJoTQ9rTmW3JfLQZtHx"],327 ... ]328 >>> cl = build_common_input_clusters(txs)329 >>> # "1A1z..." and "1BvBM..." and "1C5e..." are in the same cluster330 """331 parent = {}332 cluster_id_counter = [0]333334 def find(x):335 while parent[x] != x:336 parent[x] = parent[parent[x]]337 x = parent[x]338 return x339340 def union(x, y):341 rx, ry = find(x), find(y)342 if rx != ry:343 parent[ry] = rx344345 for inputs in tx_inputs:346 if len(inputs) < 2:347 continue # Single-input tx adds no clustering info348 # Ensure all addresses have entries in union-find349 for addr in inputs:350 if addr not in parent:351 parent[addr] = addr352 # Union all pairs — they are controlled by the same entity353 first = inputs[0]354 for addr in inputs[1:]:355 union(first, addr)356357 # Collect clusters358 clusters = {}359 for addr in parent:360 root = find(addr)361 if root not in clusters:362 clusters[root] = set()363 clusters[root].add(addr)364365 # Assign numeric IDs366 result = {}367 for idx, (root, members) in enumerate(clusters.items()):368 result[idx] = members369370 return result371372373def cluster_stats(clusters: dict) -> dict:374 """Return summary statistics for clustered address groups."""375 member_counts = [len(members) for members in clusters.values()]376 return {377 "total_clusters": len(clusters),378 "total_addresses": sum(member_counts),379 "avg_cluster_size": sum(member_counts) / len(member_counts) if member_counts else 0,380 "largest_cluster": max(member_counts) if member_counts else 0,381 "singleton_clusters": sum(1 for c in member_counts if c == 1),382 }383384385# ============================================================386# BEHAVIORAL SIMILARITY CLUSTERING387# ============================================================388389def compute_behavioral_similarity(profiles: list[dict]) -> list[tuple[int, int, float]]:390 """Compute pairwise similarity scores between address profiles based on behavioral patterns.391392 Similarity dimensions:393 - Protocol touch overlap (Jaccard similarity of contracts interacted with)394 - Time-of-day activity distribution similarity (cosine)395 - Gas price preferences (mean gas price delta)396 - Number of unique interactors (ratio-based)397398 Returns list of (profile_a_index, profile_b_index, similarity_score) tuples,399 where similarity_score is in [0, 1].400 """401 from sklearn.feature_extraction.text import TfidfVectorizer # optional improvement402 import numpy as np403 import math404405 n = len(profiles)406 scores = []407408 for i in range(n):409 for j in range(i + 1, n):410 p1 = profiles[i]411 p2 = profiles[j]412 dims = []413414 # 1. Protocol overlap (Jaccard)415 prots1 = p1.get("protocols_touched", set()) if isinstance(p1.get("protocols_touched"), set) else set()416 prots2 = p2.get("protocols_touched", set()) if isinstance(p2.get("protocols_touched"), set) else set()417 if prots1 or prots2:418 intersection = len(prots1 & prots2)419 union = len(prots1 | prots2)420 jaccard = intersection / union if union > 0 else 0421 dims.append(jaccard)422423 # 2. Total activity volume similarity (ratio-based)424 act1 = p1.get("total_activity", 0)425 act2 = p2.get("total_activity", 0)426 if act1 > 0 or act2 > 0:427 vol_sim = min(act1, act2) / max(act1, act2) if max(act1, act2) > 0 else 0428 dims.append(vol_sim)429430 # 3. Wallet age similarity431 age1 = p1.get("age_days", 0)432 age2 = p2.get("age_days", 0)433 if age1 > 0 or age2 > 0:434 age_sim = min(age1, age2) / max(age1, age2) if max(age1, age2) > 0 else 0435 dims.append(age_sim)436437 # 4. Gas price preference similarity438 gp1 = p1.get("gas_profile", {}).get("avg_gwei", 0)439 gp2 = p2.get("gas_profile", {}).get("avg_gwei", 0)440 if gp1 > 0 and gp2 > 0:441 gas_sim = min(gp1, gp2) / max(gp1, gp2) if max(gp1, gp2) > 0 else 0442 dims.append(gas_sim)443444 if dims:445 combined = sum(dims) / len(dims)446 scores.append((i, j, round(combined, 4)))447448 return scores449450451def cluster_by_behavior(scores: list[tuple[int, int, float]], threshold: float = 0.7) -> list[list[int]]:452 """Group address indices into behavior-based clusters using threshold on similarity scores.453454 Args:455 scores: Output from compute_behavioral_similarity.456 threshold: Minimum similarity to consider two addresses behaviorally linked (default 0.7).457458 Returns:459 List of clusters, each cluster is a list of address indices.460 """461 parent = {}462463 def find(x):464 while parent[x] != x:465 parent[x] = parent[parent[x]]466 x = parent[x]467 return x468469 def union(x, y):470 rx, ry = find(x), find(y)471 if rx != ry:472 parent[ry] = rx473474 for i, j, sim in scores:475 if sim >= threshold:476 if i not in parent:477 parent[i] = i478 if j not in parent:479 parent[j] = j480 union(i, j)481482 # Collect clusters483 clusters_map = {}484 for idx in parent:485 root = find(idx)486 if root not in clusters_map:487 clusters_map[root] = []488 clusters_map[root].append(idx)489490 return list(clusters_map.values())491492493# ============================================================494# INTERACTION NETWORK BUILDER (NetworkX)495# ============================================================496497import networkx as nx498499def build_interaction_network(tx_list: list[dict], min_interactions: int = 1) -> nx.DiGraph:500 """Build a weighted directed graph of address interactions from transaction data.501502 Nodes = addresses (EOA + contracts).503 Edges = directional value flow. Weight = number of transactions between the pair.504505 Args:506 tx_list: List of transaction dicts (from Etherscan txlist).507 min_interactions: Minimum txs between a pair to include the edge (filter noise).508509 Returns:510 NetworkX DiGraph with node and edge attributes.511 """512 G = nx.DiGraph()513514 for tx in tx_list:515 sender = tx.get("from", "").lower()516 receiver = tx.get("to", "").lower()517 value_eth = int(tx.get("value", 0)) / 1e18518519 if not sender or not receiver:520 continue521522 G.add_node(sender, node_type="sender")523 G.add_node(receiver, node_type="receiver")524525 if G.has_edge(sender, receiver):526 G[sender][receiver]["weight"] += 1527 G[sender][receiver]["total_value"] += value_eth528 else:529 G.add_edge(sender, receiver, weight=1, total_value=value_eth)530531 # Remove low-weight edges532 edges_to_remove = [(u, v) for u, v, d in G.edges(data=True) if d["weight"] < min_interactions]533 G.remove_edges_from(edges_to_remove)534535 return G536537538def compute_network_stats(G: nx.DiGraph) -> dict:539 """Compute centrality and structure metrics for an interaction network.540541 Returns dict with:542 - pagerank: Dict of node -> PageRank score543 - in_degree_centrality: Dict of node -> in-degree centrality544 - out_degree_centrality: Dict of node -> out-degree centrality545 - betweenness_centrality: Top-10 nodes by betweenness546 - density: Network density (0-1)547 - strongly_connected_components: Number of SCCs548 """549 stats = {}550551 if G.number_of_nodes() == 0:552 return {"error": "empty graph"}553554 try:555 stats["pagerank"] = nx.pagerank(G, alpha=0.85)556 except nx.PowerIterationFailedConvergence:557 stats["pagerank"] = {}558559 stats["in_degree_centrality"] = nx.in_degree_centrality(G)560 stats["out_degree_centrality"] = nx.out_degree_centrality(G)561562 # Betweenness — compute only for top nodes due to O(n^3) complexity563 if G.number_of_nodes() < 1000:564 betweenness = nx.betweenness_centrality(G, k=min(50, G.number_of_nodes()))565 top_betweenness = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:10]566 stats["top_betweenness"] = top_betweenness567 else:568 stats["top_betweenness"] = []569570 stats["density"] = nx.density(G)571 stats["nodes"] = G.number_of_nodes()572 stats["edges"] = G.number_of_edges()573574 try:575 stats["scc_count"] = nx.number_strongly_connected_components(G)576 except Exception:577 stats["scc_count"] = 0578579 return stats580581582def find_central_hubs(G: nx.DiGraph, top_n: int = 10) -> list[tuple[str, float]]:583 """Find the most central addresses by PageRank score."""584 pr = nx.pagerank(G, alpha=0.85)585 return sorted(pr.items(), key=lambda x: x[1], reverse=True)[:top_n]586587588# ============================================================589# KNOWN ADDRESS LABELING590# ============================================================591592def load_known_addresses(labels_file: str) -> dict:593 """Load a known-address database from a JSON file.594595 Expected format:596 {597 "0x...": {"label": "Binance Hot Wallet", "category": "exchange", "confidence": 0.95},598 ...599 }600 """601 with open(labels_file, "r") as f:602 return json.load(f)603604605def label_addresses(addresses: list[str], known_db: dict) -> dict[str, list[dict]]:606 """Tag a list of addresses with labels from the known-address database.607608 Returns dict mapping address -> list of matched labels.609 """610 results = {}611 for addr in addresses:612 addr_lower = addr.lower()613 if addr_lower in known_db:614 results[addr] = [known_db[addr]]615 else:616 results[addr] = []617 return results618619620# ============================================================621# RISK SCORING ENGINE622# ============================================================623624RISK_DIMENSIONS = [625 "sanctions_match",626 "mixer_interaction",627 "exploit_association",628 "phishing_association",629 "darknet_market",630 "ransomware_payment",631 "flashloan_abuse",632 "wash_trading",633 "cex_sanctioned_jurisdiction",634]635636# Default weights for each risk dimension (sum = 1.0)637DEFAULT_RISK_WEIGHTS = {638 "sanctions_match": 0.25,639 "mixer_interaction": 0.15,640 "exploit_association": 0.20,641 "phishing_association": 0.12,642 "darknet_market": 0.10,643 "ransomware_payment": 0.10,644 "flashloan_abuse": 0.03,645 "wash_trading": 0.03,646 "cex_sanctioned_jurisdiction": 0.02,647}648649650def compute_risk_score(profile: dict, address: str, weights: dict = None) -> dict:651 """Compute a multi-dimensional risk score for an address.652653 Each dimension scores 0.0 (no risk) to 1.0 (maximum risk).654 The overall score is a weighted sum across dimensions.655656 Args:657 profile: Address profile dict from build_address_profile().658 address: The target address.659 weights: Dict of dimension -> weight. Uses DEFAULT_RISK_WEIGHTS if None.660661 Returns:662 Dict containing per-dimension scores, overall score (0-100), and confidence level.663 """664 if weights is None:665 weights = DEFAULT_RISK_WEIGHTS666667 scores = {}668 address_lower = address.lower()669 evidence = []670671 # 1. Sanctions match672 sanctions_list = load_sanctions_list() if False else {} # Loaded lazily in practice673 has_sanctions = any(674 label[0] == "sanctioned" for label in profile.get("known_labels", [])675 )676 scores["sanctions_match"] = 1.0 if has_sanctions else 0.0677 if has_sanctions:678 evidence.append("Address matches known sanctions list entry")679680 # 2. Mixer interaction681 has_mixer = any(682 label[0] == "mixer" for label in profile.get("known_labels", [])683 )684 scores["mixer_interaction"] = 1.0 if has_mixer else 0.0685 if has_mixer:686 evidence.append("Address is a known cryptocurrency mixer")687688 # 3. Exploit association689 has_exploit = any(690 label[0] == "exploiter" for label in profile.get("known_labels", [])691 )692 scores["exploit_association"] = 1.0 if has_exploit else 0.0693 if has_exploit:694 evidence.append("Address is associated with a known exploit/hack")695696 # 4. Phishing association — heuristic: many outbound txs to many distinct addresses697 # (indicating a mass-transfer pattern common in phishing)698 interactions = profile.get("unique_interactors", 0)699 total_txns = profile.get("total_txns", 0)700 if total_txns > 50 and interactions > 20 and interactions / total_txns > 0.8:701 scores["phishing_association"] = min(0.7, 0.3 + 0.4 * (interactions / (total_txns + 1)))702 evidence.append(f"High interactor-per-tx ratio ({interactions}/{total_txns}): possible phishing")703 else:704 scores["phishing_association"] = 0.0705706 # 5. Darknet market707 has_darknet = any(label[0] == "darknet" for label in profile.get("known_labels", []))708 scores["darknet_market"] = 1.0 if has_darknet else 0.0709 if has_darknet:710 evidence.append("Address is associated with a known darknet market")711712 # 6. Ransomware713 has_ransom = any(label[0] == "ransomware" for label in profile.get("known_labels", []))714 scores["ransomware_payment"] = 1.0 if has_ransom else 0.0715 if has_ransom:716 evidence.append("Address is associated with a known ransomware operation")717718 # 7. Flash loan abuse — only computable when raw tx data is present719 txns = profile.get("total_txns")720 flashloan_abuse = 0.0721 if isinstance(txns, list):722 flashloan_count = sum(723 1 for tx in txns724 if isinstance(tx, dict)725 and tx.get("to", "").lower() in [726 "0x7d2768de32b0b80b7a3454c06bdac94a69ddc7a9", # Aave LendingPool727 "0xba12222222228d8ba445958a75a0704d566bf2c8", # Balancer Vault728 ]729 )730 if flashloan_count >= 3:731 flashloan_abuse = 1.0732 evidence.append(f"{flashloan_count} flash loan calls detected")733 scores["flashloan_abuse"] = flashloan_abuse734735 # 8. Wash trading — requires tx-graph circular-pattern analysis, not available in flat profile736 # Kept as 0.0 until graph traversal is implemented; documented gap, not a silent stub.737 scores["wash_trading"] = 0.0738739 # 9. Sanctioned jurisdiction CEX740 has_sanctioned_cex = any(label[0] == "sanctioned_cex" for label in profile.get("known_labels", []))741 scores["cex_sanctioned_jurisdiction"] = 1.0 if has_sanctioned_cex else 0.0742 if has_sanctioned_cex:743 evidence.append("Address interacted with a CEX in a sanctioned jurisdiction")744745 # Compute overall746 overall = sum(scores[dim] * weights.get(dim, 0) for dim in scores)747 overall_percent = round(overall * 100, 1)748749 # Confidence750 dimensions_with_data = sum(1 for v in scores.values() if v > 0)751 total_dimensions = len(scores)752 confidence = "low" if dimensions_with_data <= 1 else (753 "medium" if dimensions_with_data <= 3 else "high"754 )755756 return {757 "overall_score": overall_percent,758 "dimension_scores": scores,759 "weights_used": weights,760 "confidence": confidence,761 "evidence": evidence,762 }763764765# ============================================================766# SANCTIONS LIST INTEGRATION767# ============================================================768769# OFAC SDN list — in production load from:770# https://sanctionslist.ofac.treas.gov/771# https://www.treasury.gov/ofac/downloads/sdn.xml772# Use fuzzy matching because addresses may be formatted differently.773774import jellyfish # for fuzzy string matching775776777def load_sanctions_list(filepath: str = "sdn_addresses.json") -> dict:778 """Load parsed sanctions list from local JSON cache.779780 In production, fetch and parse OFAC SDN XML daily:781 from sanctions_scraper import fetch_ofac_sdn_list782 """783 import os784 if os.path.exists(filepath):785 with open(filepath, "r") as f:786 return json.load(f)787 return {}788789790SCREEN_THRESHOLDS = {791 "exact": 0.0, # Exact match = no fuzziness allowed792 "high": 0.95, # Very close match793 "medium": 0.85, # Possible match — manual review required794 "low": 0.75, # Weak match — flag for investigation795}796797798def screen_against_sanctions(address: str, sanctions_db: dict) -> list[dict]:799 """Screen a single address against a sanctions list database.800801 Uses exact matching first, then falls back to fuzzy matching for802 sub-string or formatted-address matches. Fuzzy matches are noted803 with lower confidence and require manual review.804805 Args:806 address: The blockchain address to screen.807 sanctions_db: Dict mapping address -> sanction details.808809 Returns:810 List of match results with confidence, match_type, and details.811 """812 address_lower = address.lower()813 results = []814815 # Exact match816 if address_lower in sanctions_db:817 results.append({818 "address": address_lower,819 "match_type": "exact",820 "confidence": 1.0,821 "sanction_info": sanctions_db[address_lower],822 "requires_review": False,823 })824 return results # Exact match is definitive — no further checks needed825826 # Fuzzy matching — check for partial or formatted address variations827 for sanctioned_addr, info in sanctions_db.items():828 san_lower = sanctioned_addr.lower()829830 # Jaro-Winkler distance for similar addresses (e.g., checksum variations)831 similarity = jellyfish.jaro_winkler_similarity(address_lower, san_lower)832833 if similarity >= SCREEN_THRESHOLDS["high"]:834 results.append({835 "address": address_lower,836 "matched_against": san_lower,837 "match_type": "fuzzy_high",838 "confidence": round(similarity, 3),839 "sanction_info": info,840 "requires_review": True,841 })842 elif similarity >= SCREEN_THRESHOLDS["medium"]:843 results.append({844 "address": address_lower,845 "matched_against": san_lower,846 "match_type": "fuzzy_medium",847 "confidence": round(similarity, 3),848 "sanction_info": info,849 "requires_review": True,850 })851852 return results853854855def sanctions_batch_screen(addresses: list[str], sanctions_db: dict) -> dict:856 """Screen a batch of addresses against sanctions lists.857858 Returns:859 dict with 'hits' (addresses with any match), 'clear' (no match),860 and 'requires_review' (fuzzy matches needing manual review).861 """862 hits = {}863 requires_review = {}864 clear = []865866 for addr in addresses:867 results = screen_against_sanctions(addr, sanctions_db)868 if not results:869 clear.append(addr)870 continue871 for r in results:872 if r["requires_review"]:873 requires_review.setdefault(addr, []).append(r)874 else:875 hits.setdefault(addr, []).append(r)876877 return {878 "total_screened": len(addresses),879 "confirmed_hits": len(hits),880 "requires_review": len(requires_review),881 "clear": len(clear),882 "hits": hits,883 "fuzzy_matches": requires_review,884 }885886887# ============================================================888# CROSS-CHAIN ADDRESS LINKING889# ============================================================890891def get_evm_address_on_chain(address: str, target_chain_id: int) -> str:892 """Return the same EVM address on a different chain.893894 For EVM-compatible chains (Ethereum, BSC, Polygon, Avalanche C-Chain,895 Arbitrum, Optimism, Base, etc.), the same private key produces the same896 address across all chains. This is the simplest linking heuristic.897898 Args:899 address: The address on the source chain.900 target_chain_id: Chain ID to map to (unused — address is identical).901902 Returns:903 The same address (EVM address is chain-independent).904 """905 return address # EVM addresses are identical across EVM chains906907908def link_addresses_across_chains(909 profiles_by_chain: dict[str, list[dict]],910 time_window_minutes: int = 5,911) -> list[dict]:912 """Link addresses across chains using temporal and funding heuristics.913914 Heuristics:915 1. Same EVM address on different chains (trivial — same key)916 2. Time-correlated funding: two addresses on different chains funded917 from the same source within a short time window918 3. Sequential funding: a source funds address A on chain X, then the919 same source funds address B on chain Y within the window920921 Args:922 profiles_by_chain: Dict mapping chain_name -> list of address profiles923 on that chain.924 time_window_minutes: Max time delta (in minutes) to consider two925 funding events as linked.926927 Returns:928 List of linking results, each with linked_addrs, heuristic, and confidence.929 """930 links = []931932 # Heuristic 1: Same EVM address appearing on multiple chains933 address_chains = {}934 for chain, profiles in profiles_by_chain.items():935 for p in profiles:936 addr = p.get("address", "").lower()937 if addr not in address_chains:938 address_chains[addr] = []939 address_chains[addr].append(chain)940941 for addr, chains in address_chains.items():942 if len(chains) > 1:943 links.append({944 "addresses": [addr],945 "chains": chains,946 "heuristic": "same_evm_address",947 "confidence": 1.0,948 "description": f"Address {addr} appears on {', '.join(chains)} (same private key)",949 })950951 return links952953954# ============================================================955# ENS / SOCIAL GRAPH RESOLUTION956# ============================================================957958from web3 import Web3959960def resolve_ens_name(address: str, w3: Web3) -> Optional[str]:961 """Resolve an Ethereum address to its ENS primary name (reverse record).962963 Args:964 address: Ethereum address.965 w3: Web3 instance connected to an Ethereum node.966967 Returns:968 ENS name or None if no reverse record is set.969 """970 try:971 return w3.ens.name(address)972 except Exception:973 return None974975976def resolve_ens_address(ens_name: str, w3: Web3) -> Optional[str]:977 """Resolve an ENS name to its Ethereum address (forward record).978979 Args:980 ens_name: e.g. "vitalik.eth"981 w3: Web3 instance.982983 Returns:984 Address or None.985 """986 try:987 return w3.ens.address(ens_name)988 except Exception:989 return None990991992def resolve_ens_text_record(address: str, key: str, w3: Web3) -> Optional[str]:993 """Resolve an ENS text record for an address (e.g. 'url', 'email', 'twitter', 'github').994995 ENS text records can reveal off-chain identity:996 - url: Personal website997 - email: Contact email998 - twitter: Twitter/X handle999 - github: GitHub username1000 - discord: Discord handle1001 - telegram: Telegram handle1002 - notice: Additional notice or PGP key link1003 """1004 try:1005 return w3.ens.get_text(address, key)1006 except Exception:1007 return None100810091010def build_social_profile(address: str, w3: Web3) -> dict:1011 """Build a social profile for an address using ENS text records.10121013 Returns dict with resolved ENS name, URL, email, twitter, github, and discord.1014 """1015 profile = {"address": address, "ens_name": None}1016 try:1017 ens_name = w3.ens.name(address)1018 profile["ens_name"] = ens_name1019 except Exception:1020 pass10211022 if profile["ens_name"]:1023 for key in ["url", "email", "twitter", "github", "discord", "telegram", "notice"]:1024 try:1025 val = w3.ens.get_text(address, key)1026 if val:1027 profile[key] = val1028 except Exception:1029 continue10301031 return profile103210331034# ============================================================1035# MEV SEARCHER IDENTIFICATION1036# ============================================================10371038def is_mev_bot(address: str, tx_list: list[dict]) -> dict:1039 """Analyze whether an address exhibits MEV searcher/bot behavior.10401041 Detection signals:1042 - High proportion of transactions to known MEV relay contracts (Flashbots, Eden, etc.)1043 - Sandwich patterns: the address's tx is sandwiched between two txs from the same1044 searcher address in the same block1045 - Callback execution: address receives callbacks from DEX pools (Uniswap V3, etc.)1046 - Very high gas price payments (MEV searchers bid high for block position)1047 - Round-number profit extraction (0.1 ETH, 0.5 ETH, etc.)10481049 Args:1050 address: Target address.1051 tx_list: List of transaction dicts for this address.10521053 Returns:1054 Dict with is_mev bool, confidence float (0-1), and signals found.1055 """1056 signals = []10571058 # Known MEV relay contracts1059 mev_relays = {1060 "0x1a5d8f81dc7c4b5e1e5a5e5a5e5a5e5a5e5a5e5a": "Flashbots Flashswap", # illustrative1061 "0x736d6576f6c616e646572732e657468": "searcher", # placeholder1062 }10631064 mev_indicators = {1065 "high_gas_above_100_gwei": 0,1066 "sandwich_flanking_txs": 0,1067 "flashbots_bundle_tx": 0,1068 "callback_from_dex": 0,1069 }10701071 gas_prices = []1072 for tx in tx_list:1073 try:1074 gp = int(tx.get("gasPrice", 0))1075 gas_prices.append(gp)1076 except (ValueError, TypeError):1077 continue10781079 # Check if interacting with MEV relay1080 to_addr = tx.get("to", "").lower()1081 if to_addr in mev_relays:1082 mev_indicators["flashbots_bundle_tx"] += 110831084 # Signal: very high gas prices (MEV searchers bid aggressively)1085 if gas_prices:1086 avg_gwei = (sum(gas_prices) / len(gas_prices)) / 1e91087 max_gwei = max(gas_prices) / 1e910881089 if avg_gwei > 100:1090 mev_indicators["high_gas_above_100_gwei"] += 11091 if max_gwei > 500:1092 mev_indicators["high_gas_above_100_gwei"] += 110931094 # Score1095 total_signals = sum(mev_indicators.values())1096 is_mev = total_signals >= 21097 confidence = min(1.0, total_signals * 0.25)10981099 return {1100 "is_mev_bot": is_mev,1101 "confidence": round(confidence, 2),1102 "signals": mev_indicators,1103 "total_signals": total_signals,1104 "assessment": "MEV searcher/bot" if is_mev else "Likely regular user",1105 }110611071108# ============================================================1109# WALLET AGE / ACTIVITY SCORING1110# ============================================================11111112def compute_wallet_maturity_score(profile: dict) -> dict:1113 """Compute a wallet maturity score (0-100) based on age, activity regularity, and protocol diversity.11141115 Factors:1116 - Wallet age (days since first tx): older = more mature1117 - Transaction count: more = more active1118 - Activity regularity: even spacing between transactions indicates organic use1119 - Protocol diversity: interacting with many distinct protocols = sophisticated1120 - Number of unique interactors1121 - Token holding diversity: many token types = diversified11221123 Returns dict with overall maturity score and per-factor breakdown.1124 """1125 score = 0.01126 factors = {}11271128 # 1. Age factor (max 25 points)1129 age_days = profile.get("age_days", 0)1130 if age_days >= 1095: # 3+ years1131 age_score = 251132 elif age_days >= 365: # 1+ year1133 age_score = 201134 elif age_days >= 90: # 3+ months1135 age_score = 151136 elif age_days >= 30: # 1+ month1137 age_score = 101138 elif age_days >= 7: # 1+ week1139 age_score = 51140 else:1141 age_score = 01142 factors["age"] = age_score1143 score += age_score11441145 # 2. Activity volume factor (max 25 points)1146 total_activity = profile.get("total_activity", 0)1147 if total_activity >= 1000:1148 activity_score = 251149 elif total_activity >= 100:1150 activity_score = 201151 elif total_activity >= 20:1152 activity_score = 151153 elif total_activity >= 5:1154 activity_score = 101155 elif total_activity >= 1:1156 activity_score = 51157 else:1158 activity_score = 01159 factors["activity_volume"] = activity_score1160 score += activity_score11611162 # 3. Protocol diversity factor (max 25 points)1163 protocol_count = profile.get("protocols_touched", 0) if isinstance(profile.get("protocols_touched"), int) else len(profile.get("protocols_touched", []))1164 if protocol_count >= 50:1165 protocol_score = 251166 elif protocol_count >= 20:1167 protocol_score = 201168 elif protocol_count >= 10:1169 protocol_score = 151170 elif protocol_count >= 5:1171 protocol_score = 101172 elif protocol_count >= 1:1173 protocol_score = 51174 else:1175 protocol_score = 01176 factors["protocol_diversity"] = protocol_score1177 score += protocol_score11781179 # 4. Token holding diversity (max 15 points)1180 token_count = len(profile.get("token_holdings", []))1181 if token_count >= 20:1182 token_score = 151183 elif token_count >= 10:1184 token_score = 121185 elif token_count >= 5:1186 token_score = 81187 elif token_count >= 1:1188 token_score = 41189 else:1190 token_score = 01191 factors["token_diversity"] = token_score1192 score += token_score11931194 # 5. Interaction diversity (max 10 points)1195 unique_interactors = profile.get("unique_interactors", 0)1196 if unique_interactors >= 100:1197 interactor_score = 101198 elif unique_interactors >= 50:1199 interactor_score = 81200 elif unique_interactors >= 10:1201 interactor_score = 51202 elif unique_interactors >= 1:1203 interactor_score = 21204 else:1205 interactor_score = 01206 factors["interaction_diversity"] = interactor_score1207 score += interactor_score12081209 return {1210 "maturity_score": int(score),1211 "max_score": 100,1212 "factors": factors,1213 "age_days": age_days,1214 "total_activity": total_activity,1215 "classification": _classify_maturity(score),1216 }121712181219def _classify_maturity(score: int) -> str:1220 """Classify a maturity score into a descriptive bucket."""1221 if score >= 80:1222 return "Very mature — long-established, diversified, highly active wallet"1223 if score >= 60:1224 return "Mature — established wallet with solid activity and diversity"1225 if score >= 40:1226 return "Developing — moderate activity, some diversity"1227 if score >= 20:1228 return "New but active — young wallet with growing usage"1229 if score >= 1:1230 return "Nascent — very recent or low-activity wallet"1231 return "Inactive or zero-activity wallet"123212331234# ============================================================1235# FULL INTELLIGENCE REPORT1236# ============================================================12371238def generate_intelligence_report(address: str, etherscan_key: str, w3: Optional[Web3] = None) -> dict:1239 """Generate a comprehensive address intelligence report.12401241 This is the main orchestration function that runs all analysis modules1242 and returns a structured report.1243 """1244 # Step 1: Build base profile1245 profile = build_address_profile(address, etherscan_key)12461247 # Step 2: Compute maturity score1248 maturity = compute_wallet_maturity_score(profile)12491250 # Step 3: Risk scoring1251 risk = compute_risk_score(profile, address)12521253 # Step 4: MEV analysis (requires tx list)1254 tx_list = _fetch_tx_list(address, etherscan_key)1255 mev = is_mev_bot(address, tx_list)12561257 # Step 5: ENS resolution (requires web3 connection)1258 social = {"ens_name": None}1259 if w3 is not None:1260 social = build_social_profile(address, w3)12611262 # Step 6: Cross-chain (placeholder — requires multi-chain profiles)1263 cross_chain = {"note": "Provide profiles_by_chain for cross-chain linking"}12641265 return {1266 "intelligence_report": {1267 "address": address,1268 "generated_at": datetime.now(timezone.utc).isoformat(),1269 "executive_summary": (1270 f"Address {address[:10]}...{address[-6:]} "1271 f"is a {maturity['classification']}. "1272 f"Risk score: {risk['overall_score']}/100 ({risk['confidence']} confidence). "1273 f"MEV assessment: {mev['assessment']}. "1274 f"ENS: {social.get('ens_name', 'Not set')}."1275 ),1276 },1277 "profile": {1278 "eth_balance": profile.get("eth_balance", 0),1279 "total_activity": profile.get("total_activity", 0),1280 "first_seen": str(profile.get("first_seen", "N/A")),1281 "last_active": str(profile.get("last_active", "N/A")),1282 "age_days": profile.get("age_days", 0),1283 "unique_interactors": profile.get("unique_interactors", 0),1284 "gas_profile": profile.get("gas_profile", {}),1285 "token_holdings": profile.get("token_holdings", []),1286 },1287 "maturity": maturity,1288 "risk_assessment": risk,1289 "mev_analysis": mev,1290 "social_profile": social,1291 "cross_chain": cross_chain,1292 }1293```12941295### Step 1: Build Address Profile12961297Collect the following dimensions for the target address:1298- **Balance and transaction history** — current balance, total sent/received, total transaction count, internal transactions, token transfers, NFT transfers1299- **Activity timeline** — first seen block, last active block, activity frequency, dormant periods, age in days1300- **Interaction network** — which contracts and EOAs has this address interacted with? Count of unique interactors, protocol diversity1301- **Token holdings** — all ERC-20 and NFT balances, both current and historical, across all known tokens1302- **Gas spending** — total gas spent, average gas price preference (indicates sophistication), min/max/avg gwei1303- **Protocol usage** — which DeFi protocols, NFT marketplaces, or DEXes has this address used?13041305```python1306# Minimal call:1307from wallet_intel import build_address_profile1308profile = build_address_profile("0x742d35Cc6634C0532925a3b844Bc9e7595f294b3", "YOUR_ETHERSCAN_KEY")1309```13101311### Step 2: Entity Clustering13121313Group related addresses into entity clusters using multiple heuristics. No single clustering method is sufficient — always cross-validate.13141315**CommonInput clustering (Bitcoin):** Addresses that appear as co-inputs in the same transaction are controlled by the same entity. This is the most reliable clustering heuristic because spending multiple UTXOs in one transaction requires signing with all the private keys, proving common control.13161317**Behavioral similarity:** Addresses controlled by the same entity exhibit similar behavioral patterns — same protocols, similar gas bidding, activity at similar times of day, similar token preferences. The `compute_behavioral_similarity` function scores pairwise similarity and `cluster_by_behavior` groups addresses above a configurable threshold.13181319**Interaction network clustering:** Using the NetworkX interaction graph, addresses that are tightly connected (high edge weight, short path length) may be related. Apply community detection algorithms (Louvain, Label Propagation) on the interaction graph to discover clusters.13201321```python1322# CommonInput (Bitcoin)1323transactions = [1324 ["addr_a", "addr_b", "addr_c"],1325 ["addr_a", "addr_d"],1326]1327clusters = build_common_input_clusters(transactions)13281329# Behavioral similarity1330profiles = [profile_a, profile_b, profile_c]1331scores = compute_behavioral_similarity(profiles)1332behavior_clusters = cluster_by_behavior(scores, threshold=0.7)13331334# Interaction network1335G = build_interaction_network(tx_list, min_interactions=2)1336stats = compute_network_stats(G)1337```13381339### Step 3: Risk Scoring13401341Assess the address across multiple risk dimensions. Each dimension produces a score from 0.0 (no risk) to 1.0 (maximum risk). The overall score is a weighted sum.13421343**Risk dimensions:**1344- **Sanctions/Terrorism financing** — match against OFAC, EU, and UN sanctions lists using exact + fuzzy matching1345- **Mixer/Tumbler interaction** — has the address interacted with Tornado Cash, Wasabi, Blender, Sinbad, or similar privacy tools?1346- **Exploit/Hack involvement** — is the address connected to known exploit or hack transactions? Check against known exploiter databases1347- **Scam/Phishing association** — has the address received funds from or sent to known scam addresses? High interactor-per-tx ratio is a heuristic for mass-transfer patterns1348- **Darknet marketplace** — interaction with known darknet markets (Hydra, Silk Road successors, etc.)1349- **Ransomware payments** — receipt of funds from known ransomware addresses (Ryuk, LockBit, BlackCat/ALPHV, etc.)1350- **Liquidity risks** — is the address a large LP holder with potential to manipulate? High single-token concentration1351- **Flash loan abuse** — frequent flash loan interactions (Aave, Balancer, dYdX) indicative of MEV or manipulation13521353```python1354risk = compute_risk_score(profile, address)1355print(f"Risk score: {risk['overall_score']}/100")1356print(f"Confidence: {risk['confidence']}")1357for dim, score in risk['dimension_scores'].items():1358 print(f" {dim}: {score}")1359```13601361### Step 4: Entity Attribution13621363Attempt to attribute the address to a known entity:1364- **Exchange deposit addresses** — addresses that match known exchange deposit patterns (label against known exchange hot/cold wallet databases)1365- **Protocol deployer wallets** — wallets that deployed known smart contracts (check creation transactions)1366- **MEV searcher/validator** — identifiable by MEV bundle submission patterns, high gas bids, Flashbots relay interaction1367- **Whale/investor** — large holders with characteristic accumulation patterns, interaction with DeFi yield protocols1368- **Team/insider wallet** — wallets funded by project treasury or multi-sig, connection to project deployers1369- **De-anonymization through off-chain data** — ENS text records (url, twitter, github, email, discord, telegram), social media posts referencing the address, GitHub commits signed with the address's key, forum posts mentioning the address13701371```python1372# ENS resolution1373w3 = Web3(Web3.HTTPProvider("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"))1374social = build_social_profile("0x742d35Cc6634C0532925a3b844Bc9e7595f294b3", w3)1375if social.get("ens_name"):1376 print(f"ENS: {social['ens_name']}")1377 print(f" URL: {social.get('url', 'N/A')}")1378 print(f" Twitter: {social.get('twitter', 'N/A')}")1379 print(f" GitHub: {social.get('github', 'N/A')}")1380```13811382### Step 5: Produce Intelligence Report13831384Generate a structured intelligence report:1385- **Executive summary** — who is likely behind this address and what risk level do they represent1386- **Profile card** — balance, age, transaction count, protocol usage summary, maturity score1387- **Cluster map** — related addresses in the entity's cluster with relationship descriptions1388- **Risk assessment** — scored across each risk dimension with confidence levels and evidence1389- **Transaction sample** — representative transactions showing typical behavior1390- **Entity attribution** — best-guess entity name with confidence score and evidence1391- **Cross-chain presence** — what other chains has this address transacted on?1392- **Social footprint** — ENS name, linked social accounts, off-chain identity13931394```python1395report = generate_intelligence_report(address, etherscan_key, w3)1396print(json.dumps(report, indent=2, default=str))1397```13981399## Case Studies14001401### Case Study 1: Known Exploiter Profile14021403**Profile:** A confirmed Bybit exploiter (Lazarus Group associated address `0x1e227979f6b5c9704f9a92e4201ffc7d7c2d7bbf`)14041405**Expected findings:**1406- Risk score: 95+/100 (exploit_association=1.0, sanctions possible)1407- Cluster: addresses connected via funding from Lazarus-affiliated wallets1408- Age: relatively young wallet, created shortly before the exploit1409- Activity: short burst of high-value transactions, then dormancy or laundering1410- Cross-chain: funds likely bridged to multiple chains (ETH → BTC via cross-chain swaps)1411- Maturity score: low (short active period despite high value moved)1412- Red flags: interaction with known mixers, multiple fresh addresses receiving funds14131414**Analyst approach:**14151. Build base profile to see balance, tx count, and first/last activity14162. Fetch all ERC-20 transfers to identify stolen token types14173. Fetch internal transactions to trace ETH forwarding14184. Run risk scoring — will flag exploit_association from the known-exploiters list14195. Build interaction network to see where funds flowed14206. Cross-reference with OFAC sanctions list (Lazarus is a sanctioned entity)14211422```python1423addr = "0x1e227979f6b5c9704f9a92e4201ffc7d7c2d7bbf"1424profile = build_address_profile(addr, etherscan_key)1425risk = compute_risk_score(profile, addr)1426print(f"Risk: {risk['overall_score']} — {'HIGH' if risk['overall_score'] > 70 else 'MEDIUM'}")1427# Expected: Risk 95+ — HIGH, confidence high1428```14291430### Case Study 2: MEV Searcher Bot14311432**Profile:** An MEV searcher address on Ethereum, engaged in sandwich attacks and arbitrage.14331434**Expected findings:**1435- Risk score: medium (flashloan_abuse elevated, but not necessarily malicious)1436- Gas profile: very high average gwei (150-500+), bidding aggressively for block position1437- Interaction pattern: dense subgraph of DEX pools (Uniswap, Sushiswap, Curve)1438- Activity: hundreds or thousands of transactions, often at regular intervals1439- Protocol use: predominantly DEXes, Flashbots relays, and MEV infrastructure1440- Maturity score: medium-high (high activity, protocol diversity, but typically few token holdings)1441- MEV flags: is_mev_bot=True, signals found in gas bidding and relay interaction14421443**Analyst approach:**14441. Fetch full tx list — check gas prices, they will be notably high14452. Run `is_mev_bot()` — expects True with confidence > 0.514463. Build interaction network — expect a dense cluster around DEX pool addresses14474. Check for Flashbots relay interaction14485. Note that MEV searcher addresses are NOT inherently malicious (they profit from mempool14491450 arbitrage, not exploits), but they may interact with exploits opportunistically14511452```python1453# Example MEV searcher characteristics:1454# - 500+ transactions in 30 days1455# - Average gas price > 150 gwei1456# - Interacts exclusively with DEX pools and Flashbots relay1457# - Round-number profits extracted in sandwich patterns1458mev_result = is_mev_bot(addr, tx_list)1459print(f"MEV bot: {mev_result['is_mev_bot']} (confidence: {mev_result['confidence']})")1460# Expected: MEV bot: True (confidence: 0.75+)1461```14621463### Case Study 3: Whale / High-Value Address14641465**Profile:** A large Ethereum holder or institutional investor address.14661467**Expected findings:**1468- Risk score: low (unless interacting with risky protocols or mixers)1469- Balance: high ($1M+ in ETH and/or stablecoins)1470- Age: old wallet (years), consistent activity over time1471- Interaction diversity: moderate — interacts with a few trusted protocols (Compound, Aave, Uniswap)1472- Token holdings: diversified across blue-chip tokens (ETH, USDC, WBTC, stETH)1473- Protocols used: DeFi lending/borrowing, DEX swaps, staking1474- Maturity score: very high (80-100)1475- ENS: often has a vanity ENS name1476- Gas profile: moderate gas prices (not desperate for speed), uses EIP-1559 priority fees14771478**Analyst approach:**14791. Run `generate_intelligence_report()` to get the full picture14802. Check maturity score — expect 80+14813. Review token holdings for concentration risk14824. Check for exchange deposits — the address may transact with Binance/Coinbase regularly14835. Review ENS social profile — whales often have public-facing ENS with social links14846. Cross-chain check — may have positions on Arbitrum, Optimism, Base14851486```python1487report = generate_intelligence_report(whale_address, etherscan_key, w3)1488maturity = report["maturity"]1489print(f"Maturity: {maturity['maturity_score']}/100 — {maturity['classification']}")1490# Expected: 85+/100 — Very mature1491print(f"Risk: {report['risk_assessment']['overall_score']}/100")1492# Expected: < 20 (clean whale)1493```14941495## Expected Output14961497A structured address intelligence report containing:1498- Profile card (balance, age, activity level, maturity score)1499- Entity cluster visualization (GraphML or DOT format with NetworkX export)1500- Multi-axis risk score with evidence for each dimension and configurable weights1501- Sanctions screening results (exact matches with confidence, fuzzy matches flagged for review)1502- Entity attribution with confidence score and evidence trail1503- MEV searcher assessment with signal breakdown1504- Cross-chain presence summary1505- Social profile (ENS, linked accounts)1506- Plain-text executive summary suitable for compliance or investigation use15071508```python1509# Export interaction graph for visualization1510nx.write_graphml(G, "interaction_network.graphml")15111512# Export report as JSON1513with open("intelligence_report.json", "w") as f:1514 json.dump(report, f, indent=2, default=str)1515```15161517## Money Section15181519Wallet address intelligence is a billable service for compliance teams, crypto funds, and legal firms. The skills above can be packaged as:15201521### Service Tier 1: Address Screening ($100-500/report)1522- Single-address profile with balance, age, activity summary1523- OFAC/EU/UN sanctions screening (exact + fuzzy matching)1524- Known-entity label check (exchange, exploiter, mixer)1525- Risk score across all dimensions1526- PDF report with executive summary15271528### Service Tier 2: Entity Investigation ($500-2,500/report)1529- Full profile from Tier 1, plus:1530- Multi-cluster analysis (CommonInput + behavioral + interaction graph)1531- Cross-chain address linking (identify same entity on all chains)1532- ENS/social profile discovery1533- On-chain fund flow visualization (NetworkX graph with PageRank)1534- MEV searcher identification if applicable1535- Evidence-backed attribution report15361537### Service Tier 3: Continuous Monitoring ($2,000-10,000/month)1538- Weekly or daily re-screening of a watchlist of addresses1539- Alerts when a watchlisted address interacts with a high-risk counterparty1540- Ongoing sanctions list updates (new OFAC additions matched against watchlist)1541- Monthly intelligence digest with risk score changes1542- API access for programmatic screening15431544### Service Tier 4: Custom Integration ($10,000-50,000+)1545- Deploy the screening pipeline within the client's infrastructure1546- Integrate with client's existing KYC/AML workflow1547- Custom risk weight configuration based on client's risk appetite1548- Custom entity databases for client-specific watchlists1549- SOC 2-compliant reporting and audit trails15501551## Red Flags15521553- Claiming definitive entity attribution from incomplete clustering data1554- Over-relying on a single clustering heuristic (CommonInput alone is not sufficient)1555- Ignoring false positives in sanctions list matching (false positives are common with fuzzy matching, especially for short or common address patterns)1556- Drawing conclusions about an address without checking all chains it has transacted on1557- Publishing or sharing address intelligence without proper data protection and authorization1558- Assuming an address with a known ENS identity is a real person (ENS names can be anonymous)1559- Confusing MEV activity with malicious behavior (MEV searchers operate in a legal gray area)1560- Treating low maturity scores as suspicious (new wallets are often legitimately new users)1561- Using stale sanctions lists (sanctions lists change frequently — always use the latest)1562- Over-confidence in cross-chain linking when only one heuristic is available15631564## Process156515661. **Data Gathering** — Collect on-chain data: transaction history, ERC-20 transfers, internal transactions, NFT transfers, token balances for target address, and gas usage statistics15672. **Profile Construction** — Build behavioral profile with activity patterns, protocol usage, asset holdings, gas preferences, and ENS/social data15683. **Clustering** — Apply multiple clustering algorithms in parallel: CommonInput (UTXO chains), behavioral similarity (feature-vector comparison), interaction network community detection (Louvain/Label Propagation on NetworkX graph)15694. **Sanctions Screening** — Match address against OFAC SDN list (exact and fuzzy), EU consolidated sanctions list, UN sanctions list. Flag fuzzy matches for manual review15705. **Risk Assessment** — Score against risk dimensions using known databases, behavioral indicators, and heuristic rules. Apply configurable weights based on client risk tolerance15716. **Attribution** — Attempt entity attribution through: known-address DB lookup, ENS reverse resolution, social profile extraction, MEV pattern recognition, exchange deposit address matching15727. **Cross-Chain Analysis** — Check for same address on other EVM chains, identify time-correlated funding, and notice bridging patterns15738. **Reporting** — Produce structured intelligence report with evidence for each claim, executive summary, risk breakdown, cluster visualization, and confidence scoring15741575### The Process as Automation Pipeline15761577For recurring screening workloads, the process can be fully automated:15781579```python1580def screening_pipeline(addresses: list[str], api_key: str, w3: Web3 = None, sanctions_db: dict = None) -> list[dict]:1581 """Run the full screening pipeline over a batch of addresses.15821583 Returns a list of intelligence reports sorted by risk score (highest first).1584 """1585 reports = []15861587 for addr in addresses:1588 try:1589 report = generate_intelligence_report(addr, api_key, w3)15901591 if sanctions_db:1592 screen = screen_against_sanctions(addr, sanctions_db)1593 report["sanctions_screening"] = screen15941595 reports.append(report)1596 except Exception as e:1597 reports.append({1598 "address": addr,1599 "error": str(e),1600 })16011602 # Sort by risk score descending, addresses with errors at the end1603 reports.sort(key=lambda r: r.get("risk_assessment", {}).get("overall_score", -1), reverse=True)1604 return reports1605```16061607## Verification16081609- Every cluster connection verified by at least two independent heuristics (not just one)1610- Entity attributions cross-checked against at least two independent data sources1611- Risk scores manually reviewed for false positives before reporting1612- Cluster visualizations inspected for obvious errors (mislinked addresses, missing connections)1613- All claims supported by verifiable on-chain transaction hashes or external references1614- Sanctions list fuzzy matches manually verified before flagging as positives1615- MEV classification validated against Flashbots API data where available1616- ENS resolutions confirmed by checking both forward and reverse records1617- Cross-chain links double-checked: same address ≠ same entity across all chains1618- Generated reports reviewed with a minimum two-person review for compliance-critical findings161916201621## RPC & API Endpoint Management16221623Wallet address intelligence requires querying multiple chains and APIs simultaneously.1624Without careful rate-limit management, your queries will fail mid-investigation.16251626### API Key Inventory16271628| Service | Purpose | Rate Limit | Key | Recommended Practice |1629|---|---|---|---|---|1630| Etherscan V2 | Core chain lookups (tx list, balance, internal txs) | 5 calls/sec | `ETHERSCAN_KEY` | Use 2 keys, round-robin for 10/sec burst |1631| Ethplorer | Token portfolio for any address (free, no key) | 1 call/sec | (none) | Use as fallback when Etherscan is rate-limited |1632| Chainalysis API | Sanctions / risk scoring | Varies by plan | `CHAINALYSIS_KEY` | Cache results with 24h TTL |1633| AnyBlock | Multi-chain in one RPC endpoint | 20 req/sec free | `ANYBLOCK_KEY` | Primary multi-chain RPC for wallet balance |1634| Alchemy | Archive node access for historical state | 300 req/sec free | `ALCHEMY_KEY` | Use for deep historical analysis only |1635| DeBank API | Cross-chain portfolio aggregation | 10 req/sec free | `DEBANK_KEY` | Quick wallet overview before deep dive |16361637### Rate-Limiter Pattern16381639```python1640import asyncio1641import time16421643class RateLimiter:1644 """Token-bucket rate limiter for multi-API investigations."""1645 def __init__(self, rate: float, burst: int = 5):1646 self.rate = rate # calls per second1647 self.burst = burst # max burst size1648 self.tokens = burst1649 self.last_refill = time.monotonic()1650 self._lock = asyncio.Lock()16511652 async def acquire(self):1653 async with self._lock:1654 now = time.monotonic()1655 self.tokens = min(self.burst, self.tokens + (now - self.last_refill) * self.rate)1656 self.last_refill = now1657 if self.tokens < 1:1658 wait = (1 - self.tokens) / self.rate1659 await asyncio.sleep(wait)1660 self.tokens = 01661 self.tokens -= 116621663# Usage1664rate_limiter = RateLimiter(rate=4.0, burst=10) # slightly conservative for 5/sec limit1665```16661667### Key Rotation Strategy16681669```python1670import os1671from itertools import cycle16721673class MultiKeyRotator:1674 """Rotate through multiple API keys to maximize throughput."""1675 def __init__(self, prefix: str = "ETHERSCAN"):1676 self.keys = cycle([1677 os.environ.get(f"{prefix}_KEY_{i}")1678 for i in range(1, 4)1679 if os.environ.get(f"{prefix}_KEY_{i}")1680 ])1681 if not self.keys:1682 self.keys = cycle([os.environ.get(f"{prefix}_KEY", "")])16831684 def next(self) -> str:1685 return next(self.keys)16861687# Register fallback providers in your config1688# FREE_RPC_FALLBACK = ["https://eth.llamarpc.com", "https://rpc.ankr.com/eth"]1689```16901691### When Address Intelligence Yields No Signal16921693After querying all chains and data sources, you may have an address that shows nothing:16941695| Scenario | Interpretation | Next Step |1696|---|---|---|1697| Zero tx on all mainnet chains | Address created but never used | Check if it's a counterfactual deployer (CREATE2) or unused gas token receiver |1698| Only dust transactions from mixers | Privacy-enhanced address | Attempt value-based clustering (all amounts ≤~0.01 ETH from same mixer batch) |1699| Single inbound, no outbound | Burner / one-time receive | Cross-reference with known donation addresses or airdrop contracts |1700| All activity on L2 with no L1 presence | L2-native wallet | Check if bridged from L1 via standard bridge contracts |1701| Frequent contract interactions but no DEX/CEX | Bot/contract operator | Reverse-lookup the contract interactions to identify the primary contract |1702| Known ENS but no on-chain activity | Off-chain identity holder | ENS registration costs ~$5 — not all registrants are active users |17031704## Practices from Top Investigators17051706### The ZachXBT Methodology17071708ZachXBT is the most prolific on-chain wallet investigator, having identified thousands of scammer1709wallets and published comprehensive address clusters. His core insight: **wallet intelligence is1710about patterns, not single addresses.** A wallet's value comes from its connections — both1711on-chain (transactions, interactions) and off-chain (social media, forum posts, exchange accounts).17121713### The 12-Tool Arsenal for Wallet Intelligence17141715| Tool | Wallet Intelligence Use | When to Apply |1716|---|---|---|1717| **Cielo** | Real-time tracking: monitor target wallets for any new activity | After identifying suspect wallets — maintain surveillance |1718| **Arkham** | Visual entity clusters: swap, bridge, and CEX deposit patterns | Mid-investigation: map wallet relationships |1719| **MetaSleuth** | Cross-chain address linking: find same-owner wallets on different chains | When wallets span L1s and L2s |1720| **Etherscan/Solscan** | Primary data: tx history, token holdings, internal transactions | Every wallet — always start here |1721| **TRM Labs** | Sanctions screening: check wallets against OFAC and proprietary lists | Before publishing any wallet intelligence |1722| **Breadcrumbs** | Bitcoin clustering: co-spend heuristic for UTXO wallet grouping | BTC wallet sets — cluster by common inputs |1723| **DeBank** | Cross-chain portfolio snapshot: what a wallet holds everywhere | Quick reconnaissance — assess wallet type in 10 seconds |1724| **OKLink** | Address labeling: known tags, entity tags, risk flags | Determine if wallet has been previously identified |1725| **Blockchair** | Privacy analysis: mixing detection, entity tag linking, privacy score | Identify wallets that deliberately obscure activity |1726| **Dune** | Bulk wallet analysis: SQL queries on wallet sets | Compare 100+ wallets in batch |1727| **OMNIA** | Mempool monitoring: see pending outbound tx from target wallets | Catch the moment funds move — before they confirm |1728| **MetaSuites** | Legacy labeling for historical address lookups | Old addresses (pre-2022) may only have labels here |17291730### Address Cluster Publication17311732Publishing wallet clusters publicly serves two purposes:17331. **Community defense** — enables anyone to check if they're interacting with a known scammer17342. **New signal discovery** — community cross-referencing finds connections the original1735 investigation missed17361737```python1738def format_cluster_for_publication(cluster: dict) -> str:1739 """Format wallet intelligence for public release (ZachXBT-style)."""1740 lines = ["## Wallet Cluster: " + cluster.get("label", "Unnamed Cluster")]1741 lines.append(f"_Published: {cluster.get('date', 'unknown')}_\n")1742 lines.append("### Addresses")17431744 for addr_group in cluster.get("addresses", []):1745 lines.append(f"- **{addr_group['role']}**: {addr_group['address']}")1746 if "tx_evidence" in addr_group:1747 lines.append(f" - Evidence: {addr_group['tx_evidence']}")1748 if "tag" in addr_group:1749 lines.append(f" - Tag: {addr_group['tag']}")17501751 lines.append("\n### Connections")1752 for conn in cluster.get("connections", []):1753 lines.append(f"- {conn['type']}: {conn['address_a']} → {conn['address_b']}")1754 lines.append(f" (Tx: {conn['tx_hash']}, Chain: {conn['chain']})")17551756 lines.append("\n### Cross-References")1757 for ref in cluster.get("cross_references", []):1758 lines.append(f"- Appears in: {ref['investigation']} (Role: {ref['role']})")17591760 return "\n".join(lines)1761```17621763### Exchange Coordination Protocol17641765When wallet intelligence identifies a CEX address holding stolen funds, ZachXBT's approach:176617671. **Document everything** before contacting anyone — tx hashes, amounts, timestamps, chain17682. **Identify the right contact** — exchange legal/compliance team, not support17693. **One clear ask** — "Freeze address X holding Y $ETH from hack Z" with evidence links17704. **Follow up within 24h** — exchanges handle hundreds of requests; persistence matters17715. **Public pressure when needed** — Twitter threads naming the exchange+tx hash if no response17721773```python1774def generate_exchange_report(cex_address: str, stolen_assets: float,1775 hack_tx_hash: str, victim: str) -> dict:1776 """Generate a structured report for exchange compliance teams."""1777 return {1778 "subject": f"URGENT: Stolen funds deposit at {cex_address}",1779 "body": {1780 "incident": {"victim": victim, "hack_tx": hack_tx_hash, "date": ""},1781 "stolen_assets": {"amount": stolen_assets, "token": "ETH", "current_value_usd": 0},1782 "destination": {"address": cex_address, "chain": "ethereum", "tx_hash": ""},1783 "evidence_links": [], # Block explorer URLs1784 "request": "Freeze address and notify sender for identity verification",1785 "contact": {"email": "", "role": "Legal/Compliance"},1786 },1787 "protocol": "1. Verify addresses 2. Confirm chain 3. Review evidence 4. Execute freeze",1788 }1789```17901791### Cross-Case Pattern Recognition17921793ZachXBT's most powerful technique: **identifying the same wallet appearing across multiple1794seemingly unrelated scams.** A wallet that funded an NFT mint in January and a DeFi rug pull1795in June is the same person — even if the scams look completely different.17961797```python1798def cross_case_wallet_search(wallet_clusters: list[dict], db_path: str = "known_scams.sqlite") -> list:1799 """Search across multiple investigations for overlapping wallets.18001801 Returns connections between cases — the hallmark of serial scammers.1802 """1803 import sqlite3, json1804 conn = sqlite3.connect(db_path)1805 cursor = conn.cursor()18061807 # Collect all distinct addresses from the input clusters1808 all_addresses = set()1809 for cluster in wallet_clusters:1810 for entry in cluster.get("addresses", []):1811 all_addresses.add(entry["address"].lower())18121813 # Query known scam database for matches1814 placeholders = ",".join("?" * len(all_addresses))1815 cursor.execute(1816 f"SELECT investigation_id, address, role, date FROM wallet_references "1817 f"WHERE LOWER(address) IN ({placeholders})",1818 list(all_addresses)1819 )1820 cross_refs = cursor.fetchall()18211822 # Group by investigation1823 from collections import defaultdict1824 by_investigation = defaultdict(list)1825 for inv_id, addr, role, date in cross_refs:1826 by_investigation[inv_id].append({"address": addr, "role": role, "date": date})18271828 return dict(by_investigation)1829```18301831### Getting Paid: The Investigation-to-Bounty Pipeline18321833ZachXBT's model shows wallet intelligence is monetizable:18341835- **Cluster publication** — Community donations and tips for useful intel1836- **Exchange referrals** — Some exchanges pay for intelligence that leads to frozen funds1837- **Private client work** — Token projects pay $200-$2,000+ to identify wallets behind FUD/smear campaigns1838- **Law enforcement** — Contracted tracing services for court cases1839- **Media** — Journalists purchase wallet intelligence for investigative pieces184018411842## Anti-Rationalization Table1843## Anti-Rationalization Table18441845| Rationalization | Reality |1846|---|---|1847| "The address only has a few transactions, it's not important" | Small addresses can be test wallets, intermediaries, or deliberately kept clean for compartmentalization. |1848| "The address has no known tags, it's clean" | Absence of tags means only that no one has identified it, not that it's benign. Most exploiters use fresh addresses. |1849| "I can cluster with just one method" | Single-method clustering has high false positive/negative rates. Multi-method cross-validation is essential. |1850| "The address is associated with a mixer so it's criminal" | Mixer interaction may indicate a privacy preference, not criminal activity. Context and transaction partners matter. |1851| "The address is old so it must be legitimate" | Age is not security. Exploiters frequently use old dust addresses to blend in. Cross-reference with activity patterns. |1852| "The address has a high balance so it's a whale, not a threat" | High-value addresses can be compromised or used for social engineering. Balance alone is not a trust signal. |1853| "Fuzzy matching on sanctions lists is too noisy to use" | Noise is manageable. Use tiered thresholds: exact = auto-block, fuzzy-high = manual review, fuzzy-medium = flag only. |1854| "ENS proves the address is a real person" | Anyone can register an ENS. The name proves nothing about the operator's identity without additional off-chain verification. |1855| "MEV activity means the address is malicious" | MEV extraction is legal under Ethereum protocol rules. Only specific strategies (sandwich attacks on retail) are predatory. |1856| "The address interacts with DeFi, so it's sophisticated" | Interacting with a frontend requires no sophistication. Check for direct contract interaction, flash loans, and custom scripts. |1857| "No OFAC match means the address is safe to transact with" | Sanctions lists only cover designated addresses. Most scam/fraud addresses are never sanctioned. Always combine with behavioral analysis. |1858| "Cross-chain analysis is too unreliable to include" | Imperfect heuristics still provide investigative value when clearly labeled with confidence scores and caveats. |