On-Chain Transaction Forensics
Overview
Blockchain transaction forensics involves tracing and analyzing cryptocurrency transactions to investigate illicit fund flows, identify wallet clusters, and map transaction graphs across multiple chains. Unlike traditional financial forensics, blockchain provides a public, immutable ledger where every transaction is permanently recorded. Every hop a stolen fund takes — from initial theft through mixers, bridges, DEX swaps, and exchange deposits — leaves indelible evidence.
This skill covers collecting transaction data via block explorer APIs and RPC nodes, building directed transaction flow graphs with NetworkX, applying clustering heuristics (peel chain detection, consolidation patterns, CoJoin clustering for UTXO chains, address reuse), identifying mixing services and cross-chain bridges by scanning event logs and known contract registries, and producing investigator-ready trace reports with Sankey flow visualization. The techniques here apply to EVM chains (Ethereum, BNB Chain, Polygon, Arbitrum, Optimism, Avalanche), Bitcoin-family UTXO chains, Solana, and TRON.
When to Use
Trigger phrases:
"onchain transaction forensics"
"Trace stolen funds on the blockchain"
"Follow the money on-chain"
"Analyze suspicious wallet transactions"
"Where did the stolen crypto go"
"Fund flow analysis"
"Blockchain investigation"
When investigating theft, rug pull, or hack incidents that require tracing stolen cryptocurrency
When building evidence chains for law enforcement or bounty submissions (Arkham, Lazarus Bounty)
When analyzing suspicious wallet activity for compliance or risk assessment
When reconstructing the flow of funds through mixers, bridges, or exchanges
When preparing transaction trace reports as a paid forensic service
When mapping the flow of illicit funds from a known attacker address
When performing due diligence on a large transaction or wallet before a business deal
When NOT to Use
- You need real-time monitoring of transactions (use a blockchain monitoring service or webhook provider)
- Task requires recovering private keys or seed phrases (use wallet recovery tools)
- You need to analyze smart contract logic, not transaction flow (use smart contract analysis skills)
- The blockchain is privacy-focused (Monero, Zcash) where on-chain analysis is limited to public data
- You don't have access to a reliable RPC node or block explorer API
- The investigation requires off-chain data (social media, KYC records, exchange logs) that you cannot correlate
- You are analyzing a DeFi protocol for smart contract vulnerabilities rather than following fund movements
Prerequisites
- Python 3.8+ with web3.py, requests, pandas, networkx, numpy, plotly
- Access to at least one Ethereum RPC node (Infura, Alchemy, or local node)
- Etherscan API key (or equivalent block explorer API key for target chains)
- Basic understanding of blockchain transaction structure (inputs, outputs, logs, events)
- Graph visualization tools (Graphviz
dot for DOT rendering, or plotly for HTML output)
- For UTXO chains: understanding of inputs/outputs, addresses vs public keys, change addresses
- At least 2 GB RAM for processing large transaction datasets (100k+ txs)
- Basic knowledge of DeFi protocols, bridge contracts, mixer mechanics
Multi-Chain Block Explorer Reference
| Chain |
Block Explorer |
API Base URL |
API Key Required |
Notes |
| Ethereum |
Etherscan |
https://api.etherscan.io/api |
Yes |
Most comprehensive EVM explorer |
| Ethereum (batch) |
Etherscan V2 |
https://api.etherscan.io/v2/api |
Yes |
Supports chainid param |
| BNB Chain |
BscScan |
https://api.bscscan.com/api |
Yes |
Same API shape as Etherscan |
| Polygon |
Polygonscan |
https://api.polygonscan.com/api |
Yes |
Same API shape as Etherscan |
| Arbitrum |
Arbiscan |
https://api.arbiscan.io/api |
Yes |
Same API shape as Etherscan |
| Optimism |
Optimistic Etherscan |
https://api-optimistic.etherscan.io/api |
Yes |
Same API shape as Etherscan |
| Avalanche C-Chain |
Snowtrace |
https://api.snowtrace.io/api |
Yes |
Same API shape as Etherscan |
| Base |
Basescan |
https://api.basescan.org/api |
Yes |
Same API shape as Etherscan |
| TRON |
Trongrid |
https://api.trongrid.io |
Yes (optional) |
REST API, different structure |
| Solana |
Solscan |
https://api.solscan.io |
Yes |
Different API from EVM explorers |
| Bitcoin |
Blockchair |
https://api.blockchair.com/bitcoin |
Yes (free tier) |
UTXO-specific endpoints |
| Bitcoin |
mempool.space |
https://mempool.space/api |
No |
Public, rate-limited |
| Bitcoin |
Blockchain.com |
https://blockchain.info |
No |
Legacy API, rate-limited |
| Multi-chain |
Covalent |
https://api.covalenthq.com/v1 |
Yes |
Unified API across 100+ chains |
| Multi-chain |
BitQuery |
https://graphql.bitquery.io |
Yes |
GraphQL, supports many chains |
Etherscan-like API Wrapper
The following chains use an identical API schema to Etherscan. A single helper class handles all of them:
import requests
from typing import Optional
EXPLORERS = {
"ethereum": "https://api.etherscan.io/api",
"bsc": "https://api.bscscan.com/api",
"polygon": "https://api.polygonscan.com/api",
"arbitrum": "https://api.arbiscan.io/api",
"optimism": "https://api-optimistic.etherscan.io/api",
"avalanche": "https://api.snowtrace.io/api",
"base": "https://api.basescan.org/api",
}
class ExplorerClient:
"""Unified client for Etherscan-family block explorers."""
def __init__(self, api_key: str, chain: str = "ethereum"):
self.api_key = api_key
base = EXPLORERS.get(chain)
if not base:
raise ValueError(f"Unsupported chain: {chain}")
self.base = base
def _call(self, params: dict) -> list:
params["apikey"] = self.api_key
resp = requests.get(self.base, params=params, timeout=30)
data = resp.json()
if data.get("status") != "1":
return []
return data.get("result", [])
def normal_txs(self, address: str) -> list[dict]:
return self._call({
"module": "account", "action": "txlist",
"address": address, "startblock": 0,
"endblock": 99999999, "sort": "asc"
})
def internal_txs(self, address: str) -> list[dict]:
return self._call({
"module": "account", "action": "txlistinternal",
"address": address, "startblock": 0,
"endblock": 99999999, "sort": "asc"
})
def erc20_transfers(self, address: str) -> list[dict]:
return self._call({
"module": "account", "action": "tokentx",
"address": address, "startblock": 0,
"endblock": 99999999, "sort": "asc"
})
def erc721_transfers(self, address: str) -> list[dict]:
return self._call({
"module": "account", "action": "tokennfttx",
"address": address, "startblock": 0,
"endblock": 99999999, "sort": "asc"
})
def get_logs(self, address: str, from_block: int = 0,
to_block: int = 99999999, topic0: Optional[str] = None) -> list[dict]:
params = {
"module": "logs", "action": "getLogs",
"address": address, "fromBlock": from_block,
"toBlock": to_block,
}
if topic0:
params["topic0"] = topic0
return self._call(params)
Core Workflow: Data Collection
Etherscan V2 Batch API
The Etherscan V2 API supports multi-chain queries via a single endpoint by passing chainid. This reduces complexity when tracing funds across chains:
def get_txs_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:
"""Fetch normal transactions via Etherscan V2 batch API."""
url = f"https://api.etherscan.io/v2/api"
params = {
"chainid": chain_id,
"module": "account",
"action": "txlist",
"address": address,
"startblock": 0,
"endblock": 99999999,
"sort": "asc",
"apikey": api_key
}
resp = requests.get(url, params=params, timeout=30)
return resp.json().get("result", [])
def get_internal_txs_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:
"""Fetch internal transactions via Etherscan V2 batch API."""
url = "https://api.etherscan.io/v2/api"
params = {
"chainid": chain_id,
"module": "account",
"action": "txlistinternal",
"address": address,
"startblock": 0,
"endblock": 99999999,
"sort": "asc",
"apikey": api_key
}
resp = requests.get(url, params=params, timeout=30)
return resp.json().get("result", [])
def get_erc20_transfers_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:
"""Fetch ERC-20 token transfers via Etherscan V2 batch API."""
url = "https://api.etherscan.io/v2/api"
params = {
"chainid": chain_id,
"module": "account",
"action": "tokentx",
"address": address,
"startblock": 0,
"endblock": 99999999,
"sort": "asc",
"apikey": api_key
}
resp = requests.get(url, params=params, timeout=30)
return resp.json().get("result", [])
def get_token_balances_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:
"""Fetch ERC-20 token balances via Etherscan V2."""
url = "https://api.etherscan.io/v2/api"
params = {
"chainid": chain_id,
"module": "account",
"action": "tokenlist",
"address": address,
"apikey": api_key
}
resp = requests.get(url, params=params, timeout=30)
return resp.json().get("result", [])
Chain IDs reference:
| Chain |
chainid |
| Ethereum Mainnet |
1 |
| BNB Chain |
56 |
| Polygon |
137 |
| Arbitrum One |
42161 |
| Optimism |
10 |
| Avalanche C-Chain |
43114 |
| Base |
8453 |
| Linea |
59144 |
| Scroll |
534352 |
Bitcoin Transaction Fetcher (mempool.space)
def get_btc_address_txs(address: str) -> list[dict]:
"""Fetch Bitcoin transaction history via mempool.space (no API key needed)."""
url = f"https://mempool.space/api/address/{address}/txs"
resp = requests.get(url, timeout=30)
return resp.json()
def get_btc_tx_details(txid: str) -> dict:
"""Fetch full Bitcoin transaction details."""
url = f"https://mempool.space/api/tx/{txid}"
resp = requests.get(url, timeout=30)
return resp.json()
TRON Transaction Fetcher
def get_tron_txs(address: str, api_key: str = "") -> list[dict]:
"""Fetch TRON transactions via Trongrid."""
headers = {"TRON-PRO-API-KEY": api_key} if api_key else {}
url = f"https://api.trongrid.io/v1/accounts/{address}/transactions"
resp = requests.get(url, headers=headers, timeout=30)
return resp.json().get("data", [])
Step-by-Step Methodology
Step 1: Collect All Transactions for Target Addresses
Start with the primary address from the incident — the theft wallet, the hacker's known address from a Rug Pull, or the suspicious deposit address.
def collect_all_txs(address: str, api_key: str, chain_id: int = 1) -> dict:
"""Collect normal, internal, and ERC-20 tx history for one address."""
return {
"normal": get_txs_v2(address, api_key, chain_id),
"internal": get_internal_txs_v2(address, api_key, chain_id),
"erc20": get_erc20_transfers_v2(address, api_key, chain_id),
}
- Normal TXs: Standard ETH/BNB/MATIC transfers where
from and to are directly visible
- Internal TXs: Transfers triggered by contract CALL opcodes — these are NOT visible in normal tx lists but move ETH. Critical for tracing through DEX swaps, DeFi interactions, and bridge deposits
- ERC-20 transfers: Token movements (
transfer events). The most common value transfer mechanism in DeFi hacks
- ERC-721 / ERC-1155: NFT transfers. Relevant for NFT theft and phishing investigations
Pagination: Etherscan API returns up to 10,000 rows per call. For addresses with more transactions, pass the page parameter:
def collect_all_txs_paginated(address: str, api_key: str, chain: str = "ethereum",
max_pages: int = 10) -> list[dict]:
"""Paginate through large transaction histories."""
client = ExplorerClient(api_key, chain)
all_txs = []
for page in range(1, max_pages + 1):
params = {
"module": "account", "action": "txlist",
"address": address, "startblock": 0,
"endblock": 99999999, "sort": "asc",
"page": page, "offset": 10000
}
txs = client._call(params)
if not txs:
break
all_txs.extend(txs)
if len(txs) < 10000:
break
return all_txs
Step 2: Parse and Normalize Transaction Data
Parse the raw API responses into a uniform format suitable for graph construction:
import pandas as pd
def normalize_txs(raw_txs: list[dict], tx_type: str = "normal") -> pd.DataFrame:
"""Convert raw Etherscan API results to a normalized DataFrame."""
rows = []
for tx in raw_txs:
row = {
"hash": tx.get("hash"),
"block": int(tx.get("blockNumber", 0)),
"timestamp": int(tx.get("timeStamp", 0)),
"from": tx.get("from", "").lower(),
"to": tx.get("to", "").lower(),
"value_wei": int(tx.get("value", 0)),
"value_eth": int(tx.get("value", 0)) / 1e18,
"gas": int(tx.get("gas", 0)),
"gas_price": int(tx.get("gasPrice", 0)),
"input": tx.get("input", ""),
"is_error": tx.get("isError", "0") == "1",
"tx_type": tx_type,
}
if tx_type == "erc20":
row["token_symbol"] = tx.get("tokenSymbol", "")
row["token_name"] = tx.get("tokenName", "")
row["token_decimal"] = int(tx.get("tokenDecimal", 18))
row["value_token"] = int(tx.get("value", 0)) / (10 ** int(tx.get("tokenDecimal", 18)))
rows.append(row)
return pd.DataFrame(rows)
def normalize_btc_txs(raw_txs: list[dict]) -> pd.DataFrame:
"""Normalize Bitcoin mempool.space transactions."""
rows = []
for tx in raw_txs:
txid = tx.get("txid", "")
for vin in tx.get("vin", []):
rows.append({
"hash": txid,
"from": vin.get("prevout", {}).get("scriptpubkey_address", ""),
"to": "",
"value_btc": vin.get("prevout", {}).get("value", 0) / 1e8,
"type": "input",
})
for vout in tx.get("vout", []):
rows.append({
"hash": txid,
"from": "",
"to": vout.get("scriptpubkey_address", ""),
"value_btc": vout.get("value", 0) / 1e8,
"type": "output",
})
return pd.DataFrame(rows)
Step 3: Build a Directed Transaction Graph
Construct a NetworkX directed graph from the normalized transaction data. Each node is an address, each directed edge is a transaction with amount, hash, and timestamp as edge attributes.
import networkx as nx
from typing import Optional
def build_tx_graph(df: pd.DataFrame) -> nx.DiGraph:
"""Build a directed transaction graph from normalized transaction data.
Edges: from → to, attributes include value_eth, hash, timestamp, token_symbol.
Self-loops (from == to) are excluded.
"""
G = nx.DiGraph()
for _, row in df.iterrows():
src = str(row.get("from", "")).lower()
dst = str(row.get("to", "")).lower()
if not src or not dst or src == dst:
continue
val = row.get("value_eth", 0) or row.get("value_token", 0) or 0
G.add_edge(src, dst, **{
"hash": row.get("hash", ""),
"value": float(val),
"timestamp": int(row.get("timestamp", 0)),
"token": row.get("token_symbol", "ETH"),
})
return G
def graph_summary(G: nx.DiGraph) -> dict:
"""Return summary statistics for a transaction graph."""
return {
"nodes": G.number_of_nodes(),
"edges": G.number_of_edges(),
"total_volume": sum(d["value"] for _, _, d in G.edges(data=True)),
"unique_sources": sum(1 for n, d in G.in_degree() if d == 0),
"unique_sinks": sum(1 for n, d in G.out_degree() if d == 0),
"density": nx.density(G),
}
def filter_by_value(G: nx.DiGraph, min_value: float = 0.01) -> nx.DiGraph:
"""Return a subgraph containing only edges above a minimum value threshold."""
edges_to_keep = [(u, v, d) for u, v, d in G.edges(data=True)
if d.get("value", 0) >= min_value]
H = nx.DiGraph()
H.add_edges_from(edges_to_keep)
return H
Step 4: Export Graph to DOT and GraphML
Generate visualization-ready graph formats for use with Graphviz and analysis tools:
def export_dot(G: nx.DiGraph, path: str = "tx_graph.dot") -> str:
"""Export the transaction graph as a DOT file for Graphviz rendering."""
# Relabel nodes to quoted strings for DOT compatibility
H = nx.DiGraph()
for u, v, d in G.edges(data=True):
label = f"{d.get('value', 0):.4f} {d.get('token', 'ETH')}"
H.add_edge(f'"{u[:10]}…"', f'"{v[:10]}…"', label=label)
nx.nx_pydot.write_dot(H, path)
return path
def export_graphml(G: nx.DiGraph, path: str = "tx_graph.graphml") -> str:
"""Export the transaction graph as GraphML for Gephi or yEd."""
nx.write_graphml(G, path)
return path
Step 5: Compute Graph Centrality and Find Key Nodes
Identify the most important addresses in the flow — the sink where funds concentrate, the original source, and intermediary hubs:
def find_source_nodes(G: nx.DiGraph) -> list[str]:
"""Return nodes with zero in-degree (original sources of funds)."""
return [n for n, d in G.in_degree() if d == 0]
def find_sink_nodes(G: nx.DiGraph) -> list[str]:
"""Return nodes with zero out-degree (endpoints — mixers, exchanges, bridges)."""
return [n for n, d in G.out_degree() if d == 0]
def rank_by_centrality(G: nx.DiGraph, top_n: int = 10) -> pd.DataFrame:
"""Rank addresses by weighted betweenness centrality.
Higher centrality means the address sits on more fund flow paths.
"""
if G.number_of_nodes() < 2:
return pd.DataFrame()
# Use edge weight (value) to weight paths
weight_attr = "value"
try:
centrality = nx.betweenness_centrality(G, weight=weight_attr)
except Exception:
centrality = nx.betweenness_centrality(G)
ranked = sorted(centrality.items(), key=lambda x: -x[1])
return pd.DataFrame(ranked[:top_n], columns=["address", "centrality"])
def find_top_volume_hubs(G: nx.DiGraph, top_n: int = 10) -> pd.DataFrame:
"""Find addresses with the highest total transaction volume (in + out)."""
volume = {}
for u, v, d in G.edges(data=True):
val = d.get("value", 0)
volume[u] = volume.get(u, 0) + val
volume[v] = volume.get(v, 0) + val
ranked = sorted(volume.items(), key=lambda x: -x[1])
return pd.DataFrame(ranked[:top_n], columns=["address", "total_value"])
Peel Chain Detection Algorithm
A peel chain is a money-laundering pattern where a large amount of cryptocurrency is split into gradually smaller amounts through a chain of addresses, obscuring the trail. Each address in the chain typically passes most of the funds forward while peeling off a small amount.
def detect_peel_chains(G: nx.DiGraph, max_path_length: int = 20,
min_hops: int = 3, value_decay_threshold: float = 0.95) -> list[dict]:
"""Detect peel chain patterns in a transaction graph.
A peel chain is a path where each hop passes most of the value forward
(value_decay_threshold controls how much value must be passed), with
small amounts peeled off along the way. Returns list of detected chains.
"""
chains = []
sources = find_source_nodes(G)
for src in sources:
visited = set()
path = []
current = src
while current and len(path) < max_path_length:
visited.add(current)
out_edges = list(G.out_edges(current, data=True))
if not out_edges:
break
# Sort outgoing edges by value descending
out_edges.sort(key=lambda e: e[2].get("value", 0), reverse=True)
best = out_edges[0]
next_addr = best[1]
val = best[2].get("value", 0)
# Check: does this edge pass most of the known incoming value?
in_edges = list(G.in_edges(current, data=True))
total_in = sum(e[2].get("value", 0) for e in in_edges)
if total_in > 0 and val / total_in < (1 - value_decay_threshold):
# This hop peeled off too much — likely a consolidation, not a peel chain
pass
path.append({
"from": current,
"to": next_addr,
"value": val,
"hash": best[2].get("hash", ""),
})
if next_addr in visited:
break
current = next_addr
if len(path) >= min_hops:
chains.append({
"start": src,
"end": current,
"hops": len(path),
"total_volume": sum(h["value"] for h in path),
"path": path,
})
return chains
def detect_peel_chain_heuristic_simple(address: str, txs: list[dict],
threshold_ratio: float = 0.8) -> list[dict]:
"""Detect peel chains using a simplified heuristic on raw transaction data.
A peel chain address sends most of its incoming value to a single output,
suggesting gradual fund distribution. This works on individual address analysis
without needing a full graph.
"""
outgoing = {}
for tx in txs:
frm = tx.get("from", "").lower()
to = tx.get("to", "").lower()
val = int(tx.get("value", 0))
if frm == address:
outgoing[to] = outgoing.get(to, 0) + val
if not outgoing:
return []
total_out = sum(outgoing.values())
chains = []
for dst, val in sorted(outgoing.items(), key=lambda x: -x[1]):
ratio = val / total_out if total_out > 0 else 0
if ratio >= threshold_ratio:
chains.append({
"from": address,
"to": dst,
"value": val,
"ratio": round(ratio, 4),
"pattern": "peel_chain_hop",
})
return chains
Consolidation Pattern Detector
Consolidation is the opposite of a peel chain — multiple addresses send funds to a single address. This is typical before an exchange deposit or when a hacker collects funds spread across many wallets.
def detect_consolidation(G: nx.DiGraph, min_sources: int = 3,
time_window_hours: int = 24) -> list[dict]:
"""Detect consolidation patterns in the transaction graph.
A consolidation is a node with N incoming edges from distinct addresses
within a time window. This is a classic exchange deposit / fund collection pattern.
"""
consolidations = []
for node in G.nodes():
in_edges = list(G.in_edges(node, data=True))
if len(in_edges) < min_sources:
continue
unique_sources = set(e[0] for e in in_edges)
if len(unique_sources) < min_sources:
continue
# Check time window
timestamps = [e[2].get("timestamp", 0) for e in in_edges]
timestamps = [t for t in timestamps if t > 0]
if timestamps:
span_hours = (max(timestamps) - min(timestamps)) / 3600
if span_hours > time_window_hours:
continue
total_value = sum(e[2].get("value", 0) for e in in_edges)
consolidations.append({
"sink": node,
"sources": list(unique_sources),
"num_sources": len(unique_sources),
"total_value": total_value,
"time_window_hours": round(span_hours, 2) if timestamps else 0,
"tx_hashes": [e[2].get("hash", "") for e in in_edges],
})
return sorted(consolidations, key=lambda c: -c["num_sources"])
def detect_consolidation_simple(txs: list[dict], min_sources: int = 5) -> list[dict]:
"""Detect consolidation by checking which addresses receive from many distinct senders.
Works on raw transaction data without a full graph.
"""
from collections import Counter
receivers = Counter()
receiver_txs = {}
for tx in txs:
to = tx.get("to", "").lower()
frm = tx.get("from", "").lower()
if to and frm:
receivers[to] += 1
if to not in receiver_txs:
receiver_txs[to] = []
receiver_txs[to].append(tx)
consolidations = []
for addr, count in receivers.most_common():
if count >= min_sources:
total_val = sum(int(tx.get("value", 0)) for tx in receiver_txs[addr])
consolidations.append({
"address": addr,
"incoming_count": count,
"total_value": total_val,
"source_addresses": list(set(
tx.get("from", "").lower() for tx in receiver_txs[addr]
)),
})
return consolidations
Mixer Identification
Known Mixer/Sanitizer Contract Addresses
| Service |
Chain |
Address |
Type |
Notes |
| Tornado Cash |
Ethereum |
0x12d66f87a04a9e220743712ce6d9bb1b5616b8fc |
ETH mixer |
0.1 ETH pool |
| Tornado Cash |
Ethereum |
0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936 |
ETH mixer |
1 ETH pool |
| Tornado Cash |
Ethereum |
0x910cbd523d972eb0a6f4cae4618ad62622b39dbf |
ETH mixer |
10 ETH pool |
| Tornado Cash |
Ethereum |
0xa160cdab2250da5b3f80029b6b82e1d5d0c30efb |
ETH mixer |
100 ETH pool |
| Tornado Cash |
BSC |
0x1e34a77868e19a6647b1f2f47b51ed72dede95dd |
BNB mixer |
100 BNB pool |
| Tornado Cash |
Polygon |
0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936 |
MATIC mixer |
1000 MATIC pool |
| Sinbad |
Ethereum |
0x1e31cb9b6b69a7df3225220a0ef1f0a76586d5a3 |
ETH mixer |
|
| Sinbad |
Ethereum |
0x8589427373d6d84e98730d7795d8f6f8731fda16 |
ETH mixer |
|
| Wasabi Wallet |
Bitcoin |
bc1q… (varies) |
BTC CoinJoin |
Uses PayNym, no fixed address |
| Samourai Whirlpool |
Bitcoin |
(Coordinator) |
BTC CoinJoin |
No fixed deposit address |
| ChainFlip |
Ethereum |
0x60fB0B27447480E3304bB7b2660e9C081D3775fc |
Cross-chain mixer |
|
| eXch |
Ethereum |
(varies) |
Swap-based mixer |
Swaps and splits |
| FixedFloat |
Multi |
(varies) |
Swap-based mixer |
No-KYC exchange used for obfuscation |
Mixer Deposit Detection Heuristics
# Known mixer contract addresses (Ethereum mainnet)
MIXER_ADDRESSES = {
# Tornado Cash deposit addresses (by pool size)
"0x12d66f87a04a9e220743712ce6d9bb1b5616b8fc": "tornado_0.1_eth",
"0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936": "tornado_1_eth",
"0x910cbd523d972eb0a6f4cae4618ad62622b39dbf": "tornado_10_eth",
"0xa160cdab2250da5b3f80029b6b82e1d5d0c30efb": "tornado_100_eth",
# Sinbad
"0x1e31cb9b6b69a7df3225220a0ef1f0a76586d5a3": "sinbad_1",
"0x8589427373d6d84e98730d7795d8f6f8731fda16": "sinbad_2",
}
def tag_mixer_interactions(df: pd.DataFrame) -> pd.DataFrame:
"""Tag transactions involving known mixer addresses."""
df_lower = df.copy()
df_lower["to"] = df_lower["to"].str.lower()
df_lower["from"] = df_lower["from"].str.lower()
df_lower["mixer"] = "unknown"
for addr, name in MIXER_ADDRESSES.items():
mask = (df_lower["to"] == addr) | (df_lower["from"] == addr)
df_lower.loc[mask, "mixer"] = name
return df_lower
def detect_mixer_deposit_by_amount(address: str, txs: list[dict],
known_amounts: list[float] = None) -> bool:
"""Detect potential mixer deposits by checking for exact-amount patterns.
Mixers use fixed deposit amounts (e.g., Tornado Cash pools).
If an address sends an exact pool amount to a contract, it's likely a mixer deposit.
"""
if known_amounts is None:
known_amounts = [0.1, 1.0, 10.0, 100.0] # Tornado Cash standard pool amounts
for tx in txs:
frm = tx.get("from", "").lower()
val_eth = int(tx.get("value", 0)) / 1e18
if frm == address.lower() and val_eth in known_amounts:
# Verify the recipient has contract code (mixer contract, not EOA)
return True
return False
def detect_mixer_timing_anomaly(txs: list[dict], time_window_minutes: int = 30) -> list[dict]:
"""Detect mixer deposit patterns by timing.
Mixer deposits often cluster in tight time windows.
Multiple deposits to different addresses from the same source within a short window
is a strong mixer indicator.
"""
from collections import defaultdict
windows = defaultdict(list)
for tx in txs:
ts = int(tx.get("timeStamp", 0))
to = tx.get("to", "").lower()
if ts:
bucket_key = ts // (time_window_minutes * 60) # bucket by time window
windows[bucket_key].append(tx)
suspicious = []
for bucket, group in windows.items():
unique_recipients = set(t.get("to", "").lower() for t in group)
if len(unique_recipients) >= 3:
total_val = sum(int(t.get("value", 0)) for t in group) / 1e18
suspicious.append({
"time_bucket": bucket,
"num_txs": len(group),
"unique_recipients": len(unique_recipients),
"total_value_eth": total_val,
"txs": [t.get("hash", "") for t in group[:10]],
})
return suspicious
Cross-Chain Bridge Tracing
Bridges are the most common obfuscation technique post-hack. The attacker deposits on Chain A and withdraws on Chain B, often swapping the asset type.
Known Bridge Contract Addresses
| Bridge |
Chain |
Contract Address |
Event Signature |
| LayerZero Endpoint |
Ethereum |
0x66A71Dcef29A0fFBDBE3c6a460a3B5BC225Cd675 |
MessagePayload |
| Stargate Router |
Ethereum |
0x8731d54E9D02c286767d56ac03e8037C07e01e98 |
Swap |
| Stargate Router |
Arbitrum |
0x53Bf833A5d6c4ddA888F69c22C88C9f356a41614 |
Swap |
| Wormhole Core |
Ethereum |
0x98f3c9e6E3fAce36bAAd05FE09d375Ef1464288B |
LogMessagePublished |
| Wormhole Token Bridge |
Ethereum |
0x3ee18B2214AFF97000D974cf647E7C347E8fa585 |
TransferRedeemed |
| Across |
Ethereum |
0x5c7BCd6E7De5423a257D81B442095A1a6ced35C5 |
FundsDeposited |
| Across |
Arbitrum |
0x3bB4445D30AC020a84c1b5A8A2C6248ebC9779D0 |
FundsDeposited |
| Synapse |
Ethereum |
0x2796317b0fF8538F253012862c06787Adfb8c3aC |
TokenDeposit |
| Synapse |
Arbitrum |
0x9D33eeE1540BdA15C2021C22E14dfdB41c58485b |
TokenDeposit |
| Hop |
Ethereum |
0x3666f603Cc164936C1b87e207F36BEBa4AC5f18a |
TransferSent |
| Hop |
Polygon |
0x3666f603Cc164936C1b87e207F36BEBa4AC5f18a |
TransferSent |
| AnySwap (Multichain) |
Ethereum |
0x6b7a87899490EcE95443e979cA9485CBE7E71522 |
AnySwapOut |
| Celer cBridge |
Ethereum |
0x1619DE6B6B20eD217a58d00f37B9d47C7663feca |
Send |
Bridge Detection Code
BRIDGE_CONTRACTS = {
"layerzero_endpoint": {
"ethereum": ["0x66a71dcef29a0ffbdbe3c6a460a3b5bc225cd675"],
"arbitrum": ["0x3c2269811836af69497e5f486a85d7316753cf02"],
"polygon": ["0x3c2269811836af69497e5f486a85d7316753cf02"],
},
"stargate_router": {
"ethereum": ["0x8731d54e9d02c286767d56ac03e8037c07e01e98"],
"arbitrum": ["0x53bf833a5d6c4dda888f69c22c88c9f356a41614"],
"polygon": ["0x53bf833a5d6c4dda888f69c22c88c9f356a41614"],
},
"across": {
"ethereum": ["0x5c7bcd6e7de5423a257d81b442095a1a6ced35c5"],
"arbitrum": ["0x3bb4445d30ac020a84c1b5a8a2c6248ebc9779d0"],
},
"synapse": {
"ethereum": ["0x2796317b0ff8538f253012862c06787adfb8c3ac"],
"arbitrum": ["0x9d33eee1540bda15c2021c22e14dfdb41c58485b"],
},
"wormhole": {
"ethereum": ["0x98f3c9e6e3face36baad05fe09d375ef1464288b"],
},
"hop": {
"ethereum": ["0x3666f603cc164936c1b87e207f36beba4ac5f18a"],
"polygon": ["0x3666f603cc164936c1b87e207f36beba4ac5f18a"],
},
"celer": {
"ethereum": ["0x1619de6b6b20ed217a58d00f37b9d47c7663feca"],
},
}
# Flatten bridge addresses to a single set for fast lookup
ALL_BRIDGE_ADDRESSES = set()
for name, chains in BRIDGE_CONTRACTS.items():
for chain_addrs in chains.values():
ALL_BRIDGE_ADDRESSES.update(chain_addrs)
def tag_bridge_interactions(df: pd.DataFrame) -> pd.DataFrame:
"""Tag transactions involving known bridge contracts."""
df_lower = df.copy()
for col in ["to", "from"]:
df_lower[col] = df_lower[col].str.lower()
def lookup(addr):
addr = addr.lower()
for name, chains in BRIDGE_CONTRACTS.items():
for chain_addrs in chains.values():
if addr in chain_addrs:
return name
return ""
df_lower["bridge"] = df_lower["to"].apply(lookup)
# Also check 'from' field for bridge interactions
mask_from = df_lower["bridge"] == ""
df_lower.loc[mask_from, "bridge"] = df_lower.loc[mask_from, "from"].apply(lookup)
return df_lower
def detect_bridge_transfer(tx: dict, receipt_logs: list[dict]) -> dict:
"""Detect bridge transfer from a transaction's event logs.
Returns destination chain info if a bridge event is found.
"""
for log in receipt_logs:
addr = log.get("address", "").lower()
topics = log.get("topics", [])
# Stargate Swap event: topics[0] = Swap(uint16,uint16,address,address,uint256,uint256)
if addr in ALL_BRIDGE_ADDRESSES and len(topics) >= 3:
return {
"bridge_detected": True,
"contract": addr,
"tx_hash": tx.get("hash", ""),
"topics": topics,
"data": log.get("data", ""),
"note": "Bridge interaction detected — check destination chain in event data",
}
return {"bridge_detected": False}
def extract_bridge_destination(tx_hash: str, web3_provider, bridge_address: str) -> int:
"""Extract destination chain ID from a Stargate bridge event.
Stargate emits Swap(uint16 chainIdFrom, uint16 chainIdTo, ...).
The chainIdTo is typically topic[2] in the Swap event.
"""
receipt = web3_provider.eth.get_transaction_receipt(tx_hash)
for log in receipt.logs:
if log.address.lower() == bridge_address.lower():
topics = log.topics
if len(topics) >= 3:
dest_chain_id = int.from_bytes(topics[2], "big")
return dest_chain_id
return 0
Wallet Clustering Implementation
CoJoin / Common-Input Clustering (UTXO Chains)
Bitcoin-like UTXO chains enable a powerful clustering heuristic: if two addresses appear as inputs in the same transaction, they are controlled by the same entity (assuming multi-signature or CoinJoin is not involved). This is called CoJoin or Common-Input-Ownership Heuristic.
def cluster_by_common_input(txs_utxo: list[dict]) -> dict[str, set[str]]:
"""Cluster Bitcoin addresses by common-input ownership heuristic.
If addresses A and B appear as inputs in the same transaction,
they are likely controlled by the same entity. Returns a dict
mapping cluster_id -> set of addresses.
"""
address_to_tx = {}
tx_to_addresses = {}
for tx in txs_utxo:
txid = tx.get("txid", "")
input_addresses = set()
for vin in tx.get("vin", []):
addr = vin.get("prevout", {}).get("scriptpubkey_address", "")
if addr:
input_addresses.add(addr)
if len(input_addresses) >= 2:
tx_to_addresses[txid] = input_addresses
for addr in input_addresses:
if addr not in address_to_tx:
address_to_tx[addr] = []
address_to_tx[addr].append(txid)
# Union-Find to merge clusters
parent = {}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
all_addresses = set()
for addresses in tx_to_addresses.values():
addrs = list(addresses)
for addr in addrs:
if addr not in parent:
parent[addr] = addr
all_addresses.add(addr)
for i in range(1, len(addrs)):
union(addrs[0], addrs[i])
# Build clusters
clusters = {}
for addr in all_addresses:
root = find(addr)
if root not in clusters:
clusters[root] = set()
clusters[root].add(addr)
return clusters
def cluster_by_deposit_address(txs: list[dict], exchange_pattern: str = "binance") -> list[dict]:
"""Identify exchange deposit addresses by known patterns.
Many exchanges use deterministic deposit addresses.
This heuristic clusters addresses that receive from many senders
as potential exchange deposit addresses.
"""
from collections import Counter, defaultdict
deposits_to = Counter()
depositors = defaultdict(set)
for tx in txs:
to = tx.get("to", "").lower()
frm = tx.get("from", "").lower()
if to and frm:
deposits_to[to] += 1
depositors[to].add(frm)
clusters = []
for addr, count in deposits_to.most_common(50):
if count >= 10:
clusters.append({
"deposit_address": addr,
"incoming_count": count,
"unique_depositors": len(depositors[addr]),
"likely_entity": exchange_pattern if count > 50 else "unknown",
})
return clusters
EVM Address Reuse Clustering
Even on account-based chains, addresses can be clustered by behavioral patterns:
def cluster_by_behavior(df: pd.DataFrame, min_interactions: int = 5) -> dict[str, list[str]]:
"""Cluster EVM addresses by behavioral similarity.
If two addresses interact with the same set of contracts/protocols,
they may be controlled by the same entity.
"""
from collections import defaultdict
addr_contracts = defaultdict(set)
for _, row in df.iterrows():
frm = str(row.get("from", "")).lower()
to = str(row.get("to", "")).lower()
if frm and to:
addr_contracts[frm].add(to)
if to:
addr_contracts[to] # ensure key exists
# Jaccard similarity between address contract sets
addrs = list(addr_contracts.keys())
clusters = defaultdict(list)
assigned = set()
for i, a1 in enumerate(addrs):
if a1 in assigned:
continue
set1 = addr_contracts[a1]
if len(set1) < min_interactions:
continue
cluster = [a1]
assigned.add(a1)
for a2 in addrs[i + 1:]:
if a2 in assigned:
continue
set2 = addr_contracts[a2]
if len(set2) < min_interactions:
continue
intersection = len(set1 & set2)
union = len(set1 | set2)
if union > 0 and intersection / union >= 0.7:
cluster.append(a2)
assigned.add(a2)
if len(cluster) >= 2:
clusters[f"behavioral_cluster_{len(clusters)}"] = cluster
r
…(truncated)
1---2name: onchain-transaction-forensics3description: Use when trace and analyze blockchain transactions to investigate illicit4 fund flows, identify wallet clusters, and map transaction graphs across multiple5 blockchains. Use when investigating stolen funds, following money trails on-chain,6 analyzing suspicious addresses, or tracing cross-chain transactions.7domain: cybersecurity8license: Apache-2.09subdomain: blockchain-security10tags:11- blockchain12- forensics13- onchain14- transactions15- wallet16- tracing17- investigation18- evm19- bitcoin20- money21version: '1.0'22author: oyi7723category: cybersecurity24metadata:25 source: https://skillmd.com/skills/oyi77/onchain-transaction-forensics26---272829# On-Chain Transaction Forensics3031## Overview3233Blockchain transaction forensics involves tracing and analyzing cryptocurrency transactions to investigate illicit fund flows, identify wallet clusters, and map transaction graphs across multiple chains. Unlike traditional financial forensics, blockchain provides a public, immutable ledger where every transaction is permanently recorded. Every hop a stolen fund takes — from initial theft through mixers, bridges, DEX swaps, and exchange deposits — leaves indelible evidence.3435This skill covers collecting transaction data via block explorer APIs and RPC nodes, building directed transaction flow graphs with NetworkX, applying clustering heuristics (peel chain detection, consolidation patterns, CoJoin clustering for UTXO chains, address reuse), identifying mixing services and cross-chain bridges by scanning event logs and known contract registries, and producing investigator-ready trace reports with Sankey flow visualization. The techniques here apply to EVM chains (Ethereum, BNB Chain, Polygon, Arbitrum, Optimism, Avalanche), Bitcoin-family UTXO chains, Solana, and TRON.3637## When to Use3839**Trigger phrases:**40- "onchain transaction forensics"41- "Trace stolen funds on the blockchain"42- "Follow the money on-chain"43- "Analyze suspicious wallet transactions"44- "Where did the stolen crypto go"45- "Fund flow analysis"46- "Blockchain investigation"4748- When investigating theft, rug pull, or hack incidents that require tracing stolen cryptocurrency49- When building evidence chains for law enforcement or bounty submissions (Arkham, Lazarus Bounty)50- When analyzing suspicious wallet activity for compliance or risk assessment51- When reconstructing the flow of funds through mixers, bridges, or exchanges52- When preparing transaction trace reports as a paid forensic service53- When mapping the flow of illicit funds from a known attacker address54- When performing due diligence on a large transaction or wallet before a business deal5556## When NOT to Use5758- You need real-time monitoring of transactions (use a blockchain monitoring service or webhook provider)59- Task requires recovering private keys or seed phrases (use wallet recovery tools)60- You need to analyze smart contract logic, not transaction flow (use smart contract analysis skills)61- The blockchain is privacy-focused (Monero, Zcash) where on-chain analysis is limited to public data62- You don't have access to a reliable RPC node or block explorer API63- The investigation requires off-chain data (social media, KYC records, exchange logs) that you cannot correlate64- You are analyzing a DeFi protocol for smart contract vulnerabilities rather than following fund movements6566## Prerequisites6768- Python 3.8+ with web3.py, requests, pandas, networkx, numpy, plotly69- Access to at least one Ethereum RPC node (Infura, Alchemy, or local node)70- Etherscan API key (or equivalent block explorer API key for target chains)71- Basic understanding of blockchain transaction structure (inputs, outputs, logs, events)72- Graph visualization tools (Graphviz `dot` for DOT rendering, or plotly for HTML output)73- For UTXO chains: understanding of inputs/outputs, addresses vs public keys, change addresses74- At least 2 GB RAM for processing large transaction datasets (100k+ txs)75- Basic knowledge of DeFi protocols, bridge contracts, mixer mechanics7677## Multi-Chain Block Explorer Reference7879| Chain | Block Explorer | API Base URL | API Key Required | Notes |80|---|---|---|---|---|81| Ethereum | Etherscan | `https://api.etherscan.io/api` | Yes | Most comprehensive EVM explorer |82| Ethereum (batch) | Etherscan V2 | `https://api.etherscan.io/v2/api` | Yes | Supports `chainid` param |83| BNB Chain | BscScan | `https://api.bscscan.com/api` | Yes | Same API shape as Etherscan |84| Polygon | Polygonscan | `https://api.polygonscan.com/api` | Yes | Same API shape as Etherscan |85| Arbitrum | Arbiscan | `https://api.arbiscan.io/api` | Yes | Same API shape as Etherscan |86| Optimism | Optimistic Etherscan | `https://api-optimistic.etherscan.io/api` | Yes | Same API shape as Etherscan |87| Avalanche C-Chain | Snowtrace | `https://api.snowtrace.io/api` | Yes | Same API shape as Etherscan |88| Base | Basescan | `https://api.basescan.org/api` | Yes | Same API shape as Etherscan |89| TRON | Trongrid | `https://api.trongrid.io` | Yes (optional) | REST API, different structure |90| Solana | Solscan | `https://api.solscan.io` | Yes | Different API from EVM explorers |91| Bitcoin | Blockchair | `https://api.blockchair.com/bitcoin` | Yes (free tier) | UTXO-specific endpoints |92| Bitcoin | mempool.space | `https://mempool.space/api` | No | Public, rate-limited |93| Bitcoin | Blockchain.com | `https://blockchain.info` | No | Legacy API, rate-limited |94| Multi-chain | Covalent | `https://api.covalenthq.com/v1` | Yes | Unified API across 100+ chains |95| Multi-chain | BitQuery | `https://graphql.bitquery.io` | Yes | GraphQL, supports many chains |9697### Etherscan-like API Wrapper9899The following chains use an identical API schema to Etherscan. A single helper class handles all of them:100101```python102import requests103from typing import Optional104105EXPLORERS = {106 "ethereum": "https://api.etherscan.io/api",107 "bsc": "https://api.bscscan.com/api",108 "polygon": "https://api.polygonscan.com/api",109 "arbitrum": "https://api.arbiscan.io/api",110 "optimism": "https://api-optimistic.etherscan.io/api",111 "avalanche": "https://api.snowtrace.io/api",112 "base": "https://api.basescan.org/api",113}114115class ExplorerClient:116 """Unified client for Etherscan-family block explorers."""117118 def __init__(self, api_key: str, chain: str = "ethereum"):119 self.api_key = api_key120 base = EXPLORERS.get(chain)121 if not base:122 raise ValueError(f"Unsupported chain: {chain}")123 self.base = base124125 def _call(self, params: dict) -> list:126 params["apikey"] = self.api_key127 resp = requests.get(self.base, params=params, timeout=30)128 data = resp.json()129 if data.get("status") != "1":130 return []131 return data.get("result", [])132133 def normal_txs(self, address: str) -> list[dict]:134 return self._call({135 "module": "account", "action": "txlist",136 "address": address, "startblock": 0,137 "endblock": 99999999, "sort": "asc"138 })139140 def internal_txs(self, address: str) -> list[dict]:141 return self._call({142 "module": "account", "action": "txlistinternal",143 "address": address, "startblock": 0,144 "endblock": 99999999, "sort": "asc"145 })146147 def erc20_transfers(self, address: str) -> list[dict]:148 return self._call({149 "module": "account", "action": "tokentx",150 "address": address, "startblock": 0,151 "endblock": 99999999, "sort": "asc"152 })153154 def erc721_transfers(self, address: str) -> list[dict]:155 return self._call({156 "module": "account", "action": "tokennfttx",157 "address": address, "startblock": 0,158 "endblock": 99999999, "sort": "asc"159 })160161 def get_logs(self, address: str, from_block: int = 0,162 to_block: int = 99999999, topic0: Optional[str] = None) -> list[dict]:163 params = {164 "module": "logs", "action": "getLogs",165 "address": address, "fromBlock": from_block,166 "toBlock": to_block,167 }168 if topic0:169 params["topic0"] = topic0170 return self._call(params)171```172173## Core Workflow: Data Collection174175### Etherscan V2 Batch API176177The Etherscan V2 API supports multi-chain queries via a single endpoint by passing `chainid`. This reduces complexity when tracing funds across chains:178179```python180def get_txs_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:181 """Fetch normal transactions via Etherscan V2 batch API."""182 url = f"https://api.etherscan.io/v2/api"183 params = {184 "chainid": chain_id,185 "module": "account",186 "action": "txlist",187 "address": address,188 "startblock": 0,189 "endblock": 99999999,190 "sort": "asc",191 "apikey": api_key192 }193 resp = requests.get(url, params=params, timeout=30)194 return resp.json().get("result", [])195196197def get_internal_txs_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:198 """Fetch internal transactions via Etherscan V2 batch API."""199 url = "https://api.etherscan.io/v2/api"200 params = {201 "chainid": chain_id,202 "module": "account",203 "action": "txlistinternal",204 "address": address,205 "startblock": 0,206 "endblock": 99999999,207 "sort": "asc",208 "apikey": api_key209 }210 resp = requests.get(url, params=params, timeout=30)211 return resp.json().get("result", [])212213214def get_erc20_transfers_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:215 """Fetch ERC-20 token transfers via Etherscan V2 batch API."""216 url = "https://api.etherscan.io/v2/api"217 params = {218 "chainid": chain_id,219 "module": "account",220 "action": "tokentx",221 "address": address,222 "startblock": 0,223 "endblock": 99999999,224 "sort": "asc",225 "apikey": api_key226 }227 resp = requests.get(url, params=params, timeout=30)228 return resp.json().get("result", [])229230231def get_token_balances_v2(address: str, api_key: str, chain_id: int = 1) -> list[dict]:232 """Fetch ERC-20 token balances via Etherscan V2."""233 url = "https://api.etherscan.io/v2/api"234 params = {235 "chainid": chain_id,236 "module": "account",237 "action": "tokenlist",238 "address": address,239 "apikey": api_key240 }241 resp = requests.get(url, params=params, timeout=30)242 return resp.json().get("result", [])243```244245**Chain IDs reference:**246247| Chain | chainid |248|---|---|249| Ethereum Mainnet | 1 |250| BNB Chain | 56 |251| Polygon | 137 |252| Arbitrum One | 42161 |253| Optimism | 10 |254| Avalanche C-Chain | 43114 |255| Base | 8453 |256| Linea | 59144 |257| Scroll | 534352 |258259### Bitcoin Transaction Fetcher (mempool.space)260261```python262def get_btc_address_txs(address: str) -> list[dict]:263 """Fetch Bitcoin transaction history via mempool.space (no API key needed)."""264 url = f"https://mempool.space/api/address/{address}/txs"265 resp = requests.get(url, timeout=30)266 return resp.json()267268269def get_btc_tx_details(txid: str) -> dict:270 """Fetch full Bitcoin transaction details."""271 url = f"https://mempool.space/api/tx/{txid}"272 resp = requests.get(url, timeout=30)273 return resp.json()274```275276### TRON Transaction Fetcher277278```python279def get_tron_txs(address: str, api_key: str = "") -> list[dict]:280 """Fetch TRON transactions via Trongrid."""281 headers = {"TRON-PRO-API-KEY": api_key} if api_key else {}282 url = f"https://api.trongrid.io/v1/accounts/{address}/transactions"283 resp = requests.get(url, headers=headers, timeout=30)284 return resp.json().get("data", [])285```286287## Step-by-Step Methodology288289### Step 1: Collect All Transactions for Target Addresses290291Start with the primary address from the incident — the theft wallet, the hacker's known address from a Rug Pull, or the suspicious deposit address.292293```python294def collect_all_txs(address: str, api_key: str, chain_id: int = 1) -> dict:295 """Collect normal, internal, and ERC-20 tx history for one address."""296 return {297 "normal": get_txs_v2(address, api_key, chain_id),298 "internal": get_internal_txs_v2(address, api_key, chain_id),299 "erc20": get_erc20_transfers_v2(address, api_key, chain_id),300 }301```302303- **Normal TXs**: Standard ETH/BNB/MATIC transfers where `from` and `to` are directly visible304- **Internal TXs**: Transfers triggered by contract CALL opcodes — these are NOT visible in normal tx lists but move ETH. Critical for tracing through DEX swaps, DeFi interactions, and bridge deposits305- **ERC-20 transfers**: Token movements (`transfer` events). The most common value transfer mechanism in DeFi hacks306- **ERC-721 / ERC-1155**: NFT transfers. Relevant for NFT theft and phishing investigations307308**Pagination**: Etherscan API returns up to 10,000 rows per call. For addresses with more transactions, pass the `page` parameter:309310```python311def collect_all_txs_paginated(address: str, api_key: str, chain: str = "ethereum",312 max_pages: int = 10) -> list[dict]:313 """Paginate through large transaction histories."""314 client = ExplorerClient(api_key, chain)315 all_txs = []316 for page in range(1, max_pages + 1):317 params = {318 "module": "account", "action": "txlist",319 "address": address, "startblock": 0,320 "endblock": 99999999, "sort": "asc",321 "page": page, "offset": 10000322 }323 txs = client._call(params)324 if not txs:325 break326 all_txs.extend(txs)327 if len(txs) < 10000:328 break329 return all_txs330```331332### Step 2: Parse and Normalize Transaction Data333334Parse the raw API responses into a uniform format suitable for graph construction:335336```python337import pandas as pd338339def normalize_txs(raw_txs: list[dict], tx_type: str = "normal") -> pd.DataFrame:340 """Convert raw Etherscan API results to a normalized DataFrame."""341 rows = []342 for tx in raw_txs:343 row = {344 "hash": tx.get("hash"),345 "block": int(tx.get("blockNumber", 0)),346 "timestamp": int(tx.get("timeStamp", 0)),347 "from": tx.get("from", "").lower(),348 "to": tx.get("to", "").lower(),349 "value_wei": int(tx.get("value", 0)),350 "value_eth": int(tx.get("value", 0)) / 1e18,351 "gas": int(tx.get("gas", 0)),352 "gas_price": int(tx.get("gasPrice", 0)),353 "input": tx.get("input", ""),354 "is_error": tx.get("isError", "0") == "1",355 "tx_type": tx_type,356 }357 if tx_type == "erc20":358 row["token_symbol"] = tx.get("tokenSymbol", "")359 row["token_name"] = tx.get("tokenName", "")360 row["token_decimal"] = int(tx.get("tokenDecimal", 18))361 row["value_token"] = int(tx.get("value", 0)) / (10 ** int(tx.get("tokenDecimal", 18)))362 rows.append(row)363 return pd.DataFrame(rows)364365366def normalize_btc_txs(raw_txs: list[dict]) -> pd.DataFrame:367 """Normalize Bitcoin mempool.space transactions."""368 rows = []369 for tx in raw_txs:370 txid = tx.get("txid", "")371 for vin in tx.get("vin", []):372 rows.append({373 "hash": txid,374 "from": vin.get("prevout", {}).get("scriptpubkey_address", ""),375 "to": "",376 "value_btc": vin.get("prevout", {}).get("value", 0) / 1e8,377 "type": "input",378 })379 for vout in tx.get("vout", []):380 rows.append({381 "hash": txid,382 "from": "",383 "to": vout.get("scriptpubkey_address", ""),384 "value_btc": vout.get("value", 0) / 1e8,385 "type": "output",386 })387 return pd.DataFrame(rows)388```389390### Step 3: Build a Directed Transaction Graph391392Construct a NetworkX directed graph from the normalized transaction data. Each node is an address, each directed edge is a transaction with amount, hash, and timestamp as edge attributes.393394```python395import networkx as nx396from typing import Optional397398def build_tx_graph(df: pd.DataFrame) -> nx.DiGraph:399 """Build a directed transaction graph from normalized transaction data.400401 Edges: from → to, attributes include value_eth, hash, timestamp, token_symbol.402 Self-loops (from == to) are excluded.403 """404 G = nx.DiGraph()405 for _, row in df.iterrows():406 src = str(row.get("from", "")).lower()407 dst = str(row.get("to", "")).lower()408 if not src or not dst or src == dst:409 continue410 val = row.get("value_eth", 0) or row.get("value_token", 0) or 0411 G.add_edge(src, dst, **{412 "hash": row.get("hash", ""),413 "value": float(val),414 "timestamp": int(row.get("timestamp", 0)),415 "token": row.get("token_symbol", "ETH"),416 })417 return G418419420def graph_summary(G: nx.DiGraph) -> dict:421 """Return summary statistics for a transaction graph."""422 return {423 "nodes": G.number_of_nodes(),424 "edges": G.number_of_edges(),425 "total_volume": sum(d["value"] for _, _, d in G.edges(data=True)),426 "unique_sources": sum(1 for n, d in G.in_degree() if d == 0),427 "unique_sinks": sum(1 for n, d in G.out_degree() if d == 0),428 "density": nx.density(G),429 }430431432def filter_by_value(G: nx.DiGraph, min_value: float = 0.01) -> nx.DiGraph:433 """Return a subgraph containing only edges above a minimum value threshold."""434 edges_to_keep = [(u, v, d) for u, v, d in G.edges(data=True)435 if d.get("value", 0) >= min_value]436 H = nx.DiGraph()437 H.add_edges_from(edges_to_keep)438 return H439```440441### Step 4: Export Graph to DOT and GraphML442443Generate visualization-ready graph formats for use with Graphviz and analysis tools:444445```python446def export_dot(G: nx.DiGraph, path: str = "tx_graph.dot") -> str:447 """Export the transaction graph as a DOT file for Graphviz rendering."""448 # Relabel nodes to quoted strings for DOT compatibility449 H = nx.DiGraph()450 for u, v, d in G.edges(data=True):451 label = f"{d.get('value', 0):.4f} {d.get('token', 'ETH')}"452 H.add_edge(f'"{u[:10]}…"', f'"{v[:10]}…"', label=label)453 nx.nx_pydot.write_dot(H, path)454 return path455456457def export_graphml(G: nx.DiGraph, path: str = "tx_graph.graphml") -> str:458 """Export the transaction graph as GraphML for Gephi or yEd."""459 nx.write_graphml(G, path)460 return path461```462463### Step 5: Compute Graph Centrality and Find Key Nodes464465Identify the most important addresses in the flow — the sink where funds concentrate, the original source, and intermediary hubs:466467```python468def find_source_nodes(G: nx.DiGraph) -> list[str]:469 """Return nodes with zero in-degree (original sources of funds)."""470 return [n for n, d in G.in_degree() if d == 0]471472473def find_sink_nodes(G: nx.DiGraph) -> list[str]:474 """Return nodes with zero out-degree (endpoints — mixers, exchanges, bridges)."""475 return [n for n, d in G.out_degree() if d == 0]476477478def rank_by_centrality(G: nx.DiGraph, top_n: int = 10) -> pd.DataFrame:479 """Rank addresses by weighted betweenness centrality.480481 Higher centrality means the address sits on more fund flow paths.482 """483 if G.number_of_nodes() < 2:484 return pd.DataFrame()485 # Use edge weight (value) to weight paths486 weight_attr = "value"487 try:488 centrality = nx.betweenness_centrality(G, weight=weight_attr)489 except Exception:490 centrality = nx.betweenness_centrality(G)491 ranked = sorted(centrality.items(), key=lambda x: -x[1])492 return pd.DataFrame(ranked[:top_n], columns=["address", "centrality"])493494495def find_top_volume_hubs(G: nx.DiGraph, top_n: int = 10) -> pd.DataFrame:496 """Find addresses with the highest total transaction volume (in + out)."""497 volume = {}498 for u, v, d in G.edges(data=True):499 val = d.get("value", 0)500 volume[u] = volume.get(u, 0) + val501 volume[v] = volume.get(v, 0) + val502 ranked = sorted(volume.items(), key=lambda x: -x[1])503 return pd.DataFrame(ranked[:top_n], columns=["address", "total_value"])504```505506## Peel Chain Detection Algorithm507508A peel chain is a money-laundering pattern where a large amount of cryptocurrency is split into gradually smaller amounts through a chain of addresses, obscuring the trail. Each address in the chain typically passes most of the funds forward while peeling off a small amount.509510```python511def detect_peel_chains(G: nx.DiGraph, max_path_length: int = 20,512 min_hops: int = 3, value_decay_threshold: float = 0.95) -> list[dict]:513 """Detect peel chain patterns in a transaction graph.514515 A peel chain is a path where each hop passes most of the value forward516 (value_decay_threshold controls how much value must be passed), with517 small amounts peeled off along the way. Returns list of detected chains.518 """519 chains = []520 sources = find_source_nodes(G)521522 for src in sources:523 visited = set()524 path = []525 current = src526 while current and len(path) < max_path_length:527 visited.add(current)528 out_edges = list(G.out_edges(current, data=True))529 if not out_edges:530 break531 # Sort outgoing edges by value descending532 out_edges.sort(key=lambda e: e[2].get("value", 0), reverse=True)533 best = out_edges[0]534 next_addr = best[1]535 val = best[2].get("value", 0)536537 # Check: does this edge pass most of the known incoming value?538 in_edges = list(G.in_edges(current, data=True))539 total_in = sum(e[2].get("value", 0) for e in in_edges)540541 if total_in > 0 and val / total_in < (1 - value_decay_threshold):542 # This hop peeled off too much — likely a consolidation, not a peel chain543 pass544545 path.append({546 "from": current,547 "to": next_addr,548 "value": val,549 "hash": best[2].get("hash", ""),550 })551552 if next_addr in visited:553 break554 current = next_addr555556 if len(path) >= min_hops:557 chains.append({558 "start": src,559 "end": current,560 "hops": len(path),561 "total_volume": sum(h["value"] for h in path),562 "path": path,563 })564565 return chains566567568def detect_peel_chain_heuristic_simple(address: str, txs: list[dict],569 threshold_ratio: float = 0.8) -> list[dict]:570 """Detect peel chains using a simplified heuristic on raw transaction data.571572 A peel chain address sends most of its incoming value to a single output,573 suggesting gradual fund distribution. This works on individual address analysis574 without needing a full graph.575 """576 outgoing = {}577 for tx in txs:578 frm = tx.get("from", "").lower()579 to = tx.get("to", "").lower()580 val = int(tx.get("value", 0))581 if frm == address:582 outgoing[to] = outgoing.get(to, 0) + val583584 if not outgoing:585 return []586587 total_out = sum(outgoing.values())588 chains = []589 for dst, val in sorted(outgoing.items(), key=lambda x: -x[1]):590 ratio = val / total_out if total_out > 0 else 0591 if ratio >= threshold_ratio:592 chains.append({593 "from": address,594 "to": dst,595 "value": val,596 "ratio": round(ratio, 4),597 "pattern": "peel_chain_hop",598 })599 return chains600```601602## Consolidation Pattern Detector603604Consolidation is the opposite of a peel chain — multiple addresses send funds to a single address. This is typical before an exchange deposit or when a hacker collects funds spread across many wallets.605606```python607def detect_consolidation(G: nx.DiGraph, min_sources: int = 3,608 time_window_hours: int = 24) -> list[dict]:609 """Detect consolidation patterns in the transaction graph.610611 A consolidation is a node with N incoming edges from distinct addresses612 within a time window. This is a classic exchange deposit / fund collection pattern.613 """614 consolidations = []615 for node in G.nodes():616 in_edges = list(G.in_edges(node, data=True))617 if len(in_edges) < min_sources:618 continue619620 unique_sources = set(e[0] for e in in_edges)621 if len(unique_sources) < min_sources:622 continue623624 # Check time window625 timestamps = [e[2].get("timestamp", 0) for e in in_edges]626 timestamps = [t for t in timestamps if t > 0]627 if timestamps:628 span_hours = (max(timestamps) - min(timestamps)) / 3600629 if span_hours > time_window_hours:630 continue631632 total_value = sum(e[2].get("value", 0) for e in in_edges)633 consolidations.append({634 "sink": node,635 "sources": list(unique_sources),636 "num_sources": len(unique_sources),637 "total_value": total_value,638 "time_window_hours": round(span_hours, 2) if timestamps else 0,639 "tx_hashes": [e[2].get("hash", "") for e in in_edges],640 })641642 return sorted(consolidations, key=lambda c: -c["num_sources"])643644645def detect_consolidation_simple(txs: list[dict], min_sources: int = 5) -> list[dict]:646 """Detect consolidation by checking which addresses receive from many distinct senders.647648 Works on raw transaction data without a full graph.649 """650 from collections import Counter651 receivers = Counter()652 receiver_txs = {}653 for tx in txs:654 to = tx.get("to", "").lower()655 frm = tx.get("from", "").lower()656 if to and frm:657 receivers[to] += 1658 if to not in receiver_txs:659 receiver_txs[to] = []660 receiver_txs[to].append(tx)661662 consolidations = []663 for addr, count in receivers.most_common():664 if count >= min_sources:665 total_val = sum(int(tx.get("value", 0)) for tx in receiver_txs[addr])666 consolidations.append({667 "address": addr,668 "incoming_count": count,669 "total_value": total_val,670 "source_addresses": list(set(671 tx.get("from", "").lower() for tx in receiver_txs[addr]672 )),673 })674 return consolidations675```676677## Mixer Identification678679### Known Mixer/Sanitizer Contract Addresses680681| Service | Chain | Address | Type | Notes |682|---|---|---|---|---|683| Tornado Cash | Ethereum | `0x12d66f87a04a9e220743712ce6d9bb1b5616b8fc` | ETH mixer | 0.1 ETH pool |684| Tornado Cash | Ethereum | `0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936` | ETH mixer | 1 ETH pool |685| Tornado Cash | Ethereum | `0x910cbd523d972eb0a6f4cae4618ad62622b39dbf` | ETH mixer | 10 ETH pool |686| Tornado Cash | Ethereum | `0xa160cdab2250da5b3f80029b6b82e1d5d0c30efb` | ETH mixer | 100 ETH pool |687| Tornado Cash | BSC | `0x1e34a77868e19a6647b1f2f47b51ed72dede95dd` | BNB mixer | 100 BNB pool |688| Tornado Cash | Polygon | `0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936` | MATIC mixer | 1000 MATIC pool |689| Sinbad | Ethereum | `0x1e31cb9b6b69a7df3225220a0ef1f0a76586d5a3` | ETH mixer | |690| Sinbad | Ethereum | `0x8589427373d6d84e98730d7795d8f6f8731fda16` | ETH mixer | |691| Wasabi Wallet | Bitcoin | `bc1q…` (varies) | BTC CoinJoin | Uses PayNym, no fixed address |692| Samourai Whirlpool | Bitcoin | (Coordinator) | BTC CoinJoin | No fixed deposit address |693| ChainFlip | Ethereum | `0x60fB0B27447480E3304bB7b2660e9C081D3775fc` | Cross-chain mixer | |694| eXch | Ethereum | (varies) | Swap-based mixer | Swaps and splits |695| FixedFloat | Multi | (varies) | Swap-based mixer | No-KYC exchange used for obfuscation |696697### Mixer Deposit Detection Heuristics698699```python700# Known mixer contract addresses (Ethereum mainnet)701MIXER_ADDRESSES = {702 # Tornado Cash deposit addresses (by pool size)703 "0x12d66f87a04a9e220743712ce6d9bb1b5616b8fc": "tornado_0.1_eth",704 "0x47ce0c6ed5b0ce3d3a51fdb1c52dc66a7c3c2936": "tornado_1_eth",705 "0x910cbd523d972eb0a6f4cae4618ad62622b39dbf": "tornado_10_eth",706 "0xa160cdab2250da5b3f80029b6b82e1d5d0c30efb": "tornado_100_eth",707 # Sinbad708 "0x1e31cb9b6b69a7df3225220a0ef1f0a76586d5a3": "sinbad_1",709 "0x8589427373d6d84e98730d7795d8f6f8731fda16": "sinbad_2",710}711712713def tag_mixer_interactions(df: pd.DataFrame) -> pd.DataFrame:714 """Tag transactions involving known mixer addresses."""715 df_lower = df.copy()716 df_lower["to"] = df_lower["to"].str.lower()717 df_lower["from"] = df_lower["from"].str.lower()718 df_lower["mixer"] = "unknown"719 for addr, name in MIXER_ADDRESSES.items():720 mask = (df_lower["to"] == addr) | (df_lower["from"] == addr)721 df_lower.loc[mask, "mixer"] = name722 return df_lower723724725def detect_mixer_deposit_by_amount(address: str, txs: list[dict],726 known_amounts: list[float] = None) -> bool:727 """Detect potential mixer deposits by checking for exact-amount patterns.728729 Mixers use fixed deposit amounts (e.g., Tornado Cash pools).730 If an address sends an exact pool amount to a contract, it's likely a mixer deposit.731 """732 if known_amounts is None:733 known_amounts = [0.1, 1.0, 10.0, 100.0] # Tornado Cash standard pool amounts734735 for tx in txs:736 frm = tx.get("from", "").lower()737 val_eth = int(tx.get("value", 0)) / 1e18738 if frm == address.lower() and val_eth in known_amounts:739 # Verify the recipient has contract code (mixer contract, not EOA)740 return True741 return False742743744def detect_mixer_timing_anomaly(txs: list[dict], time_window_minutes: int = 30) -> list[dict]:745 """Detect mixer deposit patterns by timing.746747 Mixer deposits often cluster in tight time windows.748 Multiple deposits to different addresses from the same source within a short window749 is a strong mixer indicator.750 """751 from collections import defaultdict752 windows = defaultdict(list)753754 for tx in txs:755 ts = int(tx.get("timeStamp", 0))756 to = tx.get("to", "").lower()757 if ts:758 bucket_key = ts // (time_window_minutes * 60) # bucket by time window759 windows[bucket_key].append(tx)760761 suspicious = []762 for bucket, group in windows.items():763 unique_recipients = set(t.get("to", "").lower() for t in group)764 if len(unique_recipients) >= 3:765 total_val = sum(int(t.get("value", 0)) for t in group) / 1e18766 suspicious.append({767 "time_bucket": bucket,768 "num_txs": len(group),769 "unique_recipients": len(unique_recipients),770 "total_value_eth": total_val,771 "txs": [t.get("hash", "") for t in group[:10]],772 })773774 return suspicious775```776777## Cross-Chain Bridge Tracing778779Bridges are the most common obfuscation technique post-hack. The attacker deposits on Chain A and withdraws on Chain B, often swapping the asset type.780781### Known Bridge Contract Addresses782783| Bridge | Chain | Contract Address | Event Signature |784|---|---|---|---|785| LayerZero Endpoint | Ethereum | `0x66A71Dcef29A0fFBDBE3c6a460a3B5BC225Cd675` | `MessagePayload` |786| Stargate Router | Ethereum | `0x8731d54E9D02c286767d56ac03e8037C07e01e98` | `Swap` |787| Stargate Router | Arbitrum | `0x53Bf833A5d6c4ddA888F69c22C88C9f356a41614` | `Swap` |788| Wormhole Core | Ethereum | `0x98f3c9e6E3fAce36bAAd05FE09d375Ef1464288B` | `LogMessagePublished` |789| Wormhole Token Bridge | Ethereum | `0x3ee18B2214AFF97000D974cf647E7C347E8fa585` | `TransferRedeemed` |790| Across | Ethereum | `0x5c7BCd6E7De5423a257D81B442095A1a6ced35C5` | `FundsDeposited` |791| Across | Arbitrum | `0x3bB4445D30AC020a84c1b5A8A2C6248ebC9779D0` | `FundsDeposited` |792| Synapse | Ethereum | `0x2796317b0fF8538F253012862c06787Adfb8c3aC` | `TokenDeposit` |793| Synapse | Arbitrum | `0x9D33eeE1540BdA15C2021C22E14dfdB41c58485b` | `TokenDeposit` |794| Hop | Ethereum | `0x3666f603Cc164936C1b87e207F36BEBa4AC5f18a` | `TransferSent` |795| Hop | Polygon | `0x3666f603Cc164936C1b87e207F36BEBa4AC5f18a` | `TransferSent` |796| AnySwap (Multichain) | Ethereum | `0x6b7a87899490EcE95443e979cA9485CBE7E71522` | `AnySwapOut` |797| Celer cBridge | Ethereum | `0x1619DE6B6B20eD217a58d00f37B9d47C7663feca` | `Send` |798799### Bridge Detection Code800801```python802BRIDGE_CONTRACTS = {803 "layerzero_endpoint": {804 "ethereum": ["0x66a71dcef29a0ffbdbe3c6a460a3b5bc225cd675"],805 "arbitrum": ["0x3c2269811836af69497e5f486a85d7316753cf02"],806 "polygon": ["0x3c2269811836af69497e5f486a85d7316753cf02"],807 },808 "stargate_router": {809 "ethereum": ["0x8731d54e9d02c286767d56ac03e8037c07e01e98"],810 "arbitrum": ["0x53bf833a5d6c4dda888f69c22c88c9f356a41614"],811 "polygon": ["0x53bf833a5d6c4dda888f69c22c88c9f356a41614"],812 },813 "across": {814 "ethereum": ["0x5c7bcd6e7de5423a257d81b442095a1a6ced35c5"],815 "arbitrum": ["0x3bb4445d30ac020a84c1b5a8a2c6248ebc9779d0"],816 },817 "synapse": {818 "ethereum": ["0x2796317b0ff8538f253012862c06787adfb8c3ac"],819 "arbitrum": ["0x9d33eee1540bda15c2021c22e14dfdb41c58485b"],820 },821 "wormhole": {822 "ethereum": ["0x98f3c9e6e3face36baad05fe09d375ef1464288b"],823 },824 "hop": {825 "ethereum": ["0x3666f603cc164936c1b87e207f36beba4ac5f18a"],826 "polygon": ["0x3666f603cc164936c1b87e207f36beba4ac5f18a"],827 },828 "celer": {829 "ethereum": ["0x1619de6b6b20ed217a58d00f37b9d47c7663feca"],830 },831}832833# Flatten bridge addresses to a single set for fast lookup834ALL_BRIDGE_ADDRESSES = set()835for name, chains in BRIDGE_CONTRACTS.items():836 for chain_addrs in chains.values():837 ALL_BRIDGE_ADDRESSES.update(chain_addrs)838839840def tag_bridge_interactions(df: pd.DataFrame) -> pd.DataFrame:841 """Tag transactions involving known bridge contracts."""842 df_lower = df.copy()843 for col in ["to", "from"]:844 df_lower[col] = df_lower[col].str.lower()845846 def lookup(addr):847 addr = addr.lower()848 for name, chains in BRIDGE_CONTRACTS.items():849 for chain_addrs in chains.values():850 if addr in chain_addrs:851 return name852 return ""853854 df_lower["bridge"] = df_lower["to"].apply(lookup)855 # Also check 'from' field for bridge interactions856 mask_from = df_lower["bridge"] == ""857 df_lower.loc[mask_from, "bridge"] = df_lower.loc[mask_from, "from"].apply(lookup)858 return df_lower859860861def detect_bridge_transfer(tx: dict, receipt_logs: list[dict]) -> dict:862 """Detect bridge transfer from a transaction's event logs.863864 Returns destination chain info if a bridge event is found.865 """866 for log in receipt_logs:867 addr = log.get("address", "").lower()868 topics = log.get("topics", [])869870 # Stargate Swap event: topics[0] = Swap(uint16,uint16,address,address,uint256,uint256)871 if addr in ALL_BRIDGE_ADDRESSES and len(topics) >= 3:872 return {873 "bridge_detected": True,874 "contract": addr,875 "tx_hash": tx.get("hash", ""),876 "topics": topics,877 "data": log.get("data", ""),878 "note": "Bridge interaction detected — check destination chain in event data",879 }880881 return {"bridge_detected": False}882883884def extract_bridge_destination(tx_hash: str, web3_provider, bridge_address: str) -> int:885 """Extract destination chain ID from a Stargate bridge event.886887 Stargate emits Swap(uint16 chainIdFrom, uint16 chainIdTo, ...).888 The chainIdTo is typically topic[2] in the Swap event.889 """890 receipt = web3_provider.eth.get_transaction_receipt(tx_hash)891 for log in receipt.logs:892 if log.address.lower() == bridge_address.lower():893 topics = log.topics894 if len(topics) >= 3:895 dest_chain_id = int.from_bytes(topics[2], "big")896 return dest_chain_id897 return 0898```899900## Wallet Clustering Implementation901902### CoJoin / Common-Input Clustering (UTXO Chains)903904Bitcoin-like UTXO chains enable a powerful clustering heuristic: if two addresses appear as inputs in the same transaction, they are controlled by the same entity (assuming multi-signature or CoinJoin is not involved). This is called CoJoin or Common-Input-Ownership Heuristic.905906```python907def cluster_by_common_input(txs_utxo: list[dict]) -> dict[str, set[str]]:908 """Cluster Bitcoin addresses by common-input ownership heuristic.909910 If addresses A and B appear as inputs in the same transaction,911 they are likely controlled by the same entity. Returns a dict912 mapping cluster_id -> set of addresses.913 """914 address_to_tx = {}915 tx_to_addresses = {}916917 for tx in txs_utxo:918 txid = tx.get("txid", "")919 input_addresses = set()920 for vin in tx.get("vin", []):921 addr = vin.get("prevout", {}).get("scriptpubkey_address", "")922 if addr:923 input_addresses.add(addr)924 if len(input_addresses) >= 2:925 tx_to_addresses[txid] = input_addresses926 for addr in input_addresses:927 if addr not in address_to_tx:928 address_to_tx[addr] = []929 address_to_tx[addr].append(txid)930931 # Union-Find to merge clusters932 parent = {}933934 def find(x):935 while parent[x] != x:936 parent[x] = parent[parent[x]]937 x = parent[x]938 return x939940 def union(a, b):941 ra, rb = find(a), find(b)942 if ra != rb:943 parent[ra] = rb944945 all_addresses = set()946 for addresses in tx_to_addresses.values():947 addrs = list(addresses)948 for addr in addrs:949 if addr not in parent:950 parent[addr] = addr951 all_addresses.add(addr)952 for i in range(1, len(addrs)):953 union(addrs[0], addrs[i])954955 # Build clusters956 clusters = {}957 for addr in all_addresses:958 root = find(addr)959 if root not in clusters:960 clusters[root] = set()961 clusters[root].add(addr)962963 return clusters964965966def cluster_by_deposit_address(txs: list[dict], exchange_pattern: str = "binance") -> list[dict]:967 """Identify exchange deposit addresses by known patterns.968969 Many exchanges use deterministic deposit addresses.970 This heuristic clusters addresses that receive from many senders971 as potential exchange deposit addresses.972 """973 from collections import Counter, defaultdict974 deposits_to = Counter()975 depositors = defaultdict(set)976977 for tx in txs:978 to = tx.get("to", "").lower()979 frm = tx.get("from", "").lower()980 if to and frm:981 deposits_to[to] += 1982 depositors[to].add(frm)983984 clusters = []985 for addr, count in deposits_to.most_common(50):986 if count >= 10:987 clusters.append({988 "deposit_address": addr,989 "incoming_count": count,990 "unique_depositors": len(depositors[addr]),991 "likely_entity": exchange_pattern if count > 50 else "unknown",992 })993994 return clusters995```996997### EVM Address Reuse Clustering998999Even on account-based chains, addresses can be clustered by behavioral patterns:10001001```python1002def cluster_by_behavior(df: pd.DataFrame, min_interactions: int = 5) -> dict[str, list[str]]:1003 """Cluster EVM addresses by behavioral similarity.10041005 If two addresses interact with the same set of contracts/protocols,1006 they may be controlled by the same entity.1007 """1008 from collections import defaultdict1009 addr_contracts = defaultdict(set)10101011 for _, row in df.iterrows():1012 frm = str(row.get("from", "")).lower()1013 to = str(row.get("to", "")).lower()1014 if frm and to:1015 addr_contracts[frm].add(to)1016 if to:1017 addr_contracts[to] # ensure key exists10181019 # Jaccard similarity between address contract sets1020 addrs = list(addr_contracts.keys())1021 clusters = defaultdict(list)1022 assigned = set()10231024 for i, a1 in enumerate(addrs):1025 if a1 in assigned:1026 continue1027 set1 = addr_contracts[a1]1028 if len(set1) < min_interactions:1029 continue1030 cluster = [a1]1031 assigned.add(a1)1032 for a2 in addrs[i + 1:]:1033 if a2 in assigned:1034 continue1035 set2 = addr_contracts[a2]1036 if len(set2) < min_interactions:1037 continue1038 intersection = len(set1 & set2)1039 union = len(set1 | set2)1040 if union > 0 and intersection / union >= 0.7:1041 cluster.append(a2)1042 assigned.add(a2)1043 if len(cluster) >= 2:1044 clusters[f"behavioral_cluster_{len(clusters)}"] = cluster10451046 return clusters1047```10481049## Sankey / Flow Diagram Visualization10501051Generate an interactive HTML flow visualization using Plotly. This produces a browser-ready trace report.10521053```python1054import plotly.graph_objects as go1055from typing import Optional10561057def build_sankey_diagram(G: nx.DiGraph, title: str = "Transaction Flow",1058 max_nodes: int = 50, min_value: float = 0.01,1059 output_path: Optional[str] = "tx_flow.html") -> Optional[str]:1060 """Generate an interactive Sankey diagram from the transaction graph.10611062 Nodes are addresses, link thickness represents transaction value.1063 Only the top-max_nodes by volume are included for readability.1064 """1065 # Filter by value and take top nodes1066 H = filter_by_value(G, min_value)10671068 # Compute total flow per node and keep top1069 node_volume = {}1070 for u, v, d in H.edges(data=True):1071 val = d.get("value", 0)1072 node_volume[u] = node_volume.get(u, 0) + val1073 node_volume[v] = node_volume.get(v, 0) + val10741075 top_nodes = set(sorted(node_volume, key=node_volume.get, reverse=True)[:max_nodes])1076 H = H.subgraph(top_nodes)10771078 # Map addresses to labels1079 nodes = list(H.nodes())1080 node_map = {n: i for i, n in enumerate(nodes)}1081 labels = [f"{n[:6]}…{n[-4:]}" for n in nodes]10821083 # Build Sankey links1084 sources, targets, values, hover_texts = [], [], [], []1085 for u, v, d in H.edges(data=True):1086 sources.append(node_map[u])1087 targets.append(node_map[v])1088 val = d.get("value", 0)1089 values.append(max(val * 100, 1)) # Scale for visibility1090 h = d.get("hash", "")[:10]1091 ts = d.get("timestamp", 0)1092 token = d.get("token", "ETH")1093 hover_texts.append(1094 f"From: {u[:6]}…{u[-4:]}<br>"1095 f"To: {v[:6]}…{v[-4:]}<br>"1096 f"Value: {val:.4f} {token}<br>"1097 f"Tx: {h}…<br>"1098 f"Timestamp: {ts}"1099 )11001101 fig = go.Figure(data=[go.Sankey(1102 node=dict(1103 pad=15,1104 thickness=20,1105 line=dict(color="black", width=0.5),1106 label=labels,1107 color="blue",1108 ),1109 link=dict(1110 source=sources,1111 target=targets,1112 value=values,1113 hovertext=hover_texts,1114 hoverinfo="text",1115 )1116 )])11171118 fig.update_layout(title=title, font_size=12, height=800)11191120 if output_path:1121 fig.write_html(output_path)1122 return output_path112311241125def build_consolidation_sankey(clusters: list[dict], output_path: str = "consolidation.html") -> str:1126 """Generate a Sankey diagram focused on consolidation patterns.11271128 Shows multiple source addresses flowing into each sink.1129 """1130 sources, targets, values, hover_texts = [], [], [], []1131 labels = []11321133 idx = 01134 for cluster in clusters[:20]: # Limit to top 20 clusters1135 sink = cluster.get("sink", cluster.get("address", ""))1136 if sink not in labels:1137 labels.append(sink)1138 sink_idx = len(labels) - 11139 else:1140 sink_idx = labels.index(sink)11411142 for src in cluster.get("sources", [])[:10]: # Limit to 10 sources per sink1143 if src not in labels:1144 labels.append(src)1145 src_idx = len(labels) - 11146 else:1147 src_idx = labels.index(src)1148 sources.append(src_idx)1149 targets.append(sink_idx)1150 values.append(5) # Uniform thickness1151 hover_texts.append(f"{src[:6]}…→ {sink[:6]}…")11521153 fig = go.Figure(data=[go.Sankey(1154 node=dict(pad=15, thickness=20, line=dict(color="black", width=0.5),1155 label=[f"{l[:6]}…{l[-4:]}" for l in labels]),1156 link=dict(source=sources, target=targets, value=values,1157 hovertext=hover_texts, hoverinfo="text"),1158 )])11591160 fig.update_layout(title="Consolidation Patterns", height=600)1161 fig.write_html(output_path)1162 return output_path1163```11641165## Case Study: Tracing a Simulated Bridge Hack Fund Flow11661167This scenario demonstrates a realistic theft investigation. Adapt the addresses and step sequence to your actual case.11681169**Scenario:** The XYZ Bridge was exploited for 5,000 ETH on Ethereum mainnet. The attacker address is `0xAttackerXYZ...`.11701171```python1172# === PHASE 1: Initial Theft ===1173# The attacker drained 5,000 ETH from the bridge contract on Ethereum.1174# Target address: 0xAttackerXYZ (replace with actual address)11751176api_key = "YOUR_ETHERSCAN_API_KEY"11771178# Step A: Collect all transaction data from the attacker address1179attacker_txs = collect_all_txs("0xAttackerXYZ...", api_key, chain_id=1)1180df_attacker = normalize_txs(attacker_txs["normal"])1181df_attacker_internal = normalize_txs(attacker_txs["internal"])1182df_attacker_erc20 = normalize_txs(attacker_txs["erc20"], tx_type="erc20")11831184# Combine all transactions1185df_all = pd.concat([df_attacker, df_attacker_internal, df_attacker_erc20],1186 ignore_index=True)1187print(f"Collected {len(df_all)} transactions for attacker address")11881189# Step B: Build the transaction graph1190G = build_tx_graph(df_all)1191summary = graph_summary(G)1192print(f"Graph: {summary['nodes']} nodes, {summary['edges']} edges")11931194# Step C: Find the first outgoing transaction (likely proceeds movement)1195first_out = df_all[df_all["from"] == "0xattackerxyz..."] \1196 .sort_values("timestamp").head(5)1197print("First outgoing transactions from attacker:")1198print(first_out[["hash", "to", "value_eth", "timestamp"]].to_string())11991200# === PHASE 2: Follow the Money ===1201# The attacker split the funds across multiple addresses (peel chain).1202peel_chains = detect_peel_chains(G, min_hops=3)1203print(f"Detected {len(peel_chains)} potential peel chains")12041205for chain in peel_chains:1206 print(f" Peel chain: {chain['start']} → {chain['end']} "1207 f"({chain['hops']} hops, {chain['total_volume']:.2f} ETH)")12081209# === PHASE 3: Identify Mixer Deposits ===1210# Check if any trace deposits to Tornado Cash1211df_tagged = tag_mixer_interactions(df_all)1212mixer_txs = df_tagged[df_tagged["mixer"] != "unknown"]1213print(f"\nMixer interactions: {len(mixer_txs)}")1214for _, tx in mixer_txs.iterrows():1215 print(f" {tx['hash']}: → {tx['to']} ({tx['mixer']}) "1216 f"value={tx['value_eth']:.4f} ETH")12171218# === PHASE 4: Bridge to Another Chain ===1219# Check if the attacker used a bridge1220df_bridge = tag_bridge_interactions(df_all)1221bridge_txs = df_bridge[df_bridge["bridge"] != ""]1222print(f"\nBridge interactions: {len(bridge_txs)}")1223for _, tx in bridge_txs.iterrows():1224 print(f" {tx['hash']}: → {tx['to']} (bridge={tx['bridge']}) "1225 f"value={tx['value_eth']:.4f} ETH")12261227# === PHASE 5: Detect Consolidation ===1228# Eventually, funds consolidate before an exchange deposit1229consolidations = detect_consolidation(G, min_sources=3)1230print(f"\nConsolidation patterns: {len(consolidations)}")1231for c in consolidations[:5]:1232 print(f" Sink: {c['sink'][:10]}... "1233 f"Sources: {c['num_sources']} "1234 f"Value: {c['total_value']:.2f} ETH")12351236# === PHASE 6: Generate Sankey Visualization ===1237build_sankey_diagram(G, title="Bridge Hack Fund Flow",1238 max_nodes=40, min_value=0.1,1239 output_path="bridge_hack_trace.html")1240print("\nFlow diagram generated: bridge_hack_trace.html")12411242# === PHASE 7: Export Graph for Analysis ===1243export_dot(G, "bridge_hack_trace.dot")1244export_graphml(G, "bridge_hack_trace.graphml")1245print("Graph exported to DOT and GraphML formats")1246```12471248**Expected trace result for this scenario:**12491. `0xAttackerXYZ` → receives 5,000 ETH from bridge drain12502. Splits into 5 x 1,000 ETH transfers to intermediate wallets (peel chain hop 1)12513. Each intermediate sends ∼997 ETH to Tornado Cash 1,000 ETH pool (mixer deposit)12524. Small amount (∼3 ETH) moves to another peel chain layer12535. After mixing: funds emerge on Arbitrum via LayerZero bridge12546. Consolidate to one address on Arbitrum12557. Deposit to Binance (consolidation detected: 15+ source addresses → 1 sink)12568. Trace ends at CEX deposit — submit subpoena request12571258## Money Section12591260Turn on-chain forensic skills into multiple revenue streams:12611262### Service Tiers for Trace Reports12631264| Tier | Scope | Deliverables | Price (USD) |1265|---|---|---|---|1266| Basic | Single address, single chain, < 50 transactions | Transaction list + simple flow diagram + entity tags | $200 – $500 |1267| Standard | Multi-address, single chain, up to 1,000 transactions | Full trace report with cluster analysis, Sankey diagram, DOT/GraphML exports | $1,000 – $3,000 |1268| Premium | Cross-chain, multi-address, unlimited transactions | Complete forensic report with all algorithms (peel chain, consolidation, mixer, bridge detection), interactive flow HTML, raw data exports, expert affidavit | $5,000 – $15,000 |1269| Enterprise | Ongoing monitoring, wallet tracking, custom alerting | Dashboard with real-time graph updates, API access, weekly briefings | $10,000 – $50,000/month |12701271### Law Enforcement / Legal Consulting Rates12721273| Service | Rate |1274|---|---|1275| Expert witness testimony (deposition) | $500 – $1,000/hour |1276| Expert witness testimony (trial) | $1,000 – $3,000/hour |1277| Forensic report for litigation | $5,000 – $25,000 flat |1278| Case consultation (hourly) | $300 – $500/hour |12791280### Bounty Hunting Revenue12811282| Platform | Typical Payout | Notes |1283|---|---|---|1284| Arkham Intelligence | $500 – $50,000+ per bounty | Requires verified wallet attribution |1285| Lazarus Bounty | Up to 10% of recoverable funds | Focused on North Korean hacker wallets |1286| Immunefi (trace required) | Part of larger bug bounty | Trace + smart contract audit combined |1287| HackerOne/ Bugcrowd | Variable | Some programs pay for fund flow analysis |1288| Private crypto investigation firms | Contract rates | Chainalysis, TRM Labs, CipherTrace partners |12891290### Business Models129112921. **Per-report consulting**: Charge per trace report for incident victims. Most crypto thefts >$100K have victims willing to pay $2K-$10K for a professional trace.129312942. **Subscription monitoring**: Recurring fee for wallet/address monitoring with alerts on fund movement. Target: DeFi protocols, VCs, high-net-worth individuals.129512963. **Bounty hunting**: Register on Arkham, Lazarus Bounty, and Immunefi. Spend 20-40 hours per lead. Hit rate varies but single bounties can exceed $50K.129712984. **Expert witness**: Build relationships with law firms handling crypto fraud and bankruptcy cases. Bill at $500-$3K/hour.129913005. **Training/education**: Sell courses on blockchain forensics. Pre-recorded course $500-$2K per student. Corporate training $5K-$20K per session.130113026. **Tool licensing**: Build a SaaS tool wrapping these algorithms. $50-$500/month per user.13031304## Expected Output13051306A forensic trace report containing:1307- Transaction flow graph (interactive HTML Sankey diagram + DOT/GraphML format)1308- Wallet cluster table with entity attributions (exchange, mixer, bridge, DeFi protocol, EOA)1309- Timeline of fund movements with USD values at time of each transaction1310- List of endpoints where funds cannot be further traced (mixers, exchange deposits, or bridges to unmonitored chains)1311- Detected patterns: peel chains, consolidations, mixer deposits, bridge interactions1312- Confidence scores for each hop and attribution1313- Raw data exports (CSV, GraphML) for independent verification1314- For legal use: expert affidavit summarizing methodology and findings13151316## Red Flags13171318- Attempting to deanonymize addresses without proper authorization or legal basis1319- Drawing conclusions from incomplete data (missing internal transactions or token transfers)1320- Over-relying on a single block explorer that may have incomplete indexing1321- Assuming a wallet belongs to an entity without cross-referencing multiple data sources1322- Treating change addresses (UTXO) as separate entities from the spending wallet1323- Ignoring transaction fees in value calculations — they affect net amounts in peel chains1324- Conflating internal transactions (contract CALLs) with external ETH transfers1325- Assuming a CoinJoin transaction implies address clustering — it's designed to break this heuristic1326- Trusting a single API response without retrying on rate-limit errors (429 responses)1327- Failing to account for wrapped assets (wETH, wBTC) as equivalent to the underlying asset13281329## Process133013311. **Data Collection** — Gather all transaction data for target addresses from block explorers and RPC nodes. Use pagination for high-volume addresses. Collect normal, internal, and token transfers for EVM chains; UTXO inputs/outputs for Bitcoin.133213332. **Flow Mapping** — Build a directed transaction graph using NetworkX. Apply filtering thresholds to remove dust transactions. Compute graph statistics (source/sink nodes, centrality, volume hubs).133413353. **Pattern Detection** — Run peel chain detection, consolidation detection, mixer identification, and bridge extraction algorithms. Each pattern provides labeled subgraphs for the investigator.133613374. **Entity Attribution** — Cross-reference addresses against known entity databases (mixer addresses table, bridge contracts table, known exchange wallets). Tag each node with its likely entity type.133813395. **Clustering** — Apply CoJoin clustering for UTXO addresses, behavioral similarity clustering for EVM addresses. Merge clusters into entity-level groups.134013416. **Cross-Chain Tracking** — Follow funds through bridges by scanning interaction with known bridge contracts. Extract destination chain IDs from bridge event logs. Re-query the destination chain with the output address.134213437. **Visualization** — Generate Sankey flow diagrams and DOT/GraphML exports. Produce both summary view (all hops) and filtered view (significant transfers only).134413458. **Reporting** — Produce structured trace report with flow diagrams, confidence scores, endpoint identification, and raw data exports.13461347## Verification13481349- Every trace hop verified against the source block explorer (not just API data)1350- Transaction hashes cross-referenced on at least two independent explorers where possible1351- Entity attributions confirmed by multiple data points, not single-source assumptions1352- Graph visualization matches the raw transaction data (no skipped or double-counted hops)1353- Internal transaction values summed and cross-checked against normal transaction balances1354- Bridge event logs parsed and verified for correct destination chain ID1355- NetworkX graph edge count matches the number of filtered transactions1356- USD value conversions use historical price data (CoinGecko or similar) at the block timestamp1357- Sankey diagram total inflow matches total outflow (conservation of value)1358- Report includes raw data exports so findings can be independently verified135913601361## RPC & API Endpoint Management13621363### Multi-Provider Fallback Strategy13641365```python1366import os, time, requests13671368BLOCK_EXPLORERS = {1369 "ethereum": [{"name": "etherscan", "base": "https://api.etherscan.io/api", "key_env": "ETHERSCAN_API_KEY"},1370 {"name": "etherscan-2","base": "https://api.etherscan.io/api", "key_env": "ETHERSCAN_API_KEY_2"}],1371 "bsc": [{"name": "bscscan", "base": "https://api.bscscan.com/api", "key_env": "BSCSCAN_API_KEY"}],1372 "polygon": [{"name": "polygonscan","base": "https://api.polygonscan.com/api", "key_env": "POLYGONSCAN_API_KEY"}],1373}13741375def robust_explorer_call(chain: str, params: dict, retries: int = 3) -> dict | None:1376 """Call block explorer API with per-chain fallback and rate-limit backoff."""1377 providers = BLOCK_EXPLORERS.get(chain, [])1378 for provider in providers:1379 api_key = os.environ.get(provider["key_env"])1380 if not api_key:1381 continue1382 params["apikey"] = api_key1383 for attempt in range(retries):1384 try:1385 resp = requests.get(provider["base"], params=params, timeout=30)1386 data = resp.json()1387 if data.get("status") == "1":1388 return data1389 if "rate limit" in str(data).lower():1390 time.sleep(2 ** attempt) # exponential backoff1391 continue1392 return data # non-rate-limit error, return anyway1393 except (requests.ConnectionError, requests.Timeout):1394 time.sleep(2 ** attempt)1395 return None1396```13971398### Key Hygiene13991400- Store keys in `.env` with per-chain names (`ETHERSCAN_API_KEY`, `BSCSCAN_API_KEY`).1401- Add a second Etherscan key (`ETHERSCAN_API_KEY_2`) for high-volume traces — the rate limit is per-key.1402- **No key?** Use the Covalent free tier (1 key, 30+ chains, 5 req/s) or the block explorer web UI (curl-able, no key for individual lookups).14031404## When the Trace Goes Cold14051406### Common Dead Ends and Real Resolutions14071408| On-Chain Signal | Interpretation | Action |1409|---|---|---|1410| Funds hit a CEX deposit address | Last on-chain point — exchange owns the address | Document tx hash + timestamp. This is a subpoena/subpoena-ready endpoint. |1411| Funds enter a privacy mixer (Tornado Cash, RAILGUN) | Intentional obfuscation | Record deposit amount + block. Scan ±200 blocks for matching withdrawal amounts. |1412| Transaction is a `create2` deployment | Counterfactual contract — may not exist yet | Compute predicted address from deployer + salt. Monitor for creation tx. |1413| Target address has zero outgoing txs for 72h+ | Sleeping address or intentional hold | Set up a cron job (`crontab -e`, check every 6h via `txlist`) to detect future movement. |1414| Funds bridged to another chain | Cross-chain escape | Parse the `Transfer`/`Swap` event on the source bridge contract. Extract `destinationChainId` and `receiver`. Re-query on the target chain. |1415| Contract self-destructed | Intentional state destruction | Investigate deployer address. The `SELFDESTRUCT` opcode sends remaining ETH to a target — follow that. |1416| UTXO chain — single input, single output | Normal spend | Check for address reuse patterns; if none, this branch is cold. |14171418### The 10/3 Rule14191420If you have made 10 API lookups on a single address and found 0 new leads in the last 3, **stop**. Archive the investigation with:14211422```python1423def archive_cold_trail(address: str, chain: str, last_tx: str, notes: str):1424 """Log a cold trail for periodic re-check."""1425 record = {"address": address, "chain": chain, "last_tx_hash": last_tx,1426 "archived_at": time.time(), "notes": notes, "next_check": time.time() + 604800}1427 # Append to cold_trails.jsonl — re-check weekly1428 with open("cold_trails.jsonl", "a") as f:1429 f.write(json.dumps(record) + "\n")1430```14311432**Do not delete cold trails.** The trace is not dead — it's waiting for the next transaction that hasn't happened. Archive with a weekly re-check window and move to higher-signal addresses.1433## Practices from Top Investigators14341435### The ZachXBT Methodology14361437ZachXBT is the most recognized on-chain investigator, having traced over $243M in stolen crypto1438funds. His methodology combines on-chain analysis with extensive cross-platform OSINT, turning1439blockchain pseudonymity into identity evidence. This section codifies his proven techniques.14401441### The 12-Tool Arsenal14421443| Tool | Purpose | When to Use |1444|---|---|---|1445| **Etherscan / Solscan** | Primary chain explorer (tx list, internal txs, token transfers) | Every trace — start here |1446| **Arkham Intelligence** | Visual fund flow graphs, entity tags, exchange hot wallets | Mid-trace: visualize complex hop chains |1447| **MetaSleuth** | Cross-chain fund flow visualization with one-click explorer links | When traces span 3+ chains |1448| **Cielo** | Real-time wallet monitoring, push alerts on target addresses | After identifying key addresses — set alerts before sleeping |1449| **TRM Labs** | Sanctions screening, risk scoring, entity attribution | Every address before publishing results |1450| **Breadcrumbs** | Bitcoin UTXO clustering, peel chain detection | BTC traces — clusters by co-spend heuristic |1451| **Blockchair** | BTC/ETH privacy analysis, entity tags, mixing detection | When mixers or privacy tools are suspected |1452| **Dune Analytics** | Custom SQL queries on decoded event data | When you need to aggregate thousands of events |1453| **DeBank** | Cross-chain portfolio view — balance history over time | Quick assessment of a wallet's activity pattern |1454| **OKLink** | Multi-chain explorer with cross-chain bridge tracking | Following funds across L1s and L2s |1455| **OMNIA** | Mempool monitoring, pending tx capture | Catching transactions before they confirm |1456| **MetaSuites** | Batch address lookups, legacy labeling data | De-anonymizing old addresses with pre-2020 data |14571458### Funding Chain Tracing (His Signature Method)14591460The core insight: **trace the attacker's funding, not just the stolen funds.** Attackers almost1461always fund their operations from an earlier hack or a tied wallet. Tracing backward from the1462attack transaction to the original source of the ETH used for gas fees often reveals:14631464- The same attacker's previous hacks (same funding source → same person)1465- Exchange deposit patterns that reveal identity1466- Timing links between multiple attacks14671468```python1469def trace_funding_chain(attacker_address: str, chain: str = "ethereum") -> list[dict]:1470 """Trace attacker's funding chain backward from attack tx.14711472 ZachXBT technique: find where the ATTACKER got their gas money.1473 The funding source often ties multiple hacks to the same person.1474 """1475 from etherscan_v2_api import fetch_txlist, fetch_internal_txlist1476 from collections import deque14771478 visited = {attacker_address}1479 queue = deque([attacker_address])1480 funding_chain = []1481 max_depth = 5 # attackers rarely fund more than 5 hops deep14821483 while queue and len(funding_chain) < max_depth:1484 addr = queue.popleft()1485 # Get the FIRST transaction the address ever received (its funding)1486 txs = fetch_txlist(addr, chain, sort="asc", limit=1) or []1487 internal_txs = fetch_internal_txlist(addr, chain, sort="asc", limit=1) or []14881489 earliest = (txs or internal_txs)[0] if (txs or internal_txs) else None1490 if not earliest:1491 funding_chain.append({"address": addr, "funding_source": "unknown", "depth": len(funding_chain)})1492 continue14931494 sender = earliest.get("from", "")1495 funding_chain.append({1496 "address": addr,1497 "funded_by": sender,1498 "value_eth": earliest.get("value_eth", earliest.get("value", 0)),1499 "block": earliest.get("blockNumber"),1500 "tx_hash": earliest.get("hash") or earliest.get("transactionHash"),1501 })15021503 if sender and sender not in visited:1504 visited.add(sender)1505 queue.append(sender)15061507 # Check: do any funding sources overlap with known hacker addresses?1508 # This is the key pattern — same funder = same attacker across exploits1509 return funding_chain1510```15111512### Cross-Platform OSINT Integration15131514ZachXBT never stops at the blockchain. Every address is cross-referenced with:151515161. **Twitter/X** — Deleted tweets, handle changes, engagement patterns15172. **Discord/Telegram** — Invite links from scam websites, group memberships15183. **GitHub** — Repository contributions, commit timestamps matching attack blocks15194. **ENS/Unstoppable Domains** — Metadata that links to real-world identities15205. **Forum posts** (BitcoinTalk, Reddit) — Historical posts with wallet mentions15211522```python1523def cross_platform_lookup(address: str, identity_hints: dict[str, str] = None) -> dict:1524 """Cross-reference an address across OSINT sources.15251526 identity_hints: {"twitter": "handle", "github": "username", "ens": "name.eth"}1527 """1528 results = {"address": address, "platforms": {}}15291530 # 1. ENS reverse lookup1531 try:1532 resp = requests.get(f"https://api.ensideas.com/ens/resolve/{address}", timeout=10)1533 if resp.ok:1534 data = resp.json()1535 results["platforms"]["ens"] = {"name": data.get("ens"), "avatar": data.get("avatar")}1536 except Exception:1537 pass15381539 # 2. Check known exploit databases for this address1540 try:1541 resp = requests.get(1542 "https://raw.githubusercontent.com/The-Blockchain-Repository/Hack-Transactions/main/data/latest.json",1543 timeout=10)1544 if resp.ok:1545 exploits = [e for e in resp.json() if address.lower() in str(e).lower()]1546 if exploits:1547 results["platforms"]["exploit_db"] = {"matches": len(exploits)}1548 except Exception:1549 pass15501551 # 3. If we have social media hints, search for them (pseudocode — API keys vary)1552 if identity_hints:1553 results["platforms"]["hints_provided"] = identity_hints1554 results["note"] = "Cross-reference identity hints against on-chain activity timestamps"15551556 return results1557```15581559### Address Cluster Publication15601561ZachXBT publicly releases address clusters on Twitter/X after investigations. This creates a1562positive feedback loop: the community cross-references new scams against published clusters,1563identifying repeat offenders across projects.15641565**Publishing strategy:**1566- **Include all identified addresses** (EOAs, contracts, intermediate wallets)1567- **Label each address** with its role (deployer, funder, intermediate, exchange deposit)1568- **Chain + tx hash evidence** for every link — no unsupported claims1569- **Timestamp the publication** to establish timeline priority15701571### The Bounty Model15721573ZachXBT demonstrates that on-chain investigation is a viable career. Revenue sources:15741575- **Community-funded bounties** — Twitter/X tip jar, Gitcoin grants, mirror.xyz articles1576- **Exchange bug bounties** — Exchanges pay for intelligence that helps them freeze stolen funds1577- **Project recovery bounties** — 5-15% of recovered funds for tracing assistance1578- **Media consulting** — Journalists pay for investigation reports on high-profile incidents1579- **Private investigations** — Law firms and insurance companies contract for court-ready reports158015811582## Anti-Rationalization Table1583## Anti-Rationalization Table15841585| Rationalization | Reality |1586|---|---|1587| "Blockchain is anonymous so tracing is impossible" | Blockchain is pseudonymous, not anonymous. Every transaction is permanently recorded and analyzable. |1588| "Mixers make tracing impossible" | Mixers complicate but don't prevent tracing. Timing analysis, amount patterns, and deposit/withdrawal correlations often deanonymize users. |1589| "The amount is too small to trace" | Small amounts are often test transactions. Follow the same address for larger patterns — test txs confirm control. |1590| "Cross-chain transactions break the trail" | Bridge contracts, wrapped assets, and event logs leave permanent on-chain evidence on both chains. The trail is cross-referencable. |1591| "Peel chains are too complex to map" | Peel chains show a statistical signature (decaying value per hop) that is algorithmically detectable. Graph analysis reveals the structure. |1592| "Exchange deposits are dead ends" | Most regulated exchanges require KYC. A deposit address + timestamp is sufficient for subpoena or law enforcement request. |1593| "UTXO chains can't be clustered" | CoJoin heuristic (multiple inputs = common owner) clusters 60-80% of addresses on Bitcoin. CoinJoin must be explicitly filtered. |1594| "I need full node data to trace" | Public block explorer APIs (Etherscan, mempool.space) are sufficient for 90% of cases. RPC nodes are only needed for raw event log parsing. |1595| "Only one chain matters, the rest are noise" | Attackers almost always bridge to another chain. Ignoring cross-chain means missing the destination of funds. |1596| "The trace is done when I hit a DeFi protocol" | DEX swaps and DeFi deposits leave logs too. Follow the LP tokens, check withdraw events, track the swap output tokens. |