Blockchain Analytics, Forensics and AIIntroductionA blockchain is an unusually rich evidence source: it records transactions, state changes, timestamps, contract interactions and, in many systems, token ownership. Yet a blockchain is not automatically a complete, correct or intelligible database. Addresses are pseudonymous, smart contracts may emit incomplete events, different chains use different data models, and off-chain information is often needed to identify people or organizations. Blockchain analytics therefore combines distributed-systems knowledge, data engineering, graph theory, statistics, investigative methods and responsible artificial intelligence. This chapter presents a practical framework for collecting and interpreting on-chain data. It considers explorers, node interfaces, indexer APIs and dashboards; develops transaction, network, holder and protocol metrics; introduces graph-based investigation and anomaly detection; and explains how AI can assist without replacing evidence-based judgment. Learning ObjectivesBy the end of this chapter, a student should be able to: - Distinguish raw blockchain data, indexed data, derived metrics and off-chain evidence.
- Select suitable explorers, node providers, APIs and analytical tools.
- Calculate and interpret transaction, network, holder and protocol metrics.
- Model blockchain activity as temporal graphs and identify useful investigative patterns.
- Apply rule-based and statistical anomaly detection appropriately.
- Evaluate AI-assisted blockchain analysis for accuracy, privacy, attribution and governance risks.
- Produce a reproducible, ethically defensible analytical report.
1. The Evidence Structure of a Blockchain1.1 Layers of analytical dataBlockchain evidence can be organized into four layers: | Layer | Examples | Main analytical question |
|---|
| Raw ledger | Blocks, transaction bytes, receipts, logs, state roots | What was recorded? | | Indexed data | Address histories, token transfers, decoded calls | How can the record be searched efficiently? | | Derived data | Balances, clusters, rates, graph features, risk scores | What patterns can be calculated? | | Off-chain evidence | Exchange records, legal documents, IP data, user reports | Who or what may an address represent? |
Raw data is closest to the consensus record but is difficult to query. Indexers transform it into searchable tables, sometimes introducing omissions or interpretation errors. A balance, for example, is not always the sum of visible transfer events: minting, burning, rebasing, contract-controlled balances and chain-specific state rules may matter. 1.2 Important terminologyAn address is an identifier used by an account or script. An externally owned account (EOA) is controlled by a private key, whereas a contract account is controlled by deployed code on platforms such as Ethereum. A transaction is a signed request or ledger operation; a receipt records execution results, including status and logs. An event log is data emitted by a smart contract. A block groups transactions and provides ordering and consensus metadata. A wallet may refer to software, a person, an organization or a custody system, so the word must not be treated as a proven identity. A finalized transaction is one that the relevant consensus system considers sufficiently irreversible. Before finality, reorganizations can alter apparent history. Analysts must record the chain, block height, block hash, extraction time and finality status. 2. Collecting On-Chain Data2.1 Explorers, nodes and APIsA block explorer is useful for inspection and teaching. It commonly provides decoded transactions, contract source information, token transfers and address pages. It is not necessarily a complete research database, and its labels and calculations may be proprietary. A node interface, commonly accessed through a remote procedure call (RPC), provides closer access to chain data. It can retrieve blocks, transactions, receipts, contract code and state queries. Full historical analysis may require an archive node or a specialized indexer. Indexer APIs organize data into endpoints such as: - blocks and transactions;
- native-asset transfers;
- token transfers and balances;
- contract calls and event logs;
- decentralized-exchange trades;
- labels and address metadata.
A data pipeline should store the source, endpoint, query parameters, chain identifier, time of retrieval and software version. Rate limits, pagination, missing records and duplicated records should be tested rather than assumed away. 2.2 A reproducible collection workflowA defensible workflow is: - Define the question and observation period.
- Define the chain, asset units and inclusion rules.
- Obtain raw or indexed records from at least one appropriate source.
- Normalize timestamps, identifiers, decimal conventions and transaction status.
- Deduplicate records using transaction hash, log index and chain-specific keys.
- Validate selected records against a second source or the node itself.
- Compute metrics using documented code.
- Preserve raw data, transformations and output tables.
- State uncertainty and limitations in the report.
Token quantities require special care. A displayed value is often calculated as qdisplayed = qraw ÷ 10d where qraw is the integer quantity recorded on-chain and d is the token’s decimal setting. The formula assumes the decimal metadata is correct and that the asset uses a fixed decimal convention. The result has token units, not necessarily a monetary value. 3. Core MetricsMetrics are useful only when their definitions, time windows and denominators are explicit. 3.1 Transaction metricsFor an observation interval, transaction count is N = ∑i=1n 1(transactioni satisfies inclusion rule) where N is the count and the indicator contributes 1 when a record meets the rule and 0 otherwise. The rule might include only successful transactions, exclude contract-internal calls, or count token transfers separately. These choices can produce very different results. The success rate is s = Nsuccess ÷ Nsubmitted where both counts refer to the same interval and population. A failed transaction may still consume fees and appear in a block; it should not silently be removed from all analyses. Average fee is F̄ = (∑i=1N feei) ÷ N where feei is measured in the chosen native unit and the denominator must state whether it includes failed transactions. For a gas-based account, fee may be computed as gas used × effective gas price, subject to the chain’s fee model. Monetary fee estimates additionally require a price timestamp and currency conversion assumption. The inter-arrival time between ordered transactions is ∆ti = timestampi − timestampi−1 and its mean is meaningful only when timestamps are comparable and ordering is correctly defined. Block timestamps can be approximate and should not be interpreted as precise human-time observations. 3.2 Network and activity metricsThe number of active addresses in period T is AT = |{a : a has at least one qualifying activity in T}| The definition of qualifying activity must specify whether receiving, sending, contract calls, failed transactions and automated system accounts count. “Active users” is often an overstatement: one person can control many addresses, and one address can represent an exchange serving many people. A simple activity concentration measure is the share of events attributable to the top k addresses: Ck = (∑j=1k x_(j)) ÷ (∑j=1m xj) where x_(j) is the j-th largest address activity value and m is the number of addresses. This is not the same as ownership concentration, because activity and holdings measure different things. For a directed address graph G = (V, E), in-degree and out-degree are din(v) = number of edges entering v dout(v) = number of edges leaving v Edges may represent transactions, token transfers or contract calls. A high-degree address may be an exchange, router or automated service rather than an influential individual. 3.3 Holder metricsIf address balances are b1, b2, …, bn and total measured supply is S = ∑bi, the share of holder i is hi = bi ÷ S This assumes the holder set and supply definition are complete and consistent. Locked contracts, treasury accounts, burn addresses, liquidity pools and custodians should be categorized rather than blindly interpreted as ordinary holders. The Herfindahl–Hirschman Index (HHI) for holder concentration is HHI = ∑i=1n hi2 With shares expressed as proportions, HHI lies between approximately 0 and 1; a value near 1 indicates concentration in one holder. With percentage shares, the conventional value is 10,000 times larger. HHI is sensitive to entity attribution: splitting one economic owner across many addresses reduces the apparent concentration. The Gini coefficient can also describe inequality. For balances sorted in nondecreasing order, one common discrete form is G = [2∑i=1n i bi] ÷ [n∑i=1n bi] − (n+1) ÷ n where n is the number of holders and zero balances are handled consistently. The formula assumes nonnegative balances and is not meaningful if the population definition changes between comparisons. 3.4 Protocol metricsProtocol analysis may include total value locked (TVL), volume, fees, revenue, utilization and liquidity. TVL is generally the market value of eligible assets at a specified time: TVL(t) = ∑a=1r quantitya(t) × pricea(t) The units are currency units, and the result depends on asset eligibility, price source, valuation time and treatment of borrowed or duplicated collateral. TVL is not automatically equivalent to protocol revenue or user deposits. A utilization ratio for a lending pool can be expressed as U = borrowed assets ÷ supplied assets provided numerator and denominator use the same asset basis and time. High utilization may indicate strong demand but also reduced withdrawal liquidity. Worked Example: Holder ConcentrationSuppose five categorized holders possess 40, 25, 15, 10 and 10 units of a token. Total supply in the measured set is 100 units, so shares are 0.40, 0.25, 0.15, 0.10 and 0.10. The HHI is HHI = 0.402 + 0.252 + 0.152 + 0.102 + 0.102 = 0.16 + 0.0625 + 0.0225 + 0.01 + 0.01 = 0.265. Thus, the measured holder distribution is substantially concentrated, although the interpretation must still consider exchanges, contracts, undisclosed common ownership and omitted addresses. 4. Graph Analytics and Forensics4.1 The transaction graphA transaction graph represents addresses or entities as nodes and transfers or interactions as directed edges. Edges may carry weight (value), time, asset type, transaction count or contract method. A temporal graph is preferable for investigations because the order of funding, interaction and movement often matters. Common graph features include degree, weighted degree, reciprocity, shortest paths, connected components and betweenness centrality. Betweenness centrality for node v is commonly defined as CB(v) = ∑s≠v≠t [σst(v) ÷ σst] where σst is the number of shortest paths from s to t and σst(v) is the number of those paths passing through v. The measure depends heavily on graph construction. A routing contract may have high centrality because it is technically necessary, not because it controls an organization. 4.2 Clustering and attributionAddress clustering attempts to infer which addresses may be controlled by one actor. Evidence can include known service addresses, common funding sources, synchronized behavior, shared withdrawal patterns and explicit attribution from reliable records. Heuristics are probabilistic, not proof. The common-input heuristic used in some UTXO systems, for example, can fail with collaborative transactions and modern privacy practices. Attribution should use confidence levels and evidence citations. A label such as “exchange” may describe a service address, a deposit address or an internal wallet, each with different analytical implications. Analysts should distinguish: - address identity: the technical identifier;
- address function: what the address appears to do;
- entity attribution: the organization or person believed to control it;
- legal identity: a conclusion requiring appropriate evidence and authority.
4.3 Investigative patternsUseful forensic patterns include peeling chains, rapid pass-through transfers, fan-in and fan-out, periodic transfers, interaction with mixers or bridges, and movement immediately before or after a known event. None is inherently illicit. Exchange batching, payroll, arbitrage, treasury management and automated market makers can produce similar patterns. A sound investigation preserves transaction hashes, block references, screenshots only as supplementary evidence, raw API responses, time zones and chain-specific interpretations. It uses independent corroboration and avoids presenting a visual graph as proof of criminal intent. 5. Anomaly DetectionAn anomaly is an observation that is unusual relative to a defined reference population. It is not automatically fraud, an attack or a protocol failure. 5.1 Rule-based detectionRules are transparent and useful for known conditions, such as a transfer exceeding a threshold, a contract receiving funds from a sanctioned address, or a sudden change in administrative permissions. Thresholds must account for asset denomination, historical behavior and false positives. 5.2 Statistical detectionFor a metric x with mean μ and standard deviation σ, a standardized score is z = (x − μ) ÷ σ This is informative when observations are reasonably comparable and the reference distribution is not severely distorted by outliers. A large absolute z-score indicates unusualness, not wrongdoing. For heavy-tailed blockchain values, the median and median absolute deviation may be more robust than mean and standard deviation. A simple rolling change rate is gt = (xt − xt−1) ÷ xt−1 where xt and xt−1 refer to comparable adjacent periods and xt−1 ≠ 0. When the denominator is zero or very small, a different measure or explicit exception is required. 5.3 Machine learningUnsupervised methods such as clustering, isolation forests and autoencoders can prioritize observations for review. Supervised classification can estimate a label when high-quality, representative labels exist. In blockchain settings, labels are often incomplete, delayed, legally sensitive or biased toward already investigated cases. Data leakage, concept drift after protocol upgrades and adversarial adaptation are major concerns. A responsible pipeline separates training, validation and test periods chronologically where possible. It reports precision, recall and false-positive rates for a defined threshold. Accuracy alone can be misleading when suspicious events are rare. Human review should examine the underlying transactions and the model’s reasons rather than accepting a score as a conclusion. 6. AI-Assisted Blockchain AnalysisAI can assist with schema mapping, natural-language querying, contract-code summarization, entity-resolution suggestions, feature generation, graph embeddings and report drafting. Retrieval-augmented systems can link generated statements to transaction hashes and source documents. These uses improve analyst productivity but do not create new ledger evidence. Important risks include: - Hallucination: a language model may invent a transaction, address label or causal explanation.
- Attribution error: similar behavior may be incorrectly assigned to one entity.
- Training bias: historical labels may reflect selective enforcement or incomplete coverage.
- Privacy risk: combining public addresses with IP, exchange or identity data can expose individuals.
- Adversarial manipulation: attackers can create deceptive patterns or poison analytical inputs.
- Automation bias: investigators may defer to a confident-looking score.
- Reproducibility failure: model versions, prompts and retrieval sources may change.
Best practice is to require source citations, maintain immutable input snapshots, version prompts and models, apply access controls, conduct bias and error testing, and obtain human approval for consequential decisions. Sensitive identity information should be minimized and processed under applicable data-protection and financial-crime laws. Public visibility is not equivalent to unrestricted ethical use. 7. Applied Case: Illustrative Token-Bridge InvestigationBackgroundA fictional compliance team monitors a cross-chain token bridge. Daily transfers normally involve many small and medium transactions, while bridge administrators use a small set of known operational addresses. ProblemOver one hour, a newly funded address sends assets through the bridge, receives assets on another chain, and rapidly distributes them to several new addresses. A dashboard flags the event as anomalous. AnalysisThe team first confirms the chain identifiers, block finality, token contract addresses and decimal settings. It retrieves raw transactions and receipts from nodes and compares them with two indexed sources. It then constructs a time-ordered graph with transfer value and contract method as edge attributes. The team calculates the address’s one-hour outflow, the ratio of pass-through value to retained value, and its deviation from a 30-day rolling baseline. A rule-based alert identifies the new address and rapid cross-chain movement. A statistical score adds context but is not treated as proof. Graph analysis shows that the funding address had previously interacted with a known service, but this is only a lead because service addresses may serve many customers. Analysts inspect bridge messages, verify whether the destination transactions succeeded, and check whether the apparent distribution is actually exchange batching or a protocol operation. They seek lawful off-chain records before assigning an entity identity. Approach and outcomeThe team classifies the event as “high-priority review,” freezes no funds solely on the model output, and sends a documented request for additional evidence through the organization’s approved compliance process. Subsequent review shows that the address was part of an authorized security exercise, so the alert is closed as a false positive and the model’s threshold is recalibrated. Learning pointsThe case demonstrates that anomaly detection prioritizes attention; it does not establish intent. Cross-chain analytics requires message correlation and careful finality handling. Attribution requires independent evidence. A false positive is not merely an inconvenience: excessive alerts consume investigative capacity and may cause unjustified action. 8. Quality, Governance and Professional PracticeA high-quality analytical report should state its question, data sources, extraction date, chain scope, inclusion rules, metric definitions, assumptions, uncertainty and limitations. It should distinguish observed facts from inferences and hypotheses. Reproducible notebooks, test datasets, unit tests for decimal conversion and reconciliation checks reduce avoidable error. Governance questions include who may access address-to-identity mappings, how long data is retained, whether subjects can challenge an attribution, and what legal standard applies to an intervention. Analysts should follow applicable anti-money-laundering, sanctions, privacy, evidence-handling and cybersecurity requirements. They should also recognize that immutable data can preserve harmful or identifying information indefinitely. 9. Contemporary DevelopmentsBlockchain analytics is increasingly multi-chain, requiring entity and event correlation across execution layers, rollups, bridges and application-specific networks. Zero-knowledge systems may reveal transaction validity while deliberately limiting linkability. Account abstraction changes assumptions about transaction sponsorship and address behavior. Decentralized finance produces composable transactions in which one user action may trigger many internal calls. These developments make simplistic address counts less reliable and increase the importance of protocol-specific semantics. AI systems are moving toward graph-based learning, agentic investigation and multimodal evidence review. Their value will depend less on fluent language generation than on traceability, calibrated uncertainty, secure data handling and effective human oversight. Chapter SummaryBlockchain analytics transforms ledger records into metrics, graphs and investigative evidence. Explorers are convenient, while nodes and indexed APIs support systematic collection; all sources require validation and documentation. Transaction counts, fees, active addresses, concentration, holder inequality, TVL and utilization are meaningful only when their populations, time windows and units are explicit. Graph methods reveal flows and structural relationships but do not by themselves prove control or intent. Rule-based, statistical and machine-learning methods can identify unusual activity, yet anomalies require contextual review. AI can accelerate querying, classification and reporting, but hallucination, attribution, privacy, bias and adversarial risks demand source-linked outputs and human accountability. The professional standard is reproducibility, cautious interpretation, lawful data use and a clear separation between recorded facts and inferred identities. Key TermsAddress: A blockchain identifier used by an account or script. Anomaly: An observation unusual relative to a defined reference population. Archive node: A node retaining historical state needed for deep queries. Attribution: An evidence-based inference connecting an address to an entity. Block explorer: An interface for browsing blockchain records. Centrality: A graph measure of a node’s structural importance. Clustering: Grouping addresses believed to share control or function. Event log: Contract-emitted data recorded in a transaction receipt. Finality: The state in which a transaction is considered sufficiently irreversible. HHI: Sum of squared holder shares used to measure concentration. Indexer: Software that organizes ledger data for efficient querying. On-chain data: Data recorded or derivable from a blockchain. Pass-through transaction: Movement in which received value is rapidly forwarded. Pseudonymity: Identifiability through persistent identifiers without direct names. RPC: An interface through which applications request node data. TVL: Market value of eligible assets held in or attributed to a protocol. Wallet: Software or custody arrangement used to control blockchain assets. Z-score: A standardized distance from a reference mean measured in standard deviations. Review QuestionsShort Answer Questions- Why should an analyst distinguish raw ledger data from indexed data?
- What does the HHI measure in holder analysis?
- Why is an address not automatically equivalent to a user?
- State two risks of AI-assisted blockchain analysis.
- What information should be preserved for a reproducible data extraction?
Long Answer Questions- Explain a complete workflow for collecting and validating on-chain data.
- Compare transaction, network, holder and protocol metrics, including their major assumptions.
- Explain how a temporal transaction graph can support blockchain forensics.
- Compare rule-based, statistical and machine-learning anomaly detection.
- Discuss ethical and governance requirements for address attribution.
Analytical / Application Questions- A token’s measured holder balances are 50, 20, 20 and 10 units. Calculate the holder shares and HHI, and explain two limitations of the result.
- Design an investigation for a newly created address that receives funds, uses a bridge and distributes assets to ten addresses within minutes. Specify evidence, validation steps and alternative explanations.
- A model flags 95% of known suspicious cases but generates many false alerts in a high-volume exchange dataset. Explain why accuracy or recall alone is insufficient and propose an evaluation and governance response.
Multiple Choice Questions with AnswersQuestion 1Which source is generally closest to the consensus record? A. A marketing dashboard B. Raw node data C. A social-media label D. An analyst’s summary Correct Answer: B. Raw node data Question 2If a token records q_raw units and has d decimals, which expression converts it to displayed token units? A. q_raw × 10^d B. q_raw + d C. q_raw ÷ 10^d D. d ÷ q_raw Correct Answer: C. q_raw ÷ 10^d Question 3What does a high holder HHI generally indicate? A. Low concentration B. High concentration C. High transaction finality D. Low network latency Correct Answer: B. High concentration Question 4Which statement about an anomaly is correct? A. It proves criminal intent B. It is always a data error C. It is unusual relative to a defined reference population D. It can only be detected by AI Correct Answer: C. It is unusual relative to a defined reference population Question 5In a directed transaction graph, out-degree counts the number of edges that: A. Enter a node B. Leave a node C. Are shortest paths D. Have zero value Correct Answer: B. Leave a node Question 6Why can TVL comparisons be misleading? A. TVL never uses prices B. TVL is independent of asset eligibility and valuation time C. TVL depends on asset scope, prices and valuation assumptions D. TVL is always equal to protocol revenue Correct Answer: C. TVL depends on asset scope, prices and valuation assumptions Question 7A z-score primarily measures: A. Distance from a reference mean in standard-deviation units B. The legal identity of an address C. The number of blocks in a chain D. The decimal setting of a token Correct Answer: A. Distance from a reference mean in standard-deviation units Question 8Which is an appropriate use of an AI model in forensic analysis? A. Treating its score as proof of guilt B. Generating uncited identities C. Prioritizing cases for human review with source-linked evidence D. Replacing all raw-data validation Correct Answer: C. Prioritizing cases for human review with source-linked evidence Question 9Why must cross-chain investigations verify bridge messages and destination transactions? A. Because blockchains cannot record timestamps B. Because an apparent transfer may not correspond to a successful or correctly matched destination operation C. Because graphs cannot contain edges D. Because token decimals are always identical across chains Correct Answer: B. Because an apparent transfer may not correspond to a successful or correctly matched destination operation Question 10If holder shares are 0.5, 0.3 and 0.2, what is the HHI? A. 0.30 B. 0.38 C. 0.50 D. 1.00 Correct Answer: B. 0.38
|