šŸŽ‰ 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
šŸ’¼ Servicesā„¹ļø Aboutāœ‰ļø ContactView Pricing Plansfrom $10

Blockchain Data Structures

Blockchain Internals🟢 Free Lesson

Blockchain Data Structures

Merkle Trees, Patricia Tries, UTXO vs Account model, state management, data structure comparisons, and hash efficiency.

Overview

Blockchain data structures are foundational to how data is stored, verified, and retrieved across decentralized networks. Understanding these structures is critical for building efficient smart contracts and optimizing on-chain storage.

Merkle Trees

A Merkle Tree is a binary tree of hashes where each leaf node contains the hash of a data block, and each non-leaf node contains the hash of its two children.

Merkle Tree Construction

python
import hashlib

def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()

class MerkleTree:
    def __init__(self, transactions: list):
        self.transactions = transactions
        self.tree = self._build_tree(transactions)

    def _build_tree(self, leaves: list) -> dict:
        if len(leaves) == 0:
            return {}
        if len(leaves) == 1:
            return {"hash": sha256(leaves[0]), "data": leaves[0]}

        mid = len(leaves) // 2
        left = self._build_tree(leaves[:mid])
        right = self._build_tree(leaves[mid:])

        combined = left["hash"] + right["hash"]
        return {
            "hash": sha256(combined.encode()),
            "left": left,
            "right": right,
        }

    def get_root(self) -> str:
        return self.tree["hash"]

    def get_proof(self, index: int) -> list:
        proof = []
        node = self.tree
        path = bin(index)[2:].zfill(self._depth())

        for bit in path:
            if bit == "0":
                proof.append({"direction": "right", "hash": node["right"]["hash"]})
                node = node["left"]
            else:
                proof.append({"direction": "left", "hash": node["left"]["hash"]})
                node = node["right"]

        return proof

    def _depth(self) -> int:
        return (len(self.transactions) - 1).bit_length()

Merkle Tree Diagram

Root HashHash(AB)Hash(CD)Hash(Tx A)Hash(Tx B)Hash(Tx C)Hash(Tx D)Transaction ATransaction BTransaction CTransaction DMerkle Tree Structure: Logarithmic proof complexity O(log n)

Merkle Proof Efficiency

The time complexity for verifying a Merkle proof is:

where is the number of leaves. For a block with 2,048 transactions, only 11 hashes are needed for verification.

Properties

PropertyDescriptionComplexity
ConstructionBuild tree from leaves
Root computationSingle root hash lookup
Proof generationPath from leaf to root
Proof verificationRecompute root from proof
Space efficiencyStore only root total, verification

Real-World Usage

Bitcoin uses Merkle Trees to summarize all transactions in a block. The Merkle root is stored in the block header, enabling Simplified Payment Verification (SPV) nodes to verify transaction inclusion without downloading the full block.


Patricia Trie (Radix Trie)

Ethereum uses a Modified Merkle Patricia Trie (MPT) for state storage, combining the advantages of Patricia tries, Merkle trees, and radix tries.

Patricia Trie Structure

Architecture Diagram
State Root
ā”œā”€ā”€ Branch Node [0..f]
│   ā”œā”€ā”€ [0] -> Leaf: account_0
│   ā”œā”€ā”€ [1] -> Extension: "a3f" -> Branch
│   │   └── Branch Node
│   │       ā”œā”€ā”€ [2] -> Leaf: account_1
│   │       └── [5] -> Leaf: account_2
│   └── [f] -> Leaf: account_15
└── ...

MPT Implementation

python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_leaf = False
        self.value = None

class ModifiedMerklePatriciaTrie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, key: str, value: bytes):
        node = self.root
        for char in key:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_leaf = True
        node.value = value

    def get(self, key: str) -> bytes:
        node = self.root
        for char in key:
            if char not in node.children:
                return None
            node = node.children[char]
        return node.value if node.is_leaf else None

    def compute_root_hash(self) -> str:
        return self._hash_node(self.root)

    def _hash_node(self, node: TrieNode) -> str:
        if node.is_leaf:
            return sha256(node.value)
        encoded = "".join(
            self._hash_node(node.children[k]) for k in sorted(node.children.keys())
        )
        return sha256(encoded.encode())

Patricia Trie vs Merkle Tree Comparison

FeatureMerkle TreePatricia Trie
StructureBinary treeRadix tree
Key storageNone (index-based)Key-value pairs
Update complexity rebuild path
Prefix sharingNoneAutomatic
Used inBitcoin blocksEthereum state
State proofsTransaction inclusionAccount/storage proofs

