3.1 Security Landscape
Smart contract security is uniquely challenging: code is immutable once deployed, transactions are irreversible, and exploits can drain millions in seconds. Understanding vulnerabilities is essential for legal due diligence and risk assessment.
Why Smart Contract Security Matters
- Immutability: Bugs cannot be patched after deployment (usually)
- High Value Targets: Contracts often hold millions in assets
- Pseudonymity: Attackers are difficult to identify and prosecute
- Complexity: Interactions between contracts create emergent vulnerabilities
- Financial Incentives: Hackers can profit directly from exploits
| Year | Incident | Loss | Vulnerability Type |
|---|---|---|---|
| 2016 | The DAO | $60M | Reentrancy |
| 2021 | Poly Network | $611M | Access Control |
| 2022 | Wormhole | $326M | Signature Verification |
| 2022 | Ronin Bridge | $625M | Private Key Compromise |
| 2022 | Nomad Bridge | $190M | Merkle Proof Validation |
| 2023 | Euler Finance | $197M | Flash Loan + Logic Error |
Security vulnerabilities can create legal liability: breach of implied warranties, negligence in development, failure to conduct adequate audits, or misrepresentation of security. Understanding vulnerabilities helps assess potential claims.
3.2 Common Vulnerabilities
Reentrancy Attacks
The first major smart contract exploit. An attacker exploited a reentrancy vulnerability in The DAO's withdrawal function, recursively draining funds before the balance was updated. This led to the Ethereum hard fork creating Ethereum (ETH) and Ethereum Classic (ETC).
// VULNERABLE: State updated AFTER external call function withdraw(uint256 amount) external { require(balances[msg.sender] >= amount); // DANGER: External call before state update (bool success, ) = msg.sender.call{value: amount}(""); require(success); // State updated AFTER call - attacker can re-enter balances[msg.sender] -= amount; // TOO LATE! }
// SECURE: Checks-Effects-Interactions pattern function withdraw(uint256 amount) external { // 1. CHECKS require(balances[msg.sender] >= amount); // 2. EFFECTS - Update state BEFORE external call balances[msg.sender] -= amount; // 3. INTERACTIONS - External call LAST (bool success, ) = msg.sender.call{value: amount}(""); require(success); }
1. Checks: Validate all conditions first
2. Effects: Update contract state
3. Interactions: Make external calls last
This pattern prevents reentrancy by ensuring state is updated before any external calls.
Integer Overflow/Underflow
Prior to Solidity 0.8.0, arithmetic operations could overflow or underflow silently.
// uint8 max value is 255 uint8 balance = 255; balance = balance + 1; // Overflows to 0! uint8 amount = 0; amount = amount - 1; // Underflows to 255! // Attack: Transfer more than you have function transfer(address to, uint256 amount) { // If balance is 0 and amount is 1: // 0 - 1 = MAX_UINT256 (underflow!) balances[msg.sender] -= amount; // No check! balances[to] += amount; }
Solidity 0.8.0 and later include built-in overflow/underflow checks. Operations that would overflow now revert automatically. Always verify the Solidity version when reviewing contracts.
Access Control Flaws
// VULNERABLE: Missing access control function setOwner(address newOwner) external { owner = newOwner; // Anyone can call! } // VULNERABLE: tx.origin instead of msg.sender function withdraw() external { require(tx.origin == owner); // Can be phished! // If owner calls malicious contract, attacker can call this }
Flash Loan Attacks
Flash loans enable attacks by temporarily providing attackers with enormous capital to manipulate prices or governance votes within a single transaction.
| Vulnerability | Description | Mitigation |
|---|---|---|
| Reentrancy | Recursive calls before state update | Checks-Effects-Interactions, ReentrancyGuard |
| Integer Overflow | Arithmetic exceeds type bounds | Solidity 0.8+, SafeMath library |
| Access Control | Missing or improper authorization | onlyOwner modifiers, role-based access |
| Front-Running | Miners/MEV bots see pending txs | Commit-reveal schemes, private mempools |
| Oracle Manipulation | Price feed manipulation | TWAP oracles, multiple sources |
| Denial of Service | Making contract unusable | Pull over push, gas limits |
3.3 Smart Contract Auditing
A security audit is a systematic examination of smart contract code to identify vulnerabilities, logic errors, and deviations from best practices. Understanding audit processes helps evaluate their quality and limitations.
Audit Process
- Scoping: Define what contracts are in scope, expected behavior, and threat model
- Documentation Review: Review whitepapers, specifications, and design documents
- Manual Code Review: Line-by-line analysis by security experts
- Automated Analysis: Static analyzers, fuzzers, and symbolic execution tools
- Testing: Unit tests, integration tests, and invariant testing
- Report Generation: Document findings with severity ratings
- Remediation: Developers fix issues, auditors verify fixes
Severity Classification
| Severity | Definition | Example |
|---|---|---|
| Critical | Direct loss of funds, protocol takeover | Reentrancy allowing unlimited withdrawals |
| High | Significant financial impact or protocol disruption | Access control allowing unauthorized minting |
| Medium | Limited financial impact or complex exploitation | Front-running opportunities |
| Low | Minimal impact, best practice violations | Missing event emissions |
| Informational | Code quality, gas optimization | Unused variables |
Leading Audit Firms
- Trail of Bits: Known for rigorous, research-oriented audits
- OpenZeppelin: Major contributor to security standards and libraries
- Consensys Diligence: Ethereum ecosystem specialists
- Certik: High-volume auditing with automated tooling
- Spearbit: Decentralized network of security researchers
An audit is a point-in-time assessment with limited scope. Audited contracts have been hacked (e.g., Euler Finance, Wormhole). Audits reduce risk but do not eliminate it. Multiple audits from different firms provide better coverage.
3.4 Formal Verification
Approaches to Formal Verification
- Model Checking: Exhaustively explore all possible states
- Theorem Proving: Mathematical proofs of correctness
- Symbolic Execution: Analyze code with symbolic inputs
- SMT Solving: Use satisfiability solvers to find violations
Formal Verification Tools
| Tool | Type | Use Case |
|---|---|---|
| Certora Prover | Formal verification | Complex DeFi invariants |
| Echidna | Fuzzer | Property-based testing |
| Mythril | Symbolic execution | Vulnerability detection |
| Slither | Static analysis | Code quality and bugs |
| Foundry/Forge | Testing framework | Fuzz testing, invariants |
When reviewing a project's security posture:
1. Has the contract been audited? By whom? When?
2. Were all critical/high findings remediated?
3. Has the code changed since the audit?
4. Is there a bug bounty program?
5. Is the contract verified on Etherscan?
6. Has formal verification been performed?
3.5 Smart Contract Insurance
DeFi insurance protocols provide coverage against smart contract failures, offering risk transfer mechanisms for users and protocols.
Insurance Protocols
| Protocol | Model | Coverage Types |
|---|---|---|
| Nexus Mutual | Mutual (membership-based) | Smart contract cover, custody cover |
| InsurAce | Decentralized | Smart contract, stablecoin depeg |
| Unslashed Finance | Capital pool | Exchange, validator, smart contract |
DeFi insurance raises novel legal questions:
- Are these products "insurance" under regulations?
- What jurisdiction governs claims?
- How are claims adjudicated (often by token voting)?
- Are payouts enforceable if disputed?
- What constitutes a covered "hack" vs. economic exploit?
Key Takeaways
- Reentrancy is the most famous vulnerability - use Checks-Effects-Interactions pattern
- Always verify contracts use Solidity 0.8+ for overflow protection
- Audits are necessary but not sufficient - audited contracts have been hacked
- Review audit reports for remediation status of all findings
- Multiple audits from different firms provide better coverage
- Formal verification provides mathematical proofs but is expensive and limited in scope
- DeFi insurance is emerging but has unclear legal status