Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement On-Chain Forensics for Incident Response

A technical guide for developers and security researchers on investigating blockchain security incidents, from initial alert to post-mortem report.
Chainscore © 2026
introduction
PRACTICAL GUIDE

How to Implement On-Chain Forensics for Incident Response

A technical walkthrough for developers and security teams on collecting and analyzing blockchain data to investigate security incidents, from initial alert to actionable intelligence.

On-chain forensics is the systematic investigation of blockchain data to understand and respond to security incidents like hacks, exploits, and fraudulent transactions. Unlike traditional digital forensics, it operates on a public, immutable ledger, providing a transparent but complex audit trail. The core workflow involves transaction tracing, address clustering, and behavioral pattern analysis to map the flow of stolen funds, identify attacker-controlled addresses, and understand the exploit's mechanics. Tools like Etherscan, Tenderly, and specialized blockchain explorers are essential for this initial data gathering phase.

The investigation begins with the incident's root transaction hash. This is your primary crime scene. Using a block explorer, you can trace all subsequent transactions (OUT) from the compromised address and trace back (IN) to identify the entry point. For Ethereum and EVM chains, analyzing the transaction's internal calls via the trace is critical, as exploits often occur within a single transaction through a series of smart contract interactions. For example, a flash loan attack on a DeFi protocol will show a complex series of borrow, swap, and liquidity manipulation calls all within one transaction block, visible in a detailed trace.

To move beyond a single address, you must perform address clustering or heuristic analysis. This involves grouping addresses likely controlled by the same entity. Common heuristics include: - Addresses funded from the same source (common input ownership). - Addresses interacting with the same obscure or newly deployed contract. - Patterns in transaction timing or gas usage. Open-source libraries like Web3.py or Ethers.js can automate querying blockchain data for these patterns. For instance, after the Poly Network exploit, analysts clustered hundreds of addresses by tracing funds through multiple hops and identifying common intermediary wallets.

For deeper analysis, you need to decode and interpret smart contract interactions. This requires fetching the contract's Application Binary Interface (ABI) to understand function calls. Using ethers or web3, you can decode input data from transactions. For a suspected token approval exploit, you would decode the approve or increaseAllowance function call to see which spender address was granted access and the amount. Combining this with event log analysis—filtering for specific Transfer or Approval events—builds a complete picture of asset movement that isn't always apparent from native token transfers alone.

The final step is creating an actionable intelligence report and implementing countermeasures. The report should include: the attacker's address cluster, the full fund flow path, the total value extracted, and the method of exploit (e.g., faulty logic, price oracle manipulation). Based on this, teams can: 1) Update threat detection systems to flag similar transaction patterns. 2) Work with exchanges to freeze identified addresses. 3) Patch the vulnerable contract logic. Continuous monitoring via services like Forta Network or custom scripts watching for known malicious signatures is crucial for ongoing defense, turning a reactive investigation into a proactive security posture.

prerequisites
ON-CHAIN FORENSICS

Prerequisites and Initial Setup

This guide outlines the essential tools, accounts, and foundational knowledge required to begin conducting on-chain forensic investigations for security incidents.

Effective on-chain forensics requires a specific technical stack. You will need a reliable Ethereum node provider (like Alchemy, Infura, or a self-hosted node) for low-latency RPC access to blockchain data. A block explorer API key from Etherscan, Arbiscan, or a similar service is crucial for programmatically fetching transaction details and contract source code. For analysis, you'll need a development environment with Python 3.8+ or Node.js 16+, along with key libraries: web3.py or ethers.js for blockchain interaction, pandas for data manipulation, and matplotlib or plotly for visualization. Finally, set up a secure note-taking system to document your investigation steps and findings.

You must create and fund several types of accounts. First, obtain a read-only API key from your chosen node provider and block explorer; these are typically free for moderate usage. For active investigation, you will need a funded wallet with testnet ETH (e.g., on Sepolia or Goerli) to simulate transactions and interact with contracts without spending real assets. In some cases, a premium blockchain data platform account (like Dune Analytics, Nansen, or Arkham) can provide enriched, indexed data that accelerates tracing, though it is not strictly mandatory for basic analysis.