UTXO vs Account Model

UTXO Model (Bitcoin)

In the UTXO model, transactions consume previous outputs and create new ones. There are no accounts or balances - only unspent transaction outputs.

Architecture Diagram
Transaction 1 (Input: UTXO_A) -> Output 1: UTXO_B (2 BTC to Alice)
                                -> Output 2: UTXO_C (3 BTC to Bob)

Transaction 2 (Input: UTXO_B) -> Output 1: UTXO_D (1 BTC to Carol)
                                -> Output 2: UTXO_E (1 BTC change to Alice)
python
class UTXO:
    def __init__(self, tx_id: str, index: int, amount: int, script_pubkey: str):
        self.tx_id = tx_id
        self.index = index
        self.amount = amount
        self.script_pubkey = script_pubkey

    @property
    def outpoint(self) -> str:
        return f"{self.tx_id}:{self.index}"

class UTXOSet:
    def __init__(self):
        self.utxos = {}

    def add(self, utxo: UTXO):
        self.utxos[utxo.outpoint] = utxo

    def remove(self, outpoint: str):
        if outpoint in self.utxos:
            del self.utxos[outpoint]

    def get_balance(self, address: str) -> int:
        return sum(
            u.amount for u in self.utxos.values()
            if u.script_pubkey == address
        )

Account Model (Ethereum)

The account model maintains global state with account balances and nonces.

// Simplified account state representation
struct AccountState {
    uint256 nonce;      // Transaction count
    uint256 balance;    // Wei balance
    bytes32 storageRoot; // Root of storage trie
    bytes32 codeHash;   // Hash of contract code
}
python
class AccountModel:
    def __init__(self):
        self.accounts = {}

    def get_balance(self, address: str) -> int:
        return self.accounts.get(address, {}).get("balance", 0)

    def transfer(self, sender: str, recipient: str, amount: int) -> bool:
        if self.get_balance(sender) < amount:
            return False

        self.accounts[sender]["balance"] -= amount
        self.accounts[sender]["nonce"] += 1

        if recipient not in self.accounts:
            self.accounts[recipient] = {"balance": 0, "nonce": 0}

        self.accounts[recipient]["balance"] += amount
        return True

Comparison Matrix

AspectUTXO ModelAccount Model
State representationSet of unspent outputsGlobal state tree
PrivacyBetter (new address per tx)Worse (reused addresses)
ParallelismNatural (independent UTXOs)Requires explicit handling
Smart contractsLimited (Bitcoin Script)Full support (EVM)
State growthUTXO set pruningRequires state management
VerificationLocal (check inputs)Global (check nonce, balance)
Double-spend checkImplicit (UTXO consumed)Explicit (nonce tracking)

State Management in Ethereum

State Trie

Ethereum maintains three main tries:

  1. State Trie - Maps addresses to account states
  2. Storage Trie - Per-account contract storage
  3. Transaction Trie - All transactions in a block
  4. Receipt Trie - Transaction execution results

State Transition Function

Where:

  • is the pre-transaction state
  • is the transaction
  • is the validation function
  • is the post-transaction state

State Pruning

python
class StatePruner:
    def __init__(self, state_trie, archive_depth=128):
        self.trie = state_trie
        self.archive_depth = archive_depth

    def prune(self, current_block: int):
        cutoff = current_block - self.archive_depth
        nodes_to_prune = self._find_old_state_nodes(cutoff)

        for node_hash in nodes_to_prune:
            self._remove_node(node_hash)

    def _find_old_state_nodes(self, before_block: int) -> list:
        # Identify nodes not referenced by recent state roots
        pass

    def _remove_node(self, node_hash: str):
        # Remove node from database
        pass

Hash Efficiency Analysis

Comparison of Hash Functions

AlgorithmOutput SizeBlock SizeSecuritySpeed (MB/s)
SHA-256256 bits512 bits128 bits~500
Keccak-256256 bits1088 bits128 bits~400
BLAKE2b512 bits128 bits256 bits~900
BLAKE3256 bits64 bits128 bits~2000

Hash Distribution Quality

python
import hashlib
from collections import Counter

def analyze_hash_distribution(hash_func, data_points: int = 10000):
    """Analyze bit distribution of hash function outputs."""
    hashes = []
    for i in range(data_points):
        h = hash_func(str(i).encode())
        hashes.append(h)

    # Count bit positions
    bit_counts = [0] * 256
    for h in hashes:
        for i, char in enumerate(h):
            byte = int(char, 16)
            for bit in range(4):
                if byte & (1 << bit):
                    bit_counts[i * 4 + bit] += 1

    # Calculate bias
    expected = data_points / 2
    max_bias = max(abs(c - expected) for c in bit_counts)

    return {
        "max_bias": max_bias,
        "bias_percentage": (max_bias / expected) * 100,
        "distribution_quality": "Good" if max_bias < expected * 0.1 else "Poor"
    }

# SHA-256 distribution
sha256_stats = analyze_hash_distribution(
    lambda x: hashlib.sha256(x).hexdigest()
)

# Keccak-256 distribution (simplified)
keccak_stats = analyze_hash_distribution(
    lambda x: hashlib.sha256(x).hexdigest()  # Placeholder
)

Avalanche Effect

A single bit change in input should flip approximately 50% of output bits.


Data Structure Selection Guide

What's your use case?Transaction VerificationState StorageKey-Value MappingMerkle TreePatricia TrieHash Map / TrieBitcoin, SPV proofsEthereum state, contractsUTXO sets, cachesChoose based on: query patterns, update frequency, proof requirements

Trade-offs

Merkle Tree Trade-offs

AdvantageDisadvantage
Efficient proofs Tree rebuild on updates
Compact representationNo key-based lookup
Tamper-evidentFixed structure

Patricia Trie Trade-offs

AdvantageDisadvantage
Key-based lookupsMore complex implementation
Prefix sharingHigher memory overhead
Efficient updatesHarder to reason about

UTXO vs Account Trade-offs

UTXO AdvantageAccount Advantage
Better privacySimpler programming model
Natural parallelismLower storage overhead
No nonce trackingEasier smart contracts
Explicit value trackingGlobal state queries

Real-World Examples

Bitcoin Merkle Tree

Bitcoin blocks contain up to ~4,000 transactions. The Merkle root enables SPV nodes to verify a transaction is included with only 12 hash comparisons:

Ethereum State Size

As of 2024, Ethereum's state trie contains:

  • ~110 million accounts
  • ~1.2 billion storage slots
  • ~800 GB total state size

Solana's AccountsDB

Solana uses a concurrent Merkle tree with hot storage for recent accounts and cold storage for historical data, achieving:

  • 400ms slot times
  • 65,000 TPS theoretical capacity

Interview Questions

Q1: Explain why Bitcoin uses Merkle Trees instead of simply hashing all transactions together.

Answer: A Merkle Tree provides several advantages:

  1. SPV Proofs: Light nodes can verify transaction inclusion with hashes instead of downloading the entire block
  2. Incremental Updates: New transactions can be added without recomputing all hashes
  3. Tamper Detection: Any change to a single transaction propagates to the root, but only affects one path in the tree
  4. Efficient Verification: Each transaction can be independently verified against the root

Q2: What is the advantage of Patricia Trie over a simple hash map for Ethereum state storage?

Answer: Patricia Tries provide:

  1. Cryptographic Proofs: Can generate compact proofs that an account exists or doesn't exist
  2. State Root: The root hash commits to the entire state without storing it all
  3. Prefix Sharing: Accounts with similar addresses share common prefixes, reducing storage
  4. Merkle Proofs: Enable light clients to verify specific account states

Q3: How does the UTXO model prevent double-spending differently than the account model?

Answer:

  • UTXO: Double-spending is prevented implicitly - each UTXO can only be consumed once. The network rejects any transaction that references an already-spent UTXO
  • Account Model: Double-spending is prevented via nonce tracking. Each account has a sequential nonce that must match the transaction nonce, preventing replay attacks

Quiz Questions

Q1: What is the time complexity of generating and verifying a Merkle proof for a tree with n leaves?

A) O(n) B) O(n log n) C) O(log n) D) O(1)

Answer: C) O(log n)

Q2: Which data structure does Ethereum use for its world state?

A) Binary Merkle Tree B) Modified Merkle Patricia Trie C) Red-Black Tree D) Hash Map

Answer: B) Modified Merkle Patricia Trie

Q3: In the UTXO model, what prevents a user from spending the same output twice?

A) Nonce tracking B) Account balance check C) UTXO consumption (spent outputs are removed) D) Smart contract validation

Answer: C) UTXO consumption (spent outputs are removed)


Practice

  1. Implement a Merkle Tree in Python that can generate and verify proofs
  2. Build a simple UTXO set manager that tracks spending
  3. Compare the storage requirements of a Merkle Tree vs Patricia Trie for 1 million key-value pairs
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
ā˜†ā˜†ā˜†ā˜†ā˜†
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement