Smart Contract Security
Overview
Smart contract security is paramount due to the immutable nature of blockchain. A single vulnerability can result in irreversible loss of funds.
â ī¸
Smart contracts handle real money. Always conduct thorough security audits, use established patterns, and test extensively before deployment.
Security Landscape
Reentrancy Attacks
The Classic Vulnerability
// 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, "No balance");
// VULNERABLE: External call before state update
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
balances[msg.sender] = 0; // Too late!
}
}
Attack Flow
Prevention: Checks-Effects-Interactions
// SECURE CONTRACT
contract SecureVault {
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, "No balance");
// CHECKS: Validate conditions
require(balance <= address(this).balance, "Insufficient contract balance");
// EFFECTS: Update state BEFORE external call
balances[msg.sender] = 0;
// INTERACTIONS: External call
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
}
}
Reentrancy Guard
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
error ReentrantCall();
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
if (_status == _ENTERED) revert ReentrantCall();
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
function _getReentrancyStatus() internal view returns (uint256) {
return _status;
}
}
contract SecureVault is ReentrancyGuard {
mapping(address => uint256) public balances;
function withdraw() public nonReentrant {
uint256 balance = balances[msg.sender];
require(balance > 0, "No balance");
balances[msg.sender] = 0;
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
}
}
Integer Overflow/Underflow
Pre-0.8.x Vulnerability
// VULNERABLE (Solidity < 0.8.0)
contract OverflowVulnerable {
mapping(address => uint8) public balances;
function transfer(address to, uint8 amount) public {
// Overflow possible!
balances[msg.sender] -= amount;
balances[to] += amount;
}
}
Protection Patterns
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract OverflowProtected {
mapping(address => uint256) public balances;
// Solidity 0.8.x has built-in overflow checks
function safeTransfer(address to, uint256 amount) public {
require(balances[msg.sender] >= amount, "Insufficient balance");
// Automatic overflow protection
balances[msg.sender] -= amount;
balances[to] += amount;
}
// Unchecked for gas optimization (when overflow impossible)
function optimizedTransfer(address to, uint256 amount) public {
require(balances[msg.sender] >= amount, "Insufficient balance");
unchecked {
// Safe because we checked above
balances[msg.sender] -= amount;
balances[to] += amount;
}
}
}
Access Control
Vulnerable Access Control
// VULNERABLE
contract VulnerableAccess {
address public owner;
constructor() {
owner = msg.sender;
}
// Missing access control!
function changeOwner(address newOwner) public {
owner = newOwner;
}
}
Secure Access Control Patterns
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract AccessControl {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
mapping(address => mapping(bytes32 => bool)) private _roles;
event RoleGranted(bytes32 indexed role, address indexed account);
event RoleRevoked(bytes32 indexed role, address indexed account);
constructor() {
_roles[msg.sender][ADMIN_ROLE] = true;
}
modifier onlyRole(bytes32 role) {
require(hasRole(role, msg.sender), "Unauthorized");
_;
}
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[account][role];
}
function grantRole(bytes32 role, address account) public onlyRole(ADMIN_ROLE) {
_roles[account][role] = true;
emit RoleGranted(role, account);
}
function revokeRole(bytes32 role, address account) public onlyRole(ADMIN_ROLE) {
_roles[account][role] = false;
emit RoleRevoked(role, account);
}
// Time-locked admin
mapping(address => uint256) public pendingAdmins;
uint256 public constant TIMELOCK_DELAY = 48 hours;
function proposeAdmin(address newAdmin) public onlyRole(ADMIN_ROLE) {
pendingAdmins[newAdmin] = block.timestamp + TIMELOCK_DELAY;
}
function acceptAdmin(address newAdmin) public {
require(pendingAdmins[newAdmin] != 0, "Not proposed");
require(block.timestamp >= pendingAdmins[newAdmin], "Too early");
_roles[newAdmin][ADMIN_ROLE] = true;
delete pendingAdmins[newAdmin];
}
}
Front-Running Attacks
Attack Vector
Mitigation: Commit-Reveal
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract CommitReveal {
mapping(bytes32 => bool) public commitments;
mapping(address => uint256) public nonces;
event CommitmentMade(bytes32 indexed commitment);
event Revealed(address indexed sender, uint256 value);
function commit(bytes32 commitment) external {
require(!commitments[commitment], "Commitment exists");
commitments[commitment] = true;
emit CommitmentMade(commitment);
}
function reveal(uint256 value, bytes32 salt) external {
bytes32 commitment = keccak256(abi.encodePacked(msg.sender, value, salt));
require(commitments[commitment], "Invalid commitment");
delete commitments[commitment];
emit Revealed(msg.sender, value);
}
}
Mitigation: Slippage Protection
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract SlippageProtection {
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut, // Slippage tolerance
uint256 deadline // Time limit
) external {
require(block.timestamp <= deadline, "Expired");
uint256 amountOut = _getAmountOut(tokenIn, tokenOut, amountIn);
require(amountOut >= minAmountOut, "Slippage exceeded");
// Execute swap
}
function _getAmountOut(address tokenIn, address tokenOut, uint256 amountIn)
internal pure returns (uint256)
{
// AMM calculation
return amountIn; // Placeholder
}
}
Oracle Manipulation
Attack Vector
// VULNERABLE: Using spot price
contract VulnerableOracle {
IUniswapV2Pair public pair;
function getPrice() public view returns (uint256) {
// VULNERABLE: Single block price can be manipulated
(uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
return (uint256(reserve1) * 1e18) / uint256(reserve0);
}
}
Mitigation: TWAP Oracle
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract TWAPOracle {
struct Observation {
uint256 timestamp;
uint256 priceCumulative;
}
Observation public lastObservation;
uint256 public constant PERIOD = 1 hours;
function update(uint256 price) external {
uint256 timeElapsed = block.timestamp - lastObservation.timestamp;
if (timeElapsed >= PERIOD) {
lastObservation = Observation({
timestamp: block.timestamp,
priceCumulative: lastObservation.priceCumulative + (price * timeElapsed)
});
}
}
function getPrice() public view returns (uint256) {
require(block.timestamp >= lastObservation.timestamp + PERIOD, "Period not elapsed");
return (lastObservation.priceCumulative) / PERIOD;
}
}
Oracle Security Comparison
| Method | Security | Latency | Cost |
|---|---|---|---|
| Spot Price | Low | Instant | Low |
| TWAP | High | 1 hour+ | Medium |
| Chainlink | High | 5-10 min | Medium |
| Multi-oracle | Very High | Variable | High |
Flash Loan Attacks
Attack Mechanism
// Simplified flash loan attack
contract FlashLoanAttack {
IERC20 public token;
IUniswapV2Router public router;
function executeAttack() external {
// 1. Borrow flash loan
uint256 borrowedAmount = 1000 ether;
token.approve(address(this), borrowedAmount);
// 2. Manipulate price oracle
_manipulatePrice();
// 3. Exploit vulnerable protocol
_exploitVulnerableProtocol();
// 4. Repay flash loan + fee
uint256 repayAmount = borrowedAmount * 10001 / 10000; // 0.1% fee
token.transfer(address(router), repayAmount);
}
function _manipulatePrice() internal {
// Dump tokens to crash price
token.transfer(address(router), 100 ether);
}
function _exploitVulnerableProtocol() internal {
// Buy at manipulated low price
}
}
Mitigation: Oracle Delay
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract FlashLoanResistant {
uint256 public lastBlock;
uint256 public constant DELAY = 1;
modifier noFlashLoan() {
require(block.number > lastBlock + DELAY, "Flash loan detected");
lastBlock = block.number;
_;
}
function criticalOperation() public noFlashLoan {
// Safe from flash loan attacks
}
}
Auditing Tools
Static Analysis
| Tool | Type | Strengths |
|---|---|---|
| Slither | Static analysis | Fast, comprehensive |
| Mythril | Symbolic execution | Deep analysis |
| Echidna | Fuzzing | Property testing |
| Securify2 | Static analysis | Pattern matching |
| Oyente | Static analysis | Early detection |
Example: Slither Usage
# Install Slither
pip install slither-analyzer
# Run analysis
slither contract.sol
# Detectors
slither --detect reentrancy-eth,unchecked-transfer contract.sol
# Print contract summary
slither --print contract-summary contract.sol
Formal Verification
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract FormalVerification {
uint256 public totalSupply;
mapping(address => uint256) public balances;
// Formal verification with Certora
// specification: totalSupply == sum(balances)
function transfer(address to, uint256 amount) public {
require(balances[msg.sender] >= amount, "Insufficient");
balances[msg.sender] -= amount;
balances[to] += amount;
// Invariant preserved: total supply unchanged
}
function mint(address to, uint256 amount) public {
totalSupply += amount;
balances[to] += amount;
// Invariant preserved: totalSupply == sum(balances)
}
}
Real-World Attacks
The DAO Hack (2016)
| Metric | Value |
|---|---|
| Loss | $60M (3.6M ETH) |
| Vulnerability | Reentrancy |
| Impact | Ethereum hard fork |
| Lesson | Checks-Effects-Interactions |
Poly Network (2021)
| Metric | Value |
|---|---|
| Loss | $611M (later returned) |
| Vulnerability | Access control |
| Impact | Cross-chain bridge |
| Lesson | Multi-sig requirements |
Wormhole (2022)
| Metric | Value |
|---|---|
| Loss | $320M |
| Vulnerability | Signature verification |
| Impact | Cross-chain bridge |
| Lesson | Cryptographic verification |
Security Checklist
## Smart Contract Security Checklist
### Access Control
- [ ] Owner functions protected
- [ ] Role-based access implemented
- [ ] Time locks for critical operations
- [ ] Multi-sig for high-value functions
### Reentrancy
- [ ] Checks-Effects-Interactions pattern
- [ ] Reentrancy guards on state-changing functions
- [ ] External call reentrancy considered
### Integer Safety
- [ ] Solidity 0.8.x or SafeMath
- [ ] Overflow/underflow checks
- [ ] Unchecked blocks justified
### Oracle Security
- [ ] TWAP or delayed oracle used
- [ ] Multi-oracle consensus
- [ ] Price bounds validated
### Front-Running
- [ ] Commit-reveal for sensitive data
- [ ] Slippage protection
- [ ] Deadline parameters
### Testing
- [ ] Unit tests (100% coverage)
- [ ] Integration tests
- [ ] Fuzz testing
- [ ] Formal verification
Trade-offs
| Security Measure | Gas Cost | Development Time | Protection Level |
|---|---|---|---|
| Reentrancy Guard | +2,600 | Low | High |
| Access Control | +5,000 | Medium | High |
| Oracle Delay | +10,000 | Medium | High |
| Multi-sig | +20,000 | High | Very High |
Interview Questions
-
Explain the Checks-Effects-Interactions pattern and why it prevents reentrancy attacks.
The pattern separates validation (checks), state changes (effects), and external calls (interactions). By updating state before external calls, reentrant calls see updated state and cannot exploit the vulnerability. This is the primary defense against reentrancy.
-
How do flash loan attacks work and what defenses exist?
Flash loans allow borrowing large amounts within one transaction. Attackers use them to manipulate prices or exploit vulnerabilities. Defenses include: TWAP oracles, block delays, oracle updates before operations, and circuit breakers.
-
Compare static analysis and formal verification for smart contract security.
Static analysis (Slither, Mythril) finds common patterns quickly but may miss complex issues. Formal verification mathematically proves contract correctness but requires more effort. Use both: static analysis for quick checks, formal verification for critical invariants.
Quiz Questions
-
What is the primary cause of the DAO hack?
- A) Integer overflow
- B) Reentrancy
- C) Access control
- D) Front-running
Answer: B - The DAO hack was caused by a reentrancy vulnerability that allowed repeated withdrawals.
-
Which pattern prevents reentrancy attacks?
- A) Pull over Push
- B) Checks-Effects-Interactions
- C) Rate Limiting
- D) Time Locks
Answer: B - Checks-Effects-Interactions ensures state is updated before external calls.
-
What is TWAP and why is it used?
- A) Time-Weighted Average Price, for oracle security
- B) Token Wrapped Average Price, for token wrapping
- C) Total Weighted Average Price, for total calculation
- D) Time-Weighted Average Pool, for pool pricing
Answer: A - TWAP (Time-Weighted Average Price) prevents price manipulation by averaging prices over time.