Before analyzing an incident, you must understand the core data structures. A blockchain transaction is more than just a transfer; it contains a from address, to address, value, input data (for contract calls), and gas parameters. The input data is critical—it encodes the function called and its arguments. You must be able to decode this using the contract's Application Binary Interface (ABI). Internally, transactions create execution traces, which are detailed logs of every smart contract call and state change that occurred, viewable via tools like debug_traceTransaction. Mastering these data sources is the foundation of tracing fund flow and attacker behavior.

Organize your investigation with a clear methodology. Start by identifying the incident's root transaction hash from public reports or alert systems. Use a block explorer to get an overview, then write scripts to programmatically fetch all related transactions. A common first step is to trace all Transfer events (ERC-20, ERC-721) from the compromised address. You should also map out the proxy and implementation contract architecture for the affected protocol, as attackers often exploit logic contracts. Bookmark relevant resources: the protocol's official documentation, its verified source code on Etherscan, and any existing public analysis of similar exploits to understand common patterns.

For practical scripting, begin with a simple Python script using web3.py to fetch and decode transactions. First, connect to your node provider (Web3(Web3.HTTPProvider(YOUR_RPC_URL))). Use w3.eth.get_transaction(tx_hash) to get basic data. To decode the input_data, you need the contract's ABI, which can be fetched from Etherscan's API or, if verified, copied directly from the contract page. With the ABI, you can instantiate a contract object (w3.eth.contract(address=address, abi=abi)) and decode the transaction input using contract.decode_function_input(tx.input). This will reveal the exact function (e.g., executeFlashLoan) and arguments used by the attacker.

key-concepts-text
INCIDENT RESPONSE

How to Implement On-Chain Forensics for Incident Response

A tactical guide for security teams to analyze blockchain transactions, trace stolen funds, and gather evidence following a security incident.

On-chain forensics is the process of analyzing public blockchain data to investigate security incidents like hacks, exploits, and fraud. Unlike traditional digital forensics, it relies on the immutable, transparent ledger to trace the flow of funds, identify attacker-controlled addresses, and understand the exploit's mechanics. Effective incident response requires moving quickly to map the attack path before funds are laundered through mixers or cross-chain bridges. Key tools for this initial triage include block explorers like Etherscan, specialized analytics platforms such as Arkham or TRM Labs, and custom scripts using node RPCs.

The first step is transaction analysis. Start with the exploit transaction hash. Examine the internal transactions and event logs to see which smart contract functions were called. Look for suspicious patterns: - Unusual token approvals to unknown contracts - Large, sudden outflows to new addresses - Interactions with known mixer deposit addresses (e.g., Tornado Cash) or cross-chain bridges. Tools like Tenderly's debugger or OpenZeppelin's Defender can replay transactions to see state changes. Document every step, noting source and destination addresses, amounts, and timestamps to build a timeline.

Next, perform address clustering and entity analysis. Attackers often use multiple wallets. Use heuristics to link them: - Common funding sources (e.g., a central exchange withdrawal) - Similar transaction patterns and timing - Interaction with the same set of intermediary contracts. Services like Chainalysis Reactor or the free WalletExplorer can help visualize these connections. The goal is to identify the attacker's "cash-out" addresses, where funds are sent to centralized exchanges (CEXs). You can then file a report with the CEX's compliance team, providing your evidence to freeze the assets.

For advanced tracing, you may need to write custom scripts. Using a library like web3.py or ethers.js, you can programmatically query transactions, filter logs, and track token movements across complex DeFi protocols. For example, after a flash loan attack, you'd trace the collateral flow through multiple liquidity pools. A basic script might fetch all Transfer event logs for a stolen ERC-20 token from the block of the exploit onward, grouping them by recipient to find the largest downstream clusters.

Finally, compile your findings into a forensic report. This should include: 1) A summary of the incident and total loss, 2) The attack transaction hash and exploited vulnerability, 3) A visual map of fund flows, 4) A list of all identified attacker-controlled addresses with labels, 5) Evidence of cash-out attempts to CEXs. Share this report with law enforcement, affected protocols, and blockchain intelligence firms. Proactive measures include monitoring the attacker's addresses for future movement and setting up alerts for any interactions with your protocol's contracts.

