Blockchain Storage
LevelDB, state trie, receipt logs, archival vs full nodes, data pruning, state channels, and storage costs.
Overview
Blockchain storage is critical for maintaining decentralized state while ensuring efficient data retrieval and verification. Different storage strategies balance completeness, cost, and performance.
Storage Architecture
Ethereum Storage Layers
Storage Layer Implementation
import json
import hashlib
import time
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
from collections import OrderedDict
@dataclass
class AccountState:
"""Ethereum account state."""
nonce: int = 0
balance: int = 0
storage_root: str = ""
code_hash: str = ""
def to_dict(self) -> dict:
return {
'nonce': self.nonce,
'balance': self.balance,
'storageRoot': self.storage_root,
'codeHash': self.code_hash
}
class LevelDBSimulator:
"""Simulated LevelDB key-value store."""
def __init__(self):
self.data: Dict[str, bytes] = {}
self.write_buffer: Dict[str, bytes] = {}
self.stats = {
'reads': 0,
'writes': 0,
'deletes': 0
}
def get(self, key: bytes) -> Optional[bytes]:
"""Get value by key."""
self.stats['reads'] += 1
key_str = key.hex()
# Check write buffer first
if key_str in self.write_buffer:
return self.write_buffer[key_str]
return self.data.get(key_str)
def put(self, key: bytes, value: bytes):
"""Put key-value pair."""
self.stats['writes'] += 1
self.write_buffer[key.hex()] = value
def delete(self, key: bytes):
"""Delete key."""
self.stats['deletes'] += 1
key_str = key.hex()
if key_str in self.data:
del self.data[key_str]
self.write_buffer.pop(key_str, None)
def commit(self):
"""Commit write buffer to main store."""
self.data.update(self.write_buffer)
self.write_buffer.clear()
def get_stats(self) -> dict:
return self.stats.copy()
# Example
db = LevelDBSimulator()
key = hashlib.sha256(b"test_key").digest()
db.put(key, b"test_value")
db.commit()
print(f"Retrieved: {db.get(key)}")
State Trie
Modified Merkle Patricia Trie
Ethereum uses a Modified Merkle Patricia Trie (MPT) for state storage.
import hashlib
from typing import Optional, Dict, Tuple
class TrieNode:
"""MPT trie node."""
def __init__(self):
self.children: Dict[str, 'TrieNode'] = {}
self.is_leaf: bool = False
self.value: bytes = b''
self.hash: Optional[str] = None
class ModifiedMerklePatriciaTrie:
"""Modified Merkle Patricia Trie implementation."""
def __init__(self):
self.root = TrieNode()
self.node_cache: Dict[str, TrieNode] = {}
def insert(self, key: str, value: bytes):
"""Insert key-value pair."""
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
node.hash = None # Invalidate hash
def get(self, key: str) -> Optional[bytes]:
"""Get value by key."""
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:
"""Compute root hash of trie."""
return self._hash_node(self.root)
def _hash_node(self, node: TrieNode) -> str:
"""Hash node and its children."""
if node.hash:
return node.hash
if node.is_leaf:
node.hash = hashlib.sha256(node.value).hexdigest()
elif not node.children:
node.hash = hashlib.sha256(b'').hexdigest()
else:
combined = b''
for char in sorted(node.children.keys()):
child_hash = self._hash_node(node.children[char])
combined += child_hash.encode()
node.hash = hashlib.sha256(combined).hexdigest()
return node.hash
def generate_proof(self, key: str) -> list:
"""Generate Merkle proof for key."""
proof = []
node = self.root
for char in key:
if char not in node.children:
return []
siblings = {
k: self._hash_node(v)
for k, v in node.children.items()
if k != char
}
proof.append({
'type': 'branch',
'siblings': siblings
})
node = node.children[char]
proof.append({
'type': 'leaf',
'hash': self._hash_node(node)
})
return proof
def verify_proof(self, key: str, value: bytes, proof: list, root_hash: str) -> bool:
"""Verify Merkle proof."""
current_hash = hashlib.sha256(value).hexdigest()
for item in reversed(proof):
if item['type'] == 'leaf':
if item['hash'] != current_hash:
return False
elif item['type'] == 'branch':
combined = current_hash.encode()
for sibling_hash in item['siblings'].values():
combined += sibling_hash.encode()
current_hash = hashlib.sha256(combined).hexdigest()
return current_hash == root_hash
# Example
trie = ModifiedMerklePatriciaTrie()
# Insert accounts
accounts = {
'a1b2c3': AccountState(nonce=5, balance=1000),
'a1b2d4': AccountState(nonce=2, balance=500),
'b3c4d5': AccountState(nonce=1, balance=2000),
}
for addr, state in accounts.items():
trie.insert(addr, json.dumps(state.to_dict()).encode())
root_hash = trie.compute_root_hash()
print(f"Root hash: {root_hash[:16]}...")
# Generate and verify proof
proof = trie.generate_proof('a1b2c3')
print(f"Proof length: {len(proof)} nodes")
State Trie Optimization
class StateTrieOptimizer:
"""Optimize state trie storage."""
def __init__(self, trie: ModifiedMerklePatriciaTrie):
self.trie = trie
self.node_store = {}
self.ref_counts = {}
def flatten_trie(self) -> Dict[str, str]:
"""Flatten trie to node storage format."""
node_hashes = {}
self._flatten_node(self.trie.root, node_hashes)
return node_hashes
def _flatten_node(self, node: TrieNode, store: Dict[str, str]):
"""Recursively flatten node to storage."""
node_hash = self.trie._hash_node(node)
store[node_hash] = self._encode_node(node)
for child in node.children.values():
self._flatten_node(child, store)
def _encode_node(self, node: TrieNode) -> str:
"""Encode node for storage."""
if node.is_leaf:
return f"leaf:{node.value.hex()}"
else:
children = {
k: self.trie._hash_node(v)
for k, v in node.children.items()
}
return f"branch:{json.dumps(children)}"
def prune_old_nodes(self, current_root: str, old_roots: list):
"""Prune nodes not referenced by current state."""
# Mark all nodes reachable from current root
reachable = set()
self._mark_reachable(current_root, reachable)
# Find nodes only in old roots
old_only = set()
for old_root in old_roots:
self._mark_reachable(old_root, old_only)
old_only -= reachable
# Remove old-only nodes
pruned = 0
for node_hash in old_only:
if node_hash in self.node_store:
del self.node_store[node_hash]
pruned += 1
return pruned
def _mark_reachable(self, node_hash: str, reachable: set):
"""Mark all nodes reachable from given hash."""
if node_hash in reachable:
return
reachable.add(node_hash)
# In real implementation, decode node and recurse
# This is simplified
Receipt Logs
Transaction Receipt Structure
from dataclasses import dataclass
from typing import List
@dataclass
class Log:
"""Event log from transaction execution."""
address: str
topics: List[str]
data: bytes
block_number: int
tx_hash: str
tx_index: int
block_hash: str
log_index: int
@dataclass
class TransactionReceipt:
"""Transaction receipt."""
tx_hash: str
block_hash: str
block_number: int
status: int # 0 = failure, 1 = success
cumulative_gas_used: int
gas_used: int
contract_address: str
logs: List[Log]
logs_bloom: bytes
def to_dict(self) -> dict:
return {
'transactionHash': self.tx_hash,
'blockHash': self.block_hash,
'blockNumber': hex(self.block_number),
'status': hex(self.status),
'cumulativeGasUsed': hex(self.cumulative_gas_used),
'gasUsed': hex(self.gas_used),
'contractAddress': self.contract_address or '',
'logs': [
{
'address': log.address,
'topics': log.topics,
'data': log.data.hex(),
'blockNumber': hex(log.block_number),
'transactionHash': log.tx_hash,
'logIndex': hex(log.log_index)
}
for log in self.logs
]
}
class ReceiptManager:
"""Manage transaction receipts."""
def __init__(self):
self.receipts: Dict[str, TransactionReceipt] = {}
self.blooms: Dict[int, bytes] = {}
def store_receipt(self, receipt: TransactionReceipt):
"""Store transaction receipt."""
self.receipts[receipt.tx_hash] = receipt
# Store bloom filter for block
if receipt.block_number not in self.blooms:
self.blooms[receipt.block_number] = receipt.logs_bloom
else:
self.blooms[receipt.block_number] = self._or_blooms(
self.blooms[receipt.block_number],
receipt.logs_bloom
)
def get_receipt(self, tx_hash: str) -> Optional[TransactionReceipt]:
"""Get receipt by transaction hash."""
return self.receipts.get(tx_hash)
def get_logs(self, filter_criteria: dict) -> List[Log]:
"""Get logs matching filter criteria."""
logs = []
for receipt in self.receipts.values():
if filter_criteria.get('fromBlock', 0) > receipt.block_number:
continue
if filter_criteria.get('toBlock', float('inf')) < receipt.block_number:
continue
for log in receipt.logs:
if filter_criteria.get('address') and log.address != filter_criteria['address']:
continue
if filter_criteria.get('topics'):
if not self._topics_match(log.topics, filter_criteria['topics']):
continue
logs.append(log)
return logs
def _or_blooms(self, bloom1: bytes, bloom2: bytes) -> bytes:
"""Bitwise OR of two bloom filters."""
return bytes(a | b for a, b in zip(bloom1, bloom2))
def _topics_match(self, log_topics: list, filter_topics: list) -> bool:
"""Check if log topics match filter."""
for i, topic in enumerate(filter_topics):
if topic and topic != log_topics[i]:
return False
return True
Bloom Filter for Logs
class BloomFilter:
"""Bloom filter for efficient log filtering."""
def __init__(self, size: int = 256, num_hashes: int = 3):
self.size = size
self.num_hashes = num_hashes
self.bits = [0] * (size * 8) # 2048 bits
def add(self, item: bytes):
"""Add item to bloom filter."""
for i in range(self.num_hashes):
hash_result = hashlib.sha256(item + i.to_bytes(4, 'big')).digest()
index = int.from_bytes(hash_result[:4], 'big') % len(self.bits)
self.bits[index] = 1
def might_contain(self, item: bytes) -> bool:
"""Check if item might be in the filter."""
for i in range(self.num_hashes):
hash_result = hashlib.sha256(item + i.to_bytes(4, 'big')).digest()
index = int.from_bytes(hash_result[:4], 'big') % len(self.bits)
if self.bits[index] == 0:
return False
return True
def merge(self, other: 'BloomFilter') -> 'BloomFilter':
"""Merge two bloom filters."""
result = BloomFilter(self.size, self.num_hashes)
result.bits = [a | b for a, b in zip(self.bits, other.bits)]
return result
Node Types
Node Comparison Matrix
| Node Type | Stores | Sync Time | Storage | Use Case |
|---|---|---|---|---|
| Full Node | Blockchain + State | Days | ~1TB | Validation |
| Archive Node | Everything forever | Weeks | ~12TB | Historical queries |
| Light Node | Headers only | Minutes | ~50MB | Mobile wallets |
| Pruned Node | Recent state | Hours | ~500GB | Reduced storage |
| Staking Node | Full state | Days | ~1TB | Consensus |
Node Implementation
class NodeType:
"""Different node storage configurations."""
def __init__(self, node_type: str):
self.node_type = node_type
self.config = self._get_config()
def _get_config(self) -> dict:
"""Get storage configuration for node type."""
configs = {
'full': {
'store_blockchain': True,
'store_state': True,
'store_receipts': True,
'state_pruning': False,
'archive_mode': False,
'retention_blocks': 0, # All blocks
'estimated_size': '1TB'
},
'archive': {
'store_blockchain': True,
'store_state': True,
'store_receipts': True,
'state_pruning': False,
'archive_mode': True,
'retention_blocks': 0,
'estimated_size': '12TB'
},
'light': {
'store_blockchain': False,
'store_state': False,
'store_receipts': False,
'state_pruning': True,
'archive_mode': False,
'retention_blocks': 0,
'estimated_size': '50MB'
},
'pruned': {
'store_blockchain': True,
'store_state': True,
'store_receipts': True,
'state_pruning': True,
'archive_mode': False,
'retention_blocks': 128,
'estimated_size': '500GB'
}
}
return configs.get(self.node_type, configs['full'])
def calculate_storage(self, block_count: int) -> dict:
"""Calculate estimated storage requirements."""
# Approximate sizes
bytes_per_block = 50000 # 50KB average
bytes_per_receipt = 500 # 500B average
bytes_per_state_entry = 200 # 200B average
storage = {}
if self.config['store_blockchain']:
storage['blockchain'] = block_count * bytes_per_block
if self.config['store_state']:
# State is relative to current state, not blocks
storage['state'] = 800 * 1024 * 1024 * 1024 # 800GB
if self.config['store_receipts']:
storage['receipts'] = block_count * bytes_per_receipt
if self.config['archive_mode']:
storage['historical_state'] = block_count * bytes_per_state_entry
return storage
# Example
for node_type in ['full', 'archive', 'light', 'pruned']:
node = NodeType(node_type)
storage = node.calculate_storage(18000000) # 18M blocks
total = sum(storage.values())
print(f"{node_type:10}: {total/1024**3:.1f} GB")
Data Pruning
State Pruning Strategy
class StatePruner:
"""Prune old state data."""
def __init__(self, retention_blocks: int = 128):
self.retention_blocks = retention_blocks
self.state_versions = {} # block_number -> state_root
self.pruned_count = 0
def register_state(self, block_number: int, state_root: str):
"""Register new state version."""
self.state_versions[block_number] = state_root
def prune(self, current_block: int) -> dict:
"""Prune old state versions."""
cutoff = current_block - self.retention_blocks
to_prune = [
block for block in self.state_versions.keys()
if block < cutoff
]
pruned = {}
for block in to_prune:
state_root = self.state_versions.pop(block)
# In real implementation, would delete trie nodes
pruned[block] = state_root
self.pruned_count += 1
return {
'pruned_blocks': len(to_prune),
'pruned_nodes': self.pruned_count,
'remaining_versions': len(self.state_versions)
}
def estimate_savings(self, nodes_per_state: int = 1000000,
bytes_per_node: int = 200) -> dict:
"""Estimate storage savings from pruning."""
retained_versions = self.retention_blocks
pruned_versions = max(0, len(self.state_versions) - retained_versions)
savings = pruned_versions * nodes_per_state * bytes_per_node
return {
'retained_versions': retained_versions,
'pruned_versions': pruned_versions,
'estimated_savings_gb': savings / (1024**3)
}
# Example
pruner = StatePruner(retention_blocks=128)
# Simulate state versions
for i in range(200):
pruner.register_state(i, f"state_root_{i}")
result = pruner.prune(200)
print(f"Pruned: {result}")
savings = pruner.estimate_savings()
print(f"Estimated savings: {savings['estimated_savings_gb']:.1f} GB")
Block Pruning
class BlockPruner:
"""Prune old block data."""
def __init__(self, keep_blocks: int = 100000):
self.keep_blocks = keep_blocks
self.block_index = {} # block_number -> block_hash
self.pruned_blocks = set()
def register_block(self, block_number: int, block_hash: str):
"""Register new block."""
self.block_index[block_number] = block_hash
def prune(self, current_block: int) -> dict:
"""Prune old blocks."""
cutoff = current_block - self.keep_blocks
to_prune = [
block for block in self.block_index.keys()
if block < cutoff
]
for block in to_prune:
self.pruned_blocks.add(block)
del self.block_index[block]
return {
'pruned_count': len(to_prune),
'remaining_blocks': len(self.block_index),
'pruned_total': len(self.pruned_blocks)
}
def can_serve_block(self, block_number: int) -> bool:
"""Check if node can serve a specific block."""
return block_number in self.block_index
State Channels
State Channel Storage
from dataclasses import dataclass
from typing import List, Optional
import hashlib
@dataclass
class ChannelState:
"""State channel state."""
channel_id: str
participants: List[str]
balances: dict
nonce: int
is_open: bool
@dataclass
class StateUpdate:
"""State channel update."""
channel_id: str
nonce: int
balances: dict
signatures: List[bytes]
timestamp: float
class StateChannel:
"""State channel implementation."""
def __init__(self, channel_id: str, participants: List[str],
initial_balances: dict):
self.channel_id = channel_id
self.participants = participants
self.current_state = ChannelState(
channel_id=channel_id,
participants=participants,
balances=initial_balances,
nonce=0,
is_open=True
)
self.state_history: List[StateUpdate] = []
def update_state(self, new_balances: dict, signatures: List[bytes]) -> bool:
"""Update channel state."""
if not self.current_state.is_open:
return False
# Verify signatures
if not self._verify_signatures(new_balances, signatures):
return False
# Update state
new_nonce = self.current_state.nonce + 1
self.current_state.balances = new_balances
self.current_state.nonce = new_nonce
# Store update
update = StateUpdate(
channel_id=self.channel_id,
nonce=new_nonce,
balances=new_balances,
signatures=signatures,
timestamp=time.time()
)
self.state_history.append(update)
return True
def close_channel(self) -> dict:
"""Close channel and settle balances."""
self.current_state.is_open = False
return {
'channel_id': self.channel_id,
'final_balances': self.current_state.balances,
'final_nonce': self.current_state.nonce,
'settlement_time': time.time()
}
def get_proof(self, nonce: int) -> Optional[StateUpdate]:
"""Get proof for specific state."""
for update in self.state_history:
if update.nonce == nonce:
return update
return None
def _verify_signatures(self, balances: dict, signatures: List[bytes]) -> bool:
"""Verify participant signatures."""
# Simplified verification
return len(signatures) == len(self.participants)
# Example
channel = StateChannel(
channel_id="ch_123",
participants=["alice", "bob"],
initial_balances={"alice": 100, "bob": 100}
)
# Update state
channel.update_state(
new_balances={"alice": 90, "bob": 110},
signatures=[b"sig1", b"sig2"]
)
print(f"Channel state: nonce={channel.current_state.nonce}")
print(f"Balances: {channel.current_state.balances}")
# Close channel
settlement = channel.close_channel()
print(f"Settlement: {settlement}")
State Channel Benefits
| Aspect | On-Chain | State Channel |
|---|---|---|
| Latency | 12 sec | Instant |
| Cost | Gas fees | Near zero |
| Privacy | Public | Private |
| Scalability | Limited | High |
| Finality | After confirmation | Immediate |
Storage Costs Analysis
Cost Comparison
class StorageCostAnalyzer:
"""Analyze storage costs across chains."""
def __init__(self):
self.chains = {}
def add_chain(self, name: str, cost_per_gb: float,
avg_block_size: float, block_time: float):
"""Add chain cost data."""
self.chains[name] = {
'cost_per_gb': cost_per_gb,
'avg_block_size': avg_block_size,
'block_time': block_time
}
def calculate_annual_cost(self, chain_name: str) -> dict:
"""Calculate annual storage cost."""
chain = self.chains[chain_name]
# Blocks per year
blocks_per_year = 365 * 24 * 3600 / chain['block_time']
# Data per year in GB
data_per_year_gb = (
blocks_per_year * chain['avg_block_size'] / (1024**3)
)
# Cost per year
cost_per_year = data_per_year_gb * chain['cost_per_gb']
return {
'chain': chain_name,
'blocks_per_year': int(blocks_per_year),
'data_per_year_gb': data_per_year_gb,
'cost_per_year': cost_per_year
}
def compare_chains(self) -> dict:
"""Compare storage costs across chains."""
comparisons = {}
for chain_name in self.chains:
comparisons[chain_name] = self.calculate_annual_cost(chain_name)
return comparisons
# Example
analyzer = StorageCostAnalyzer()
analyzer.add_chain('Bitcoin', 0.02, 0.001, 600) # $0.02/GB, 1MB block, 10min
analyzer.add_chain('Ethereum', 0.05, 0.0001, 12) # $0.05/GB, 100KB block, 12s
analyzer.add_chain('Solana', 0.01, 0.00001, 0.4) # $0.01/GB, 10KB block, 0.4s
comparison = analyzer.compare_chains()
for chain, costs in comparison.items():
print(f"{chain:12}: ${costs['cost_per_year']:.2f}/year for {costs['data_per_year_gb']:.2f} GB")
Storage Optimization Strategies
| Strategy | Description | Savings |
|---|---|---|
| Compression | Compress block data | 50-70% |
| Pruning | Remove old state | 80-90% |
| Sharding | Distribute storage | 90%+ |
| State channels | Off-chain state | 99%+ |
| Zero-knowledge | Verify without storing | 95%+ |
Trade-offs
Storage Trade-offs
| Aspect | Full Storage | Pruned Storage |
|---|---|---|
| Completeness | Complete history | Recent state only |
| Query capability | All historical queries | Limited queries |
| Storage cost | High | Low |
| Sync time | Long | Short |
| Network support | Full validation | Partial validation |
Node Type Trade-offs
| Node Type | Pros | Cons |
|---|---|---|
| Full | Complete validation | High storage |
| Archive | Historical queries | Very high storage |
| Light | Low storage | Limited functionality |
| Pruned | Reduced storage | Limited history |
Real-World Examples
Bitcoin Storage
- Full blockchain: ~500 GB
- UTXO set: ~5 GB
- Pruned nodes: ~550 MB minimum
- Growth rate: ~50 GB/year
Ethereum Storage
- Full node: ~1 TB
- State trie: ~800 GB
- Archive node: ~12 TB
- Growth rate: ~300 GB/year
Solana Storage
- Full node: ~5 TB
- Ledger: ~20 TB (with full history)
- Growth rate: ~1 TB/year
Interview Questions
Q1: Explain the difference between a full node and an archive node in Ethereum.
Answer:
| Aspect | Full Node | Archive Node |
|---|---|---|
| State Storage | Current state only | All historical states |
| Block Storage | All blocks | All blocks |
| Query Capability | Current + recent history | Any historical state |
| Storage Required | ~1 TB | ~12 TB |
| Sync Time | Days | Weeks |
| Use Case | Validation, staking | Historical analytics, explorers |
| State Pruning | Yes (old states deleted) | No (all states retained) |
Full nodes can validate current transactions but cannot answer queries about historical states (e.g., "What was Alice's balance at block 1,000,000?"). Archive nodes retain all historical states for such queries.
Q2: How does state pruning work and what are its trade-offs?
Answer: State pruning removes old state trie nodes that are no longer needed for current state validation.
How it works:
- Keep state roots for recent blocks (e.g., last 128)
- Identify nodes only referenced by old states
- Delete unreferenced nodes
- Maintain current state trie integrity
Trade-offs:
- Saves: 80-90% storage
- Loses: Ability to query historical states
- Risk: Cannot serve as archive node
- Benefit: Reduced hardware requirements
Q3: What is the storage cost difference between storing data on-chain vs state channels?
Answer:
| Metric | On-Chain | State Channel |
|---|---|---|
| Cost per transaction | ~0.0001 | |
| Storage per state | ~200 bytes on-chain | 0 bytes (off-chain) |
| Latency | 12 seconds | Instant |
| Privacy | Public | Private |
| Finality | After confirmation | Immediate |
For high-frequency applications (e.g., micropayments, gaming), state channels can reduce storage costs by 99%+ while improving latency and privacy.
Quiz Questions
Q1: What data structure does Ethereum use for its world state?
A) Hash Map B) Red-Black Tree C) Modified Merkle Patricia Trie D) Skip List
Answer: C) Modified Merkle Patricia Trie
Q2: How much storage does a typical Ethereum archive node require?
A) 100 GB B) 500 GB C) 1 TB D) 12 TB
Answer: D) 12 TB
Q3: What is the primary benefit of state channels for blockchain storage?
A) Compress on-chain data B) Reduce gas costs C) Move state off-chain D) Improve consensus speed
Answer: C) Move state off-chain
Practice
- Implement a simple state trie and measure storage efficiency
- Compare storage costs across different blockchain networks
- Build a state channel simulator with balance updates
- Analyze the impact of pruning on node storage requirements