Blockchain Security
51% attacks, double spending, MEV, front-running, sandwich attacks, reentrancy, and common vulnerabilities.
Overview
Blockchain security encompasses protecting decentralized systems from attacks, vulnerabilities, and exploits. Understanding these threats is crucial for building secure protocols and applications.
51% Attacks
Attack Description
A 51% attack occurs when an entity controls majority of network hash power (PoW) or stake (PoS), enabling them to manipulate the blockchain.
Attack Vectors
51% Attack Simulation
import random
from dataclasses import dataclass
from typing import List
@dataclass
class Blockchain:
"""Simulated blockchain for attack analysis."""
blocks: List[dict]
difficulty: int
class FiftyOnePercentAttack:
"""Simulate 51% attack."""
def __init__(self, attacker_hashrate: float, total_hashrate: float):
self.attacker_hashrate = attacker_hashrate
self.total_hashrate = total_hashrate
self.hash_rate_ratio = attacker_hashrate / total_hashrate
def calculate_success_probability(self, confirmations: int) -> float:
"""Calculate probability of catching up to N confirmations."""
p = self.hash_rate_ratio
q = 1 - p
if q == 0:
return 1.0
# Probability of catching up
if p <= 0.5:
# Formula: (q/p)^n
return (q / p) ** confirmations
else:
return 1.0
def simulate_double_spend(self, amount: float,
confirmations: int) -> dict:
"""Simulate double spend attack."""
success_prob = self.calculate_success_probability(confirmations)
# Monte Carlo simulation
trials = 10000
successes = 0
for _ in range(trials):
attacker_blocks = 0
honest_blocks = 0
while honest_blocks < confirmations:
# Simulate block race
if random.random() < self.hash_rate_ratio:
attacker_blocks += 1
else:
honest_blocks += 1
# Check if attacker caught up
if attacker_blocks > honest_blocks:
successes += 1
break
actual_prob = successes / trials
return {
'amount': amount,
'confirmations': confirmations,
'attacker_hashrate': f"{self.hash_rate_ratio*100:.1f}%",
'theoretical_probability': f"{success_prob*100:.2f}%",
'simulated_probability': f"{actual_prob*100:.2f}%",
'expected_loss': amount * success_prob
}
# Example
attack = FiftyOnePercentAttack(attacker_hashrate=55, total_hashrate=100)
# Test different confirmation levels
for confirmations in [1, 3, 6, 12]:
result = attack.simulate_double_spend(
amount=10.0,
confirmations=confirmations
)
print(f"{confirmations} confirmations: "
f"Success prob = {result['simulated_probability']}, "
f"Expected loss = ${result['expected_loss']:.2f}")
Double Spending
Attack Types
class DoubleSpendAttack:
"""Different double spending attack vectors."""
def __init__(self):
self.attack_history = []
def race_attack(self, amount: float) -> dict:
"""Race attack - send two conflicting transactions."""
return {
'type': 'race',
'description': 'Broadcast two conflicting txs simultaneously',
'success_rate': 'High with low confirmations',
'mitigation': 'Wait for confirmations',
'amount': amount
}
def finney_attack(self, amount: float) -> dict:
"""Finney attack - pre-mined block with double spend."""
return {
'type': 'finney',
'description': 'Pre-mine block containing double spend',
'requirements': 'Control mining power',
'success_rate': 'Moderate',
'mitigation': 'Wait for multiple confirmations',
'amount': amount
}
def vector76_attack(self, amount: float) -> dict:
"""Vector76 - combine race and Finney attacks."""
return {
'type': 'vector76',
'description': 'One-block double spend',
'requirements': 'Mining power + merchant cooperation',
'success_rate': 'Low to moderate',
'mitigation': 'More confirmations',
'amount': amount
}
def analyze_vulnerability(self, confirmation_time: float,
block_time: float) -> dict:
"""Analyze double spend vulnerability."""
# Risk decreases exponentially with confirmations
risk_per_block = 0.1 # 10% risk per block
risk_after_n = risk_per_block ** (confirmation_time / block_time)
return {
'confirmation_time': confirmation_time,
'block_time': block_time,
'risk_after_1_block': f"{risk_per_block*100:.1f}%",
'risk_after_6_blocks': f"{(risk_per_block**6)*100:.4f}%",
'recommended_confirmations': int(-0.01 / (risk_per_block * block_time))
}
# Example
double_spend = DoubleSpendAttack()
analysis = double_spend.analyze_vulnerability(
confirmation_time=60, # 60 minutes
block_time=10 # 10 minutes
)
print(f"Double spend risk analysis: {analysis}")
MEV (Maximal Extractable Value)
MEV Definition
MEV is the maximum value that can be extracted from block production by including, excluding, or reordering transactions.
MEV Categories
class MEVCategories:
"""Categories of MEV extraction."""
def __init__(self):
self.categories = {
'front_running': {
'description': 'Place transaction before known future tx',
'examples': ['DEX trades', 'NFT mints', 'Oracle updates'],
'profit_mechanism': 'Price movement prediction'
},
'back_running': {
'description': 'Place transaction after known future tx',
'examples': ['Arbitrage after large trades', 'Liquidations'],
'profit_mechanism': 'Exploit price impact'
},
'sandwich_attacks': {
'description': 'Front and back run victim tx',
'examples': ['DEX liquidity manipulation'],
'profit_mechanism': 'Price manipulation'
},
'liquidations': {
'description': 'Liquidate undercollateralized positions',
'examples': ['DeFi lending protocols'],
'profit_mechanism': 'Liquidation bonuses'
},
'arbitrage': {
'description': 'Exploit price differences',
'examples': ['Cross-DEX arbitrage', 'Cross-chain'],
'profit_mechanism': 'Price convergence'
}
}
def estimate_mev(self, category: str, params: dict) -> dict:
"""Estimate MEV opportunity."""
estimates = {
'front_running': params.get('trade_size', 0) * 0.01,
'back_running': params.get('price_impact', 0) * 0.1,
'sandwich_attacks': params.get('trade_size', 0) * 0.03,
'liquidations': params.get('debt_amount', 0) * 0.05,
'arbitrage': params.get('price_difference', 0) * params.get('volume', 0)
}
return {
'category': category,
'estimated_profit': estimates.get(category, 0),
'risk_level': 'High' if category == 'sandwich_attacks' else 'Medium'
}
# Example
mev = MEVCategories()
print("MEV Categories:")
for cat, info in mev.categories.items():
print(f" {cat}: {info['description']}")
MEV Protection Mechanisms
| Mechanism | Description | Effectiveness |
|---|---|---|
| Private mempools | Hide transactions from public | High |
| Commit-reveal | Submit hash first, reveal later | Medium |
| Batch auctions | Process transactions simultaneously | High |
| MEV-Share | Distribute MEV to users | Medium |
| Slippage limits | Limit price impact | Low |
Front-Running
Attack Description
Front-running occurs when an attacker observes a pending transaction and places their own transaction before it.
Front-Running Implementation
from dataclasses import dataclass
from typing import List, Tuple
import time
@dataclass
class PendingTransaction:
"""Pending transaction in mempool."""
tx_hash: str
from_address: str
to_address: str
value: float
gas_price: float
data: bytes
timestamp: float
class FrontRunningAttack:
"""Simulate front-running attack."""
def __init__(self, attacker_address: str, gas_budget: float):
self.attacker = attacker_address
self.gas_budget = gas_budget
def detect_opportunity(self, pending_txs: List[PendingTransaction]) -> dict:
"""Detect front-running opportunity."""
opportunities = []
for tx in pending_txs:
# Look for DEX trades
if self._is_dex_trade(tx):
expected_profit = self._estimate_profit(tx)
gas_cost = tx.gas_price * 100000 # Estimated gas
if expected_profit > gas_cost:
opportunities.append({
'target_tx': tx.tx_hash,
'expected_profit': expected_profit,
'gas_cost': gas_cost,
'net_profit': expected_profit - gas_cost
})
return {
'opportunities': len(opportunities),
'best_opportunity': max(opportunities, key=lambda x: x['net_profit'])
if opportunities else None
}
def create_front_run(self, target_tx: PendingTransaction,
trade_amount: float) -> dict:
"""Create front-running transaction."""
# Calculate gas price (higher than target)
front_run_gas = target_tx.gas_price * 1.5
return {
'type': 'front_run',
'attacker': self.attacker,
'target': target_tx.tx_hash,
'trade_amount': trade_amount,
'gas_price': front_run_gas,
'expected_profit': trade_amount * 0.01
}
def _is_dex_trade(self, tx: PendingTransaction) -> bool:
"""Check if transaction is a DEX trade."""
# Simplified check for DEX router contracts
dex_routers = [
"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", # Uniswap V2
"0xE592427A0AEce92De3Edee1F18E0157C05861564", # Uniswap V3
]
return tx.to_address.lower() in [r.lower() for r in dex_routers]
def _estimate_profit(self, target_tx: PendingTransaction) -> float:
"""Estimate profit from front-running."""
# Simplified profit estimation
return target_tx.value * 0.005 # 0.5% of trade value
# Example
frunner = FrontRunningAttack(
attacker_address="0xAttacker",
gas_budget=1000000000000000000 # 1 ETH
)
# Simulate pending transactions
pending = [
PendingTransaction(
tx_hash="0x123",
from_address="0xVictim",
to_address="0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D",
value=100000,
gas_price=50,
data=b"",
timestamp=time.time()
)
]
opportunity = frunner.detect_opportunity(pending)
print(f"Front-running opportunities: {opportunity['opportunities']}")
Front-Running Protection
| Method | Description | Trade-off |
|---|---|---|
| Commit-reveal | Submit hash, then reveal | Added latency |
| Private mempool | Hidden transactions | Centralization |
| Batch auctions | Process together | Complex |
| MEV-Share | Distribute profits | New protocol |
Sandwich Attacks
Attack Mechanism
A sandwich attack places transactions before and after a victim's trade to profit from price manipulation.
class SandwichAttack:
"""Simulate sandwich attack on DEX."""
def __init__(self, attacker: str, initial_liquidity: float):
self.attacker = attacker
self.initial_liquidity = initial_liquidity
def calculate_attack(self, victim_trade: float,
pool_fee: float = 0.003) -> dict:
"""Calculate sandwich attack parameters."""
# Simplified AMM math (x * y = k)
x = self.initial_liquidity
y = self.initial_liquidity
# Front-run: buy before victim
front_run_amount = victim_trade * 0.1 # 10% of victim trade
# Price after front-run
new_x = x - front_run_amount
new_y = (x * y) / new_x
price_after_buy = new_y / new_x
# Victim trade executes at worse price
victim_amount_out = victim_trade * (new_x / (new_x + victim_trade))
new_x_after_victim = new_x + victim_trade
new_y_after_victim = (x * y) / new_x_after_victim
# Back-run: sell after victim
back_run_amount = front_run_amount + victim_amount_out * 0.01
final_x = new_x_after_victim - back_run_amount
final_y = (x * y) / final_x
# Calculate profit
profit = back_run_amount - front_run_amount
return {
'victim_trade': victim_trade,
'front_run_amount': front_run_amount,
'price_impact': f"{((price_after_buy - 1) * 100):.2f}%",
'victim_loss': f"{(victim_trade * 0.003):.2f}",
'attacker_profit': f"{profit:.2f}",
'gas_cost_estimate': '0.01-0.05 ETH',
'net_profit': f"{profit - 0.02:.2f}"
}
def simulate_attack_sequence(self, victim_trade: float) -> list:
"""Simulate full attack sequence."""
steps = [
{
'step': 1,
'action': 'Front-run buy',
'description': f'Buy {victim_trade * 0.1:.2f} tokens'
},
{
'step': 2,
'action': 'Victim trade',
'description': f'Victim buys at higher price'
},
{
'step': 3,
'action': 'Back-run sell',
'description': 'Sell tokens for profit'
},
{
'step': 4,
'action': 'Collect profit',
'description': 'Net profit from price manipulation'
}
]
return steps
# Example
sandwich = SandwichAttack(attacker="0xAttacker", initial_liquidity=1000000)
result = sandwich.calculate_attack(victim_trade=10000)
print(f"Sandwich attack analysis:")
print(f" Victim trade: ${result['victim_trade']}")
print(f" Price impact: {result['price_impact']}")
print(f" Attacker profit: ${result['attacker_profit']}")
Reentrancy Attacks
Vulnerability Description
Reentrancy occurs when a contract calls an external contract before updating its state, allowing recursive calls.
Reentrancy Implementation
// Vulnerable contract (DO NOT USE)
contract VulnerableVault {
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw() public {
uint256 balance = balances[msg.sender];
require(balance > 0);
// Vulnerable: external call before state update
(bool success, ) = msg.sender.call{value: balance}("");
require(success);
balances[msg.sender] = 0; // State update after call
}
}
// Attack contract
contract ReentrancyAttack {
VulnerableVault vault;
function attack() external payable {
vault.deposit{value: msg.value}();
vault.withdraw();
}
receive() external payable {
if (address(vault).balance >= 1 ether) {
vault.withdraw(); // Re-enter before balance is zeroed
}
}
}
// Secure contract
contract SecureVault {
mapping(address => uint256) public balances;
bool private locked;
modifier noReentrant() {
require(!locked, "No reentrancy");
locked = true;
_;
locked = false;
}
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw() public noReentrant {
uint256 balance = balances[msg.sender];
require(balance > 0);
balances[msg.sender] = 0; // State update BEFORE call
(bool success, ) = msg.sender.call{value: balance}("");
require(success);
}
}
Reentrancy Prevention
class ReentrancyGuard:
"""Reentrancy protection patterns."""
def __init__(self):
self.locked = False
def check_reentrancy(self, contract_state: dict,
external_call: callable) -> dict:
"""Check for reentrancy vulnerability."""
issues = []
# Check for state updates after external calls
if contract_state.get('state_updates_after_call'):
issues.append({
'type': 'reentrancy',
'severity': 'critical',
'description': 'State updated after external call'
})
# Check for reentrancy guard
if not contract_state.get('has_reentrancy_guard'):
issues.append({
'type': 'missing_guard',
'severity': 'high',
'description': 'No reentrancy protection'
})
return {
'vulnerable': len(issues) > 0,
'issues': issues,
'recommendation': 'Use checks-effects-interactions pattern'
}
# Patterns
REENTRANCY_PATTERNS = {
'checks_effects_interactions': {
'description': 'Update state before external calls',
'example': '''
require(balance > 0);
balances[msg.sender] = 0; // Effect
(bool success, ) = msg.sender.call{value: balance}(""); // Interaction
'''
},
'reentrancy_guard': {
'description': 'Use mutex to prevent re-entry',
'example': '''
modifier noReentrant() {
require(!locked);
locked = true;
_;
locked = false;
}
'''
},
'pull_payments': {
'description': 'Let users withdraw instead of push',
'example': '''
mapping(address => uint256) public credits;
function withdraw() public {
uint256 amount = credits[msg.sender];
credits[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
'''
}
}
Common Vulnerabilities
Smart Contract Vulnerability Matrix
| Vulnerability | Severity | Description | Prevention |
|---|---|---|---|
| Reentrancy | Critical | Recursive external calls | Checks-effects-interactions |
| Integer overflow | High | Arithmetic overflow/underflow | SafeMath or Solidity 0.8+ |
| Access control | Critical | Unauthorized function access | Role-based access control |
| Front-running | Medium | Transaction ordering | Commit-reveal |
| Oracle manipulation | Critical | Price feed attacks | TWAP, multiple oracles |
| Flash loan attacks | High | Uncollateralized borrowing | Time delays |
| Signature replay | High | Reusing signatures | Nonces |
| Timestamp dependence | Medium | Block time manipulation | Avoid for randomness |
Vulnerability Scanner
class SmartContractScanner:
"""Scan smart contracts for common vulnerabilities."""
def __init__(self):
self.vulnerability_patterns = {
'reentrancy': {
'pattern': r'\.call\{.*\}\(.*\)',
'severity': 'critical',
'description': 'External call before state update'
},
'integer_overflow': {
'pattern': r'(\+|\-|\*|\/)(?![\s]*uint)',
'severity': 'high',
'description': 'Potential integer overflow'
},
'tx_origin': {
'pattern': r'tx\.origin',
'severity': 'high',
'description': 'Use of tx.origin for auth'
},
'block_timestamp': {
'pattern': r'block\.timestamp',
'severity': 'medium',
'description': 'Dependence on block timestamp'
},
'selfdestruct': {
'pattern': r'selfdestruct\(',
'severity': 'high',
'description': 'Use of selfdestruct'
}
}
def scan_code(self, contract_code: str) -> dict:
"""Scan contract code for vulnerabilities."""
import re
findings = []
for vuln_name, vuln_info in self.vulnerability_patterns.items():
matches = re.findall(vuln_info['pattern'], contract_code)
if matches:
findings.append({
'vulnerability': vuln_name,
'severity': vuln_info['severity'],
'description': vuln_info['description'],
'occurrences': len(matches)
})
return {
'total_findings': len(findings),
'critical': sum(1 for f in findings if f['severity'] == 'critical'),
'high': sum(1 for f in findings if f['severity'] == 'high'),
'medium': sum(1 for f in findings if f['severity'] == 'medium'),
'findings': findings
}
# Example
scanner = SmartContractScanner()
vulnerable_code = """
function withdraw() public {
uint256 balance = balances[msg.sender];
(bool success, ) = msg.sender.call{value: balance}("");
balances[msg.sender] = 0;
}
"""
results = scanner.scan_code(vulnerable_code)
print(f"Scan results: {results['total_findings']} findings")
for finding in results['findings']:
print(f" {finding['vulnerability']}: {finding['severity']}")
Trade-offs
Security vs Performance
| Trade-off | Security | Performance |
|---|---|---|
| Confirmation time | More confirmations | Faster UX |
| Gas limits | Higher limits | More complex |
| Access control | Strict | Flexible |
| Reentrancy guards | Locked functions | Unlocked |
| Oracle updates | More frequent | More costly |
Decentralization vs Security
| Aspect | More Decentralized | More Centralized |
|---|---|---|
| Attack surface | Larger | Smaller |
| Coordination | Harder | Easier |
| Trust | Trustless | Trusted |
| Resilience | Higher | Lower |
| Speed | Slower | Faster |
Real-World Examples
The DAO Hack (2016)
- Vulnerability: Reentrancy in withdrawal function
- Loss: 3.6M ETH (~$50M at the time)
- Result: Ethereum hard fork to recover funds
- Lesson: Checks-effects-interactions pattern
Poly Network Hack (2021)
- Vulnerability: Cross-chain bridge signature verification
- Loss: $611M (later returned)
- Result: White hat eventually returned funds
- Lesson: Bridge security is critical
Ronin Bridge Hack (2022)
- Vulnerability: Compromised validator keys
- Loss: $625M
- Result: Axie Infinity ecosystem impact
- Lesson: Key management and multi-sig requirements
Interview Questions
Q1: Explain the difference between front-running and sandwich attacks.
Answer:
| Aspect | Front-Running | Sandwich Attack |
|---|---|---|
| Transactions | 1 (before victim) | 3 (before, victim, after) |
| Mechanism | Order displacement | Price manipulation |
| Profit source | Information advantage | Price impact |
| Victim impact | Worse execution | Worse execution + slippage |
| Complexity | Simple | More complex |
| Profit potential | Lower | Higher |
Example:
- Front-run: See large buy order → buy first → sell after price rises
- Sandwich: See large buy → buy → victim buys at higher price → sell
Q2: How does MEV-Share differ from traditional MEV extraction?
Answer:
| Aspect | Traditional MEV | MEV-Share |
|---|---|---|
| Who benefits | Searchers/validators | Users |
| Transparency | Opaque | Transparent |
| Distribution | Centralized | Distributed |
| User protection | None | Partial |
| Protocol | Private | Open |
MEV-Share mechanism:
- User submits transaction to private mempool
- Searchers bid to include transactions
- Profits shared with user
- Reduces sandwich attacks
Example: Flashbots Protect, MEV Blocker
Q3: What are the key principles for writing secure smart contracts?
Answer:
-
Checks-Effects-Interactions Pattern
- Validate all inputs
- Update state before external calls
- Make external calls last
-
Reentrancy Protection
- Use reentrancy guards
- Implement pull payments
- Test with reentrancy exploits
-
Access Control
- Use role-based access
- Implement multi-sig for critical functions
- Use timelocks for upgrades
-
Input Validation
- Validate all parameters
- Check for overflow/underflow
- Use safe math libraries
-
Oracle Security
- Use multiple oracles
- Implement TWAP
- Add circuit breakers
Quiz Questions
Q1: What is the primary defense against reentrancy attacks?
A) Higher gas limits B) Checks-effects-interactions pattern C) Multiple confirmations D) Private mempool
Answer: B) Checks-effects-interactions pattern
Q2: What percentage of hash power is typically needed for a 51% attack on Bitcoin?
A) 33% B) 51% C) 67% D) 75%
Answer: B) 51%
Q3: Which MEV protection mechanism processes transactions simultaneously?
A) Private mempool B) Batch auctions C) Commit-reveal D) Slippage limits
Answer: B) Batch auctions
Practice
- Implement a reentrancy attack simulation
- Analyze sandwich attack profitability
- Build a simple MEV detector
- Audit a sample smart contract for vulnerabilities