step-1-alert-triage
INCIDENT RESPONSE WORKFLOW

Step 1: Alert Triage and Initial Data Collection

The first critical phase in on-chain forensics involves systematically assessing an alert and gathering the foundational data needed for investigation. This step determines the scope and priority of the response.

When an alert fires—whether from a monitoring tool like Forta, a community report, or an internal dashboard—your first task is triage. This means quickly assessing the alert's severity and validity. Ask key questions: Is this a false positive from a benign contract interaction? Is it a known attack pattern (e.g., a flash loan exploit)? Or is it a novel, in-progress incident? Prioritize alerts based on potential financial impact and the attacker's window of opportunity to move funds.

With a validated alert, begin initial data collection. The core artifact is the transaction hash (tx_hash). This single identifier is your entry point to the blockchain's immutable ledger. Using a node provider or block explorer API (e.g., Etherscan, Blockscout), retrieve the full transaction object. Critical fields to extract include: the from and to addresses, transaction value, input data (for contract calls), gas used, and the block number and timestamp. This data forms the baseline for your investigation.

Next, expand your view by fetching the transaction receipt and tracing its execution. Use an archive node's debug_traceTransaction RPC method or a service like Tenderly to get a full execution trace. This trace reveals every internal call, state change, and log emitted during the transaction's lifecycle. It allows you to see the actual flow of logic and funds, not just the top-level result. For Ethereum Virtual Machine (EVM) chains, tools like ethers.js or web3.py can programmatically fetch this data for analysis.

Simultaneously, collect all event logs emitted by the transaction. Events are a smart contract's way of recording significant occurrences on-chain, such as token transfers (Transfer), ownership changes, or specific function calls. These logs are indexed and searchable, providing a high-level map of the transaction's effects. Correlate the logs with the execution trace to understand the sequence of operations. This combined dataset—raw transaction, execution trace, and event logs—completes the initial evidence package.

Finally, document your findings in a structured incident log. Record the alert source, triage decision, collected tx_hash, involved addresses (tagging known entities like DeFi protocols or exchange deposit addresses), and a preliminary hypothesis. This log ensures knowledge is retained and can be handed off if needed. Effective triage and data collection transform a raw alert into a structured, actionable case file, setting the stage for deeper forensic analysis in the next steps.

step-2-trace-funds
ON-CHAIN FORENSICS

Step 2: Tracing Stolen Fund Flows

Once a security breach is confirmed, the next critical step is to trace the movement of stolen assets across the blockchain. This process, known as on-chain forensics, involves mapping the flow of funds from the initial theft to their current location or exit points.

Effective on-chain forensics begins with identifying the initial exploit transaction on the source chain. This involves analyzing the transaction hash, the attacker's wallet address (EOA or contract), and the exact method of theft (e.g., a reentrancy attack, a compromised private key, or a flawed contract logic). Tools like Etherscan, Arbiscan, or Tenderly are essential for this initial reconnaissance. The goal is to establish a definitive starting point for the fund trail, noting the token types (native ETH, ERC-20, ERC-721) and amounts involved.

With the source identified, you must trace the subsequent hops of the stolen funds. Attackers rarely keep assets in the initial wallet. They use techniques like chain-hopping (moving funds between L1 and L2s), mixing through privacy protocols or decentralized exchanges, and bridging to other ecosystems. To follow this, you need to use specialized blockchain explorers that support cross-chain tracing, such as Arkham or Chainalysis Reactor, or write custom scripts using libraries like web3.py or ethers.js to programmatically track transactions from the attacker's address.

A key pattern to watch for is fund dispersion. Attackers often split large sums into smaller amounts and send them to dozens of intermediate wallets in a process called peeling chains. This is done to obfuscate the trail and avoid triggering exchange monitoring systems. Your forensic analysis must map each of these outgoing transactions. Look for transactions that consolidate funds again at a later point, as this often indicates preparation for a cash-out attempt.

