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
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
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
| Property | Description | Complexity |
|---|---|---|
| Construction | Build tree from leaves | |
| Root computation | Single root hash | lookup |
| Proof generation | Path from leaf to root | |
| Proof verification | Recompute root from proof | |
| Space efficiency | Store 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
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
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
| Feature | Merkle Tree | Patricia Trie |
|---|---|---|
| Structure | Binary tree | Radix tree |
| Key storage | None (index-based) | Key-value pairs |
| Update complexity | rebuild | path |
| Prefix sharing | None | Automatic |
| Used in | Bitcoin blocks | Ethereum state |
| State proofs | Transaction inclusion | Account/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.
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)
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
}
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
| Aspect | UTXO Model | Account Model |
|---|---|---|
| State representation | Set of unspent outputs | Global state tree |
| Privacy | Better (new address per tx) | Worse (reused addresses) |
| Parallelism | Natural (independent UTXOs) | Requires explicit handling |
| Smart contracts | Limited (Bitcoin Script) | Full support (EVM) |
| State growth | UTXO set pruning | Requires state management |
| Verification | Local (check inputs) | Global (check nonce, balance) |
| Double-spend check | Implicit (UTXO consumed) | Explicit (nonce tracking) |
State Management in Ethereum
State Trie
Ethereum maintains three main tries:
- State Trie - Maps addresses to account states
- Storage Trie - Per-account contract storage
- Transaction Trie - All transactions in a block
- 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
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
| Algorithm | Output Size | Block Size | Security | Speed (MB/s) |
|---|---|---|---|---|
| SHA-256 | 256 bits | 512 bits | 128 bits | ~500 |
| Keccak-256 | 256 bits | 1088 bits | 128 bits | ~400 |
| BLAKE2b | 512 bits | 128 bits | 256 bits | ~900 |
| BLAKE3 | 256 bits | 64 bits | 128 bits | ~2000 |
Hash Distribution Quality
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
Trade-offs
Merkle Tree Trade-offs
| Advantage | Disadvantage |
|---|---|
| Efficient proofs | Tree rebuild on updates |
| Compact representation | No key-based lookup |
| Tamper-evident | Fixed structure |
Patricia Trie Trade-offs
| Advantage | Disadvantage |
|---|---|
| Key-based lookups | More complex implementation |
| Prefix sharing | Higher memory overhead |
| Efficient updates | Harder to reason about |
UTXO vs Account Trade-offs
| UTXO Advantage | Account Advantage |
|---|---|
| Better privacy | Simpler programming model |
| Natural parallelism | Lower storage overhead |
| No nonce tracking | Easier smart contracts |
| Explicit value tracking | Global 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:
- SPV Proofs: Light nodes can verify transaction inclusion with hashes instead of downloading the entire block
- Incremental Updates: New transactions can be added without recomputing all hashes
- Tamper Detection: Any change to a single transaction propagates to the root, but only affects one path in the tree
- 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:
- Cryptographic Proofs: Can generate compact proofs that an account exists or doesn't exist
- State Root: The root hash commits to the entire state without storing it all
- Prefix Sharing: Accounts with similar addresses share common prefixes, reducing storage
- 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
- Implement a Merkle Tree in Python that can generate and verify proofs
- Build a simple UTXO set manager that tracks spending
- Compare the storage requirements of a Merkle Tree vs Patricia Trie for 1 million key-value pairs