The ultimate goal of tracing is to identify off-ramps—points where crypto converts to fiat or moves to a custodial service. The most common off-ramps are centralized exchanges (CEXs), fiat-backed stablecoin issuers, and cross-chain bridges to regulated networks. When funds hit a deposit address at a known CEX like Binance or Coinbase, you can file a formal law enforcement request or use the exchange's official incident response channel. Documenting the entire flow with timestamps, amounts, and wallet addresses is crucial for this process.

For developers, automating parts of this trace can be vital for rapid response. Below is a simplified Python example using the Web3.py library to get the outgoing transactions from an attacker's address, which can be the first step in building a custom tracing tool.

python
from web3 import Web3
import json

# Connect to an Ethereum node (e.g., via Infura)
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY'))

attacker_address = '0xAttackerAddressHere'

# Get the last 100 blocks for analysis
latest_block = w3.eth.block_number
start_block = latest_block - 100

print(f"Scanning from block {start_block} to {latest_block}")

for block_num in range(start_block, latest_block + 1):
    block = w3.eth.get_block(block_num, full_transactions=True)
    for tx in block.transactions:
        if tx['from'].lower() == attacker_address.lower():
            print(f"Block: {block_num}, Tx Hash: {tx.hash.hex()}, To: {tx.to}, Value: {w3.from_wei(tx.value, 'ether')} ETH")

This script identifies outgoing transactions, which you can then further investigate to see where the funds were sent.

Finally, compile your findings into a clear forensic report. This should include a visual flow diagram (tools like Maltego or manual charts work), a timeline of key transactions, a list of all associated wallet addresses, and the identified off-ramps. This report is your primary artifact for engaging with exchanges, law enforcement, and the public to potentially freeze funds and warn other projects. Remember, speed and accuracy in this phase directly impact the chances of asset recovery.

step-3-address-clustering
ON-CHAIN FORENSICS

Address Clustering and Attacker Profiling

This guide details the process of grouping related blockchain addresses to build a profile of a malicious actor, a critical step in incident response.

Address clustering is the process of linking multiple blockchain addresses to a single controlling entity. Attackers rarely use a single wallet; they create complex networks of addresses for fund dispersion, laundering, and obfuscation. The core technique is heuristic analysis, which uses on-chain patterns to infer connections. Common heuristics include: - Common Input Ownership (CIO): If multiple addresses are inputs to the same transaction, they are likely controlled by the same entity. - Change Address Detection: Identifying which output of a transaction is the 'change' sent back to the sender. - Deposit/Withdrawal Patterns: Tracking funds moving between centralized exchanges and on-chain wallets.

To implement clustering, you need to programmatically analyze transaction graphs. Using a node provider like Alchemy or QuickNode, you can fetch transaction data. The following Python snippet demonstrates fetching inputs for a transaction, a foundational step for CIO analysis:

python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('YOUR_RPC_URL'))
tx_hash = '0x...'
tx = w3.eth.get_transaction(tx_hash)
receipt = w3.eth.get_transaction_receipt(tx_hash)
# The 'from' address is a known controller
controller = tx['from']
# All input addresses in this transaction are clustered with the controller
input_addresses = [tx['from']]  # Start with the sender
for log in receipt['logs']:
    # Analyze internal transactions or token transfers for more addresses
    pass

Once you have a cluster of addresses, you begin attacker profiling. This involves analyzing the cluster's behavior to answer key questions: What was the initial funding source (e.g., a stolen NFT sale, a mixer deposit)? What tools did they use (specific smart contracts for swapping, bridging, or laundering like Tornado Cash)? What is their cash-out strategy (which CEXs do they deposit to)? This profile helps predict the attacker's next moves, assess the likelihood of fund recovery, and provide critical intelligence to exchanges and law enforcement. Tools like Chainalysis Reactor or open-source libraries like web3.py and ethers.js are essential for this deep-dive analysis.

step-4-root-cause-analysis
ON-CHAIN FORENSICS

Step 4: Root Cause Analysis of the Exploit

After initial triage, the next critical step is to conduct a detailed root cause analysis. This involves using on-chain forensics tools to trace the exploit's execution path, identify the vulnerable contract function, and understand the precise flaw in the logic.

Begin your analysis by reconstructing the exploit transaction sequence. Use a block explorer like Etherscan or a specialized forensic platform like Tenderly to examine the transaction hash. Focus on the internal transactions or trace calls, which show the exact flow of execution between smart contracts. Look for unexpected token transfers, contract creations, or calls to obscure functions. The goal is to map out every step the attacker took, from the initial entry point to the final fund exfiltration.

Next, isolate the vulnerable contract and function. Load the contract's verified source code into an IDE and examine the specific function called by the attacker. Common vulnerabilities to look for include: reentrancy in state updates, integer overflows/underflows, flawed access control (e.g., missing onlyOwner modifiers), and price oracle manipulation. Compare the on-chain state (storage slots read/written) from the transaction trace against the contract's intended logic to spot the discrepancy. Tools like Etherscan's State Changes tab or OpenChain's differential tracer can visualize this.

For a concrete example, consider a reentrancy attack. The trace will show a call from the vulnerable contract to an external, malicious contract, which then calls back into the original function before its state (like a balance) is updated. In Solidity, this often occurs in functions that perform a call.value() before updating an internal balance variable. The forensic evidence is the recursive call pattern visible in the transaction trace.

To automate parts of this process, you can use scripts with libraries like web3.py or ethers.js. For instance, you can fetch and decode transaction logs and trace data to programmatically identify suspicious patterns. ```python

Example: Fetching trace data for a transaction hash using Web3.py

from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY')) trace = w3.provider.make_request('debug_traceTransaction', ['0x...', {'tracer': 'callTracer'}]) print(trace) # Analyze the nested call structure

Finally, synthesize your findings into a clear root cause statement. This should specify: 1) The vulnerable contract address and function, 2) The type of vulnerability (e.g., "Reentrancy in the withdraw() function"), 3) The flawed logic or missing safeguard, and 4) How the attacker's input exploited it. This analysis is crucial for writing the incident report, patching the vulnerability, and preventing future occurrences. Document all evidence, including links to transaction traces and relevant code snippets.

DATA SOURCES & ANALYSIS

On-Chain Forensic Tool Comparison

Comparison of popular tools for analyzing blockchain transactions and wallet activity during security investigations.

Feature / MetricEtherscanTenderlyArkham Intelligence

Real-time Transaction Simulation

Multi-Chain Support (EVM + non-EVM)

Free Tier API Rate Limit

5 calls/sec

10 calls/sec

1 call/sec

Entity Labeling & Clustering

Basic

Limited

Advanced

Private Transaction Forking

Historical State Queries

Last 10k blocks

Full Archive Node

Last 10k blocks

Visual Flow Diagrams

Basic

Advanced

Advanced

Cost for Pro Tier (Monthly)

$99+

$49

$99+

step-5-reporting
INVESTIGATION SYNTHESIS

Step 5: Compiling the Investigation Report

This final step transforms raw blockchain data into a structured, actionable narrative for stakeholders. A well-compiled report documents the incident, supports recovery efforts, and informs future security posture.

The investigation report is the primary deliverable of your forensic process. It must clearly communicate the attack vector, financial impact, attacker attribution, and remediation steps to both technical and non-technical audiences. Start with an executive summary that concisely states the incident's scope, the confirmed loss amount in USD and native tokens, and the root cause (e.g., "private key compromise via phishing" or "exploit of a reentrancy vulnerability in contract X"). This section should allow a manager or investor to grasp the core facts within 60 seconds.

The body of the report details the methodology and evidence. Document the tools used, such as Etherscan, Tenderly, or custom scripts, and the specific transaction hashes that form the attack chain. For example: Transaction 0xabc... was the malicious approval, and 0xdef... was the drain transaction. Include relevant smart contract addresses, wallet addresses (EOAs and contracts), and the block range of the incident. Use code snippets to illustrate critical findings, like a decoded function call showing the exploit parameters or a query from a block explorer's API.

A critical section is the timeline reconstruction. Create a chronological log of events from the initial suspicious transaction to the final fund movement. For each step, note the block height, timestamp, from/to addresses, asset type, and amount. This timeline is essential for understanding the attack flow and is often required for legal proceedings or insurance claims. Visual aids, like a simple flowchart or a table exported from your investigation notes, significantly improve clarity here.

Conclude with actionable recommendations. These should be specific and prioritized. For example: 1) Immediate: Revoke all unnecessary token approvals for the compromised wallet using Revoke.cash. 2) Short-term: Implement a multisig wallet for treasury management. 3) Long-term: Commission a smart contract audit for the vulnerable protocol and establish a formal incident response plan. Link each recommendation directly to a finding in your evidence section to justify the proposed action.

Finally, archive all supporting materials. This includes the raw data dumps, saved block explorer links, script outputs, and chain snapshots. Store these in a secure, version-controlled repository. The completed report should serve as a definitive record of the incident, enabling post-mortem analysis, guiding security improvements, and providing necessary documentation for any external reporting requirements to law enforcement or regulatory bodies.

ON-CHAIN FORENSICS

Frequently Asked Questions

Common questions and technical challenges developers face when implementing on-chain forensics for security incident response.

The first step is transaction tracing to establish the attack vector. This involves analyzing the initial malicious transaction that triggered the incident. Key actions include:

  • Identifying the entry point: Find the contract function call (e.g., swap(), approve(), execute()) that was exploited.
  • Extracting calldata: Decode the input parameters to understand what data was passed to the contract.
  • Reviewing event logs: Smart contracts emit events for state changes; these are immutable and crucial for reconstructing the attack flow.

Tools like Etherscan's Tracer, Tenderly Debugger, or BlockSec's Phalcon are essential for this step. Start from the exploit transaction hash and work backwards to map the fund flow and contract interactions.

conclusion-next-steps
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

This guide has outlined the core components of building an on-chain forensics pipeline for security incident response. The next step is to integrate these techniques into a cohesive workflow.

Implementing on-chain forensics requires a systematic approach. Start by establishing a real-time data ingestion pipeline using services like The Graph for indexed event logs or direct RPC nodes for low-latency block streaming. Tools such as Ethers.js or Viem are essential for querying transaction details and internal calls. For persistent storage, consider a time-series database like TimescaleDB to efficiently handle the volume of blockchain data, enabling complex historical analysis.

The analytical layer is where your custom logic applies. Develop modular scripts for common tasks: tracing fund flows with debug_traceTransaction, mapping smart contract interactions via decoded event logs, and clustering addresses using heuristic rules (e.g., common funding sources or contract creators). Open-source libraries like Tenderly's SDK or EVM Codes can help simulate transactions and decode complex bytecode, providing deeper insight into exploit mechanics.

To operationalize this, build an incident response playbook. This should define clear triggers (e.g., anomalous transaction volume alerts from a platform like Chainalysis or TRM), assign roles, and outline step-by-step procedures for the forensic phases: Triage, Investigation, Attribution, and Reporting. Automate the initial evidence collection so responders begin with a populated dossier of relevant transactions, token movements, and involved addresses.

Continuous improvement is critical. Maintain a threat intelligence repository of known malicious signatures (e.g., phishing contract bytecode hashes, mixer deposit patterns) and attacker EOA (Externally Owned Account) clusters. Participate in communities like the Blockchain Intelligence Group or open-source projects such as Forta Network to stay updated on new attack vectors. Regularly test your pipeline with historical incidents, such as analyzing the 2022 Nomad Bridge exploit, to validate its effectiveness.

Finally, consider the ethical and legal framework. On-chain analysis often touches on privacy considerations. Develop clear internal policies for data handling. For teams requiring advanced capabilities, exploring specialized platforms like Arkham or Nansen for enriched entity labeling can augment in-house tools. The goal is to move from reactive analysis to proactive threat detection, ultimately hardening your protocol's security posture.

How to Implement On-Chain Forensics for Incident Response | ChainScore Guides