Blockchain Security
Purpose
Guide blockchain-specific security analysis covering smart contract auditing, DeFi threat modeling, economic security, incident response, formal verification, and bug bounty programs. Combines traditional security engineering with blockchain-specific risks like economic attack vectors, flash loans, oracle manipulation, and MEV.
Agent Protocol
Trigger
"blockchain security", "smart contract audit", "DeFi security", "DeFi threat model", "blockchain threat modeling", "audit methodology", "blockchain incident response", "emergency pause", "fork coordination", "bug bounty", "Immunefi", "Code4rena", "economic security", "game theory blockchain", "incentive analysis", "MEV security", "certora", "formal verification blockchain", "Halmos", "Scribble", "solidity security", "smart contract vulnerability", "blockchain exploit", "flash loan attack", "oracle manipulation", "reentrancy", "access control blockchain", "cross-chain security", "bridge security"
Input Context
- Smart contracts or protocol to analyze
- Platform (EVM/Solana/Cosmos/Cardano)
- Security objective (audit/threat model/incident response/pre-audit review)
- Codebase location and audit history
- Previous incidents or vulnerabilities
- TVL and risk exposure
Output Artifact
Security analysis including: threat model, vulnerability findings, economic analysis, verification approach, and remediation recommendations.
Response Format
- Threat model: assets, actors, attack vectors, trust assumptions, attack surface
- Audit approach: methodology, tools, timeline, expected coverage
- Economic analysis: incentive structures, game theory, exploit scenarios
- Security controls: mitigations, circuit breakers, monitoring
- Verification: formal properties, invariants, proof techniques
- Incident response: emergency plan, communication template
Completion Criteria
- Threat model identifies all trust assumptions and attack surfaces
- Vulnerability findings include severity, impact, likelihood, and remediation
- Economic analysis models incentive alignment and identifies exploit paths
- Formal verification specifies key invariants (solvency, access control, correctness)
- Emergency response plan covers: pause, communication, fork coordination, post-mortem
Max Response Length
5000 tokens
Decision Trees
Security Assessment Type
Security need:
├── Pre-deployment audit?
│ ├── Early stage → Threat modeling + architecture review
│ │ ├── Identify trust assumptions
│ │ ├── Map attack surface
│ │ └── Design security controls
│ ├── Mid-development → Full audit (automated + manual + fuzz)
│ │ ├── Slither + Mythril static analysis (first pass)
│ │ ├── Manual line-by-line review (second pass)
│ │ ├── Foundry fuzz + invariant tests (third pass)
│ │ ├── Echidna/Medusa property-based fuzzing (fourth pass)
│ │ └── Certora/Halmos formal verification (fifth pass)
│ └── Pre-launch → Final audit + bug bounty launch
│ ├── Re-audit after fixes
│ ├── Immunefi or Code4rena bounty program
│ └── Emergency response plan
├── Incident response?
│ ├── Ongoing exploit → Emergency pause + communication
│ ├── Post-exploit → Damage assessment + recovery plan
│ └── Post-mortem → Root cause analysis + fix implementation
└── Ongoing security?
├── Continuous monitoring → Forta, Tenderly alerts
├── Bug bounty management → VRT, severity classification
└── Periodic review → Quarterly parameter review, annual deep audit
Vulnerability Severity (Immunefi Standard)
| Severity |
Impact |
Payout Range |
| Critical |
Direct loss of funds, permanent DoS |
Up to $10M+ |
| High |
Theft of unclaimed yield, temporary DoS |
$50K-$500K |
| Medium |
Contract fails to deliver expected return, temporarily frozen funds |
$5K-$50K |
| Low |
Griefing (no direct financial loss) |
$1K-$5K |
| None |
Informational |
No payout |
DeFi Threat Modeling (STRIDE-Blockchain)
STRIDE Adapted for Blockchain
| Threat |
Blockchain Equivalent |
Example |
| Spoofing |
Fake event log emission, counterfeit token |
Impostor token impersonation |
| Tampering |
State manipulation, reorg, flash loan price |
Manipulating oracle price |
| Repudiation |
Unauthorized proposal, fake governance |
Flash loan governance attack |
| Information disclosure |
Mempool snooping, frontrunning |
MEV extraction from public tx pool |
| Denial of Service |
Gas griefing, block stuffing |
Low-cost DoS via state bloat |
| Elevation of Privilege |
Unauthorized role assignment, proxy admin |
OpenZeppelin UUPS unauthorized upgrade |
Common Attack Trees
Reentrancy Attack Tree
├── External call before state update
│ ├── ETH transfer via .call{value}() (forward all gas)
│ ├── ERC-777 callback (tokensToSend hook)
│ └── ERC-1155 callback (onERC1155Received)
├── Recipient is malicious contract
│ └── Malicious fallback re-enters victim function
└── Mitigations:
├── Checks-effects-interactions pattern
├── ReentrancyGuard (OpenZeppelin)
└── Pull-over-push for payments
Oracle Manipulation Attack Tree
├── Single oracle price source
│ ├── Flash loan to manipulate AMM price
│ ├── Sandwich attack on oracle update
│ └── Frontrun oracle transaction
├── TWAP manipulation
│ └── Multi-block TWAP manipulation (expensive but possible)
└── Mitigations:
├── Redundant oracles (minimum 3 independent sources)
├── TWAP with sufficient window (30 min+)
├── Stale price checks (max age < 1 hour)
└── Circuit breakers on price deviation
Flash Loan Attack Tree
├── Borrow large capital from flash loan provider
├── Manipulate price (AMM swap → oracle price change)
├── Exploit protocol with manipulated price
│ ├── Mint undercollateralized position
│ ├── Drain pool via mispriced asset
│ └── Trigger false liquidations
└── Repay flash loan + profit
Vulnerability Catalog
Reentrancy
// VULNERABLE
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
(bool ok, ) = msg.sender.call{value: amount}(""); // external call BEFORE state
require(ok);
balances[msg.sender] -= amount; // state update AFTER
}
// FIXED: CEI pattern
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount; // state update FIRST
(bool ok, ) = msg.sender.call{value: amount}(""); // then external call
require(ok);
}
Access Control
// VULNERABLE: init function unprotected
function initialize(address _owner) external {
owner = _owner; // anyone can call this
}
// FIXED
function initialize(address _owner) external initializer {
__Ownable_init(_owner);
}
// VULNERABLE: tx.origin for auth
function adminOnly() external {
require(tx.origin == owner); // tx.origin can be phished
}
// FIXED: msg.sender for auth
function adminOnly() external {
require(msg.sender == owner);
}
Flash Loan Attack Example
// VULNERABLE: uses spot price for liquidation
function getLiquidationValue(address user) external view returns (uint256) {
return collateral[user] * getSpotPrice(); // Can be manipulated
}
// FIXED: uses TWAP
function getLiquidationValue(address user) external view returns (uint256) {
return collateral[user] * getTWAP(30 minutes); // Manipulation resistant
}
ERC-4626 Inflation Attack
// VULNERABLE: first depositor manipulates share price
// Attacker mints 1 wei shares, then donates large amount to vault
// share price becomes very high → subsequent depositors get 0 shares
// FIXED: virtual shares + assets
uint256 internal constant VIRTUAL_SHARES = 1e6;
uint256 internal constant VIRTUAL_ASSETS = 1e6;
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply + VIRTUAL_SHARES;
return assets * supply / (totalAssets() + VIRTUAL_ASSETS);
}
Audit Methodology
Phase 1: Scope & Recon
- Define audit scope: contracts, functions, interactions
- Review specification and architecture documentation
- Understand trust model: admin roles, upgrade paths, emergency mechanisms
- Set up local environment with all dependencies
Phase 2: Automated Analysis
- Run Slither: detect common vulnerabilities, generate inheritance graph
- Run Mythril: symbolic execution for deep vulnerability detection
- Run Aderyn: Solidity static analyzer for spec violations
- Run Halmos: symbolic testing for complex assertions
- Run semgrep with custom rules
Phase 3: Manual Review
- Storage layout review: collision risks, upgrade compatibility
- Access control review: privilege escalation paths, role hierarchy
- Business logic review: correctness, edge cases, integer handling
- External dependency review: oracle, bridge, token interactions
- Economic analysis: incentive alignment, MEV exposure, game theory
Phase 4: Fuzz & Invariant
- Parameterized fuzzing with Foundry
- Invariant tests with Echidna or Medusa
- Stateful fuzzing with Foundry fuzz
- Differential testing with reference implementation
Phase 5: Formal Verification
- Certora CVL for critical invariants (solvency, access control)
- Scribble for annotation-based formal specs
- Halmos for symbolic testing of complex logic
Phase 6: Report & Remediation
- Document findings with severity, impact, exploit scenario, fix
- Retest fixes after remediation
- Final report with methodology, findings, and risk assessment
Audit Tools Comparison
| Tool |
Type |
Best For |
Limitations |
| Slither |
Static analysis |
First-pass vulnerability detection, inheritance analysis |
False positives, limited deep logic |
| Mythril |
Symbolic execution |
Complex state-exploration bugs |
Slow, state explosion |
| Echidna |
Property-based fuzzing |
Invariant testing with custom properties |
Requires writing properties |
| Foundry fuzz |
Parameterized fuzzing |
Input-range fuzzing, stateful tests |
Less directed than Echidna |
| Certora |
Formal verification |
Critical invariants, solvency proofs |
Expensive, requires CVL DSL |
| Halmos |
Symbolic testing |
Bounded verification of assertions |
Not fully automated |
| Aderyn |
Static analysis |
Solidity spec compliance |
Limited depth |
Formal Verification
Certora CVL Example
// Certora Verification Language: define invariants
rule total_supply_invariant() {
// totalSupply must equal sum of all balances
uint256 total = totalSupply();
uint256 sum = 0;
address user;
// Quantified assertion over all users (handled by Certora)
assert total == currentContract.balance + sumOfAllUserBalances();
}
rule no_double_withdrawal(address user) {
uint256 balance_before = balanceOf(user);
uint256 amount = balance_before / 2;
withdraw(amount);
withdraw(amount);
uint256 balance_after = balanceOf(user);
assert balance_after == 0;
}
Economic Security
Game Theory Analysis Framework
Protocol economic security:
├── Nash equilibrium analysis
│ ├── Does a rational user have incentive to act honestly?
│ └── Is there a profitable deviation path?
├── Attack cost vs. profit
│ ├── How much capital required for exploit?
│ └── What is the expected profit from exploit?
├── MEV analysis
│ ├── What MEV opportunities exist?
│ └── Can MEV disrupt protocol equilibrium?
└── Composability risk
├── What other protocols does this interact with?
└── Can a failure cascade through the system?
Incident Response
Emergency Response Playbook
// Emergency pause pattern
contract Pausable {
bool public paused;
address public guardian;
modifier whenNotPaused() {
require(!paused, "PAUSED");
_;
}
function pause() external {
require(msg.sender == guardian, "NOT_GUARDIAN");
paused = true;
emit EmergencyPaused(msg.sender);
}
function unpause() external {
require(msg.sender == guardian, "NOT_GUARDIAN");
paused = false;
emit EmergencyUnpaused(msg.sender);
}
}
Incident Response Phases
1. DETECT: Monitoring alert, community report, or security partner notification
- Forta bot detects anomalous activity
- Tenderly alert on unexpected state changes
- Community report via Discord/Immunefi
2. ASSESS: Guardian multi-sig evaluates severity (15-30 min)
- Is there an active exploit?
- What is compromised? (contract, key, oracle, bridge?)
- What is the damage scope? (TVL at risk)
3. PAUSE: Guardian pauses affected contracts
- Emergency pause kill switch (guardian only)
- Stop deposits, withdraws, liquidations as needed
- Can't pause critical owner functions (timelock bypass)
4. COMMUNICATE: Pre-prepared message template
- "We are aware of an issue with [contract]. All funds are safe. Paused while investigating."
- Twitter/Discord/Governance forum within 30 min
- Regular updates every 2 hours
5. MITIGATE: Emergency proposal with fix
- Upgrade contract (if upgradeable) or deploy new version
- Requires timelock delay (unless emergency bypass)
6. RESUME: Governance vote to unpause + validate fix
- Multi-sig unpause after fix confirmed
- Bug bounty payout for reporter
7. POST-MORTEM: Public incident report within 7 days
- Root cause analysis
- Timeline of events
- Fix details
- Lessons learned
Rules
- Always start with threat modeling before writing any code — identify assets, trust boundaries, attack surfaces
- Audit pipeline: scope → manual review → automated tooling → fuzz/invariant → formal verification → report
- Economic security is as important as code security — analyze game theory and incentive alignment
- Bug bounty programs follow Immunefi severity: Critical (up to $1M+), High ($50K-$100K), Medium ($5K-$20K), Low ($1K-$5K)
- Incident response: freeze/pause contract → assess damage → communicate → fork coordination → post-mortem → compensation
- Formal verification complements but does NOT replace manual review and fuzz testing
- Always verify signature malleability (low-s for ECDSA), nonce reuse, and signature replay protection
- Cross-chain bridges require additional security layers: rate limiting, circuit breakers, tiered security
- ERC-4626 vaults must prevent inflation attacks with virtual shares + assets
- Flash loan resistance requires TWAP pricing, not spot prices for critical operations
- Upgradeable contracts must have disabled initializers on implementation contracts
- All admin functions should be behind timelock + multi-sig, never single-key control
- Oracle prices must be validated for freshness (staleness threshold) and deviation
- Economic security analysis must model worst-case market conditions, not average
- Bug bounties must cover the protocol's total value secured (TVS) for adequate incentives
Implementation Examples
Security Analysis (Solidity — Reentrancy Guard)
contract ProtectedVault {
using SafeERC20 for IERC20;
uint256 private _status = 1; // 1=unlocked 2=locked
modifier nonReentrant() {
require(_status == 1, "Reentrant call");
_status = 2; _;
_status = 1;
}
function withdraw(uint256 amount) external nonReentrant {
uint256 bal = balances[msg.sender];
require(bal >= amount, "Insufficient");
balances[msg.sender] = bal - amount; // Effects first
token.safeTransfer(msg.sender, amount); // Interaction last
}
}
Formal Verification — Certora CVL
methods {
function totalAssets() external returns (uint256);
function totalSupply() external returns (uint256);
}
invariant solvency()
totalAssets() >= totalSupply()
filtered on f { f.contract != currentContract }
- references/bug-bounty-program.md — Bug Bounty Programs for Blockchain Projects
- references/economic-security.md — Economic Security in Blockchain Systems
- references/formal-verification-deep.md — Formal Verification for Smart Contracts
- references/incident-response.md — Blockchain Incident Response
- references/smart-contract-security.md — Smart Contract Security
- references/threat-modeling.md — Threat Modeling for Blockchain Systems
- references/blockchain-vulnerability-catalog.md — Common Blockchain Vulnerabilities Catalog
- references/cross-chain-security.md — Cross-Chain Security Considerations
- references/flash-loan-attack-patterns.md — Flash Loan Attack Patterns
Architecture Decision Trees
Blockchain Security Approach
├── Audit phase?
│ ├── Pre-development → Threat model + formal spec
│ ├── Post-development → Smart contract audit + fuzzing
│ ├── Pre-deployment → Comprehensive security review + bug bounty
│ └── Post-deployment → Continuous monitoring + incident response
├── Vulnerability type?
│ ├── Reentrancy → ReentrancyGuard, checks-effects-interactions
│ ├── Access control → OpenZeppelin AccessControl, multisig
│ ├── Oracle manipulation → TWAP, multiple sources, circuit breaker
│ └── Math errors → SafeMath (pre-0.8), overflow checks (0.8+)
├── Formal verification needed?
│ ├── Yes (high-value) → Certora / Halmos (rule-based verification)
│ ├── Yes (ZK circuits) → Circom compiler checks, zkVerify
│ └── No → Standard audit + fuzz testing
└── Bug bounty program?
├── Yes → Immunefi / HackerOne (up to 10% of TVL)
└── No → Internal audits only (higher residual risk)
Decision criteria: Evaluate TVL at risk, regulatory requirements, team security maturity, and budget.
Implementation Patterns
Reentrancy Protection
// blockchain-security/contracts/ReentrancyGuard.sol
pragma solidity ^0.8.20;
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
Access Control with Timelock
// blockchain-security/contracts/TimelockController.sol
contract TimelockController {
uint256 public constant MIN_DELAY = 2 days;
uint256 public constant GRACE_PERIOD = 14 days;
mapping(bytes32 => bool) public queuedTransactions;
event Queued(bytes32 indexed txHash, address target, uint256 value, bytes data, uint256 executeTime);
event Executed(bytes32 indexed txHash);
function queue(address target, uint256 value, bytes calldata data) external onlyRole(PROPOSER_ROLE) {
bytes32 txHash = keccak256(abi.encode(target, value, data, block.timestamp + MIN_DELAY));
queuedTransactions[txHash] = true;
emit Queued(txHash, target, value, data, block.timestamp + MIN_DELAY);
}
function execute(address target, uint256 value, bytes calldata data) external onlyRole(EXECUTOR_ROLE) {
bytes32 txHash = keccak256(abi.encode(target, value, data, block.timestamp));
require(queuedTransactions[txHash], "Not queued");
delete queuedTransactions[txHash];
(bool success,) = target.call{value: value}(data);
require(success, "Execution failed");
emit Executed(txHash);
}
}
Production Considerations
- Audit frequency: Full audit before mainnet deploy; re-audit on major upgrade (> 20% code change).
- Bug bounty: Launch Immunefi bounty (up to 10% TVL); scope all contracts and frontend.
- Monitoring: Deploy Forta/OpenZeppelin Defender Sentinel for transaction monitoring.
- Incident response: Pre-defined IR playbook; pause contracts within 30 min of exploit detection.
- Insurance: Purchase DeFi insurance (Nexus Mutual, Sherlock) for TVL coverage.
- Responsible disclosure: Maintain security.txt; private disclosure channel for vulnerability reports.
Anti-Patterns
| Anti-Pattern |
Consequence |
Solution |
| Skipping threat model |
Miss architecture-level vulnerabilities |
Mandatory threat model before code |
| Only automated audits |
Miss logic bugs |
Manual review + automated + fuzzing |
| No timelock on upgrades |
Compromised owner upgrades malicious code |
Enforce minimum 48h timelock |
| Fixing bugs without re-audit |
New bugs introduced |
Re-audit > 20% code changes |
| No pause mechanism |
Can't stop exploit in progress |
Implement pausable + emergency stop |
Performance Optimization
- Gas-efficient access control: Use bitmap-based roles (BitMaps) instead of array for role management.
- Batch verification: Verify multiple signatures in single operation for multisig.
- Storage-efficient audits: Use event-based audit trail instead of on-chain storage for non-critical logs.
- Off-chain monitoring: Use The Graph subgraph for security monitoring; avoid on-chain overhead.
- Selective audit scope: Focus formal verification on critical paths (token transfers, liquidations).
Security Considerations
- Checks-effects-interactions: Always follow pattern: validate → update state → external calls.
- Proxy security: Use transparent proxy (EIP-1967) to avoid function selector collisions.
- Access control: Implement role-based access with OpenZeppelin AccessControl; avoid
onlyOwner.
- Signature replay: Include domain separator, nonce, and chain ID; validate expiry.
- Randomness: Use Chainlink VRF for on-chain randomness; never use block.timestamp or blockhash.
- Governance attack resistance: Implement flash loan resistant voting; time-weighted voting power.
Phase
blockchain → blockchain-security
1---2name: blockchain-security3description: Use this skill when asked about blockchain security, smart contract auditing, DeFi threat modeling, blockchain incident response, bug bounty programs, economic security, formal verification of smart contracts, and blockchain-specific security analysis. Languages: Solidity, Python, Rust, Haskell. Covers threat modeling for DeFi protocols (STRIDE for blockchain), audit methodology (scope, manual review, tooling, report), incident response (emergency pause, fork coordination, compensation), bug bounty programs (Immunefi, Code4rena), economic security (game theory, incentive analysis, MEV), and formal verification (Certora CVL, Halmos, Scribble). References shared skills from skills/security/ (threat-intelligence, secrets-management, siem-engineering) and skills/quality/ (property-based-testing) where core concepts overlap. Do NOT use for: general smart contract testing (use blockchain-testing), standard application security (use skills/security/ skills), or core cryptography (use blockchain-cryptography).4license: MIT5---67# Blockchain Security89## Purpose10Guide blockchain-specific security analysis covering smart contract auditing, DeFi threat modeling, economic security, incident response, formal verification, and bug bounty programs. Combines traditional security engineering with blockchain-specific risks like economic attack vectors, flash loans, oracle manipulation, and MEV.1112## Agent Protocol1314### Trigger15"blockchain security", "smart contract audit", "DeFi security", "DeFi threat model", "blockchain threat modeling", "audit methodology", "blockchain incident response", "emergency pause", "fork coordination", "bug bounty", "Immunefi", "Code4rena", "economic security", "game theory blockchain", "incentive analysis", "MEV security", "certora", "formal verification blockchain", "Halmos", "Scribble", "solidity security", "smart contract vulnerability", "blockchain exploit", "flash loan attack", "oracle manipulation", "reentrancy", "access control blockchain", "cross-chain security", "bridge security"1617### Input Context18- Smart contracts or protocol to analyze19- Platform (EVM/Solana/Cosmos/Cardano)20- Security objective (audit/threat model/incident response/pre-audit review)21- Codebase location and audit history22- Previous incidents or vulnerabilities23- TVL and risk exposure2425### Output Artifact26Security analysis including: threat model, vulnerability findings, economic analysis, verification approach, and remediation recommendations.2728### Response Format291. **Threat model**: assets, actors, attack vectors, trust assumptions, attack surface302. **Audit approach**: methodology, tools, timeline, expected coverage313. **Economic analysis**: incentive structures, game theory, exploit scenarios324. **Security controls**: mitigations, circuit breakers, monitoring335. **Verification**: formal properties, invariants, proof techniques346. **Incident response**: emergency plan, communication template3536### Completion Criteria37- Threat model identifies all trust assumptions and attack surfaces38- Vulnerability findings include severity, impact, likelihood, and remediation39- Economic analysis models incentive alignment and identifies exploit paths40- Formal verification specifies key invariants (solvency, access control, correctness)41- Emergency response plan covers: pause, communication, fork coordination, post-mortem4243### Max Response Length445000 tokens4546## Decision Trees4748### Security Assessment Type49```50Security need:51├── Pre-deployment audit?52│ ├── Early stage → Threat modeling + architecture review53│ │ ├── Identify trust assumptions54│ │ ├── Map attack surface55│ │ └── Design security controls56│ ├── Mid-development → Full audit (automated + manual + fuzz)57│ │ ├── Slither + Mythril static analysis (first pass)58│ │ ├── Manual line-by-line review (second pass)59│ │ ├── Foundry fuzz + invariant tests (third pass)60│ │ ├── Echidna/Medusa property-based fuzzing (fourth pass)61│ │ └── Certora/Halmos formal verification (fifth pass)62│ └── Pre-launch → Final audit + bug bounty launch63│ ├── Re-audit after fixes64│ ├── Immunefi or Code4rena bounty program65│ └── Emergency response plan66├── Incident response?67│ ├── Ongoing exploit → Emergency pause + communication68│ ├── Post-exploit → Damage assessment + recovery plan69│ └── Post-mortem → Root cause analysis + fix implementation70└── Ongoing security?71 ├── Continuous monitoring → Forta, Tenderly alerts72 ├── Bug bounty management → VRT, severity classification73 └── Periodic review → Quarterly parameter review, annual deep audit74```7576### Vulnerability Severity (Immunefi Standard)77| Severity | Impact | Payout Range |78|----------|--------|-------------|79| Critical | Direct loss of funds, permanent DoS | Up to $10M+ |80| High | Theft of unclaimed yield, temporary DoS | $50K-$500K |81| Medium | Contract fails to deliver expected return, temporarily frozen funds | $5K-$50K |82| Low | Griefing (no direct financial loss) | $1K-$5K |83| None | Informational | No payout |8485## DeFi Threat Modeling (STRIDE-Blockchain)8687### STRIDE Adapted for Blockchain88| Threat | Blockchain Equivalent | Example |89|--------|----------------------|---------|90| Spoofing | Fake event log emission, counterfeit token | Impostor token impersonation |91| Tampering | State manipulation, reorg, flash loan price | Manipulating oracle price |92| Repudiation | Unauthorized proposal, fake governance | Flash loan governance attack |93| Information disclosure | Mempool snooping, frontrunning | MEV extraction from public tx pool |94| Denial of Service | Gas griefing, block stuffing | Low-cost DoS via state bloat |95| Elevation of Privilege | Unauthorized role assignment, proxy admin | OpenZeppelin UUPS unauthorized upgrade |9697### Common Attack Trees9899**Reentrancy Attack Tree**100```101├── External call before state update102│ ├── ETH transfer via .call{value}() (forward all gas)103│ ├── ERC-777 callback (tokensToSend hook)104│ └── ERC-1155 callback (onERC1155Received)105├── Recipient is malicious contract106│ └── Malicious fallback re-enters victim function107└── Mitigations:108 ├── Checks-effects-interactions pattern109 ├── ReentrancyGuard (OpenZeppelin)110 └── Pull-over-push for payments111```112113**Oracle Manipulation Attack Tree**114```115├── Single oracle price source116│ ├── Flash loan to manipulate AMM price117│ ├── Sandwich attack on oracle update118│ └── Frontrun oracle transaction119├── TWAP manipulation120│ └── Multi-block TWAP manipulation (expensive but possible)121└── Mitigations:122 ├── Redundant oracles (minimum 3 independent sources)123 ├── TWAP with sufficient window (30 min+)124 ├── Stale price checks (max age < 1 hour)125 └── Circuit breakers on price deviation126```127128**Flash Loan Attack Tree**129```130├── Borrow large capital from flash loan provider131├── Manipulate price (AMM swap → oracle price change)132├── Exploit protocol with manipulated price133│ ├── Mint undercollateralized position134│ ├── Drain pool via mispriced asset135│ └── Trigger false liquidations136└── Repay flash loan + profit137```138139## Vulnerability Catalog140141### Reentrancy142```solidity143// VULNERABLE144function withdraw(uint256 amount) external {145 require(balances[msg.sender] >= amount);146 (bool ok, ) = msg.sender.call{value: amount}(""); // external call BEFORE state147 require(ok);148 balances[msg.sender] -= amount; // state update AFTER149}150151// FIXED: CEI pattern152function withdraw(uint256 amount) external {153 require(balances[msg.sender] >= amount);154 balances[msg.sender] -= amount; // state update FIRST155 (bool ok, ) = msg.sender.call{value: amount}(""); // then external call156 require(ok);157}158```159160### Access Control161```solidity162// VULNERABLE: init function unprotected163function initialize(address _owner) external {164 owner = _owner; // anyone can call this165}166167// FIXED168function initialize(address _owner) external initializer {169 __Ownable_init(_owner);170}171172// VULNERABLE: tx.origin for auth173function adminOnly() external {174 require(tx.origin == owner); // tx.origin can be phished175}176177// FIXED: msg.sender for auth178function adminOnly() external {179 require(msg.sender == owner);180}181```182183### Flash Loan Attack Example184```solidity185// VULNERABLE: uses spot price for liquidation186function getLiquidationValue(address user) external view returns (uint256) {187 return collateral[user] * getSpotPrice(); // Can be manipulated188}189190// FIXED: uses TWAP191function getLiquidationValue(address user) external view returns (uint256) {192 return collateral[user] * getTWAP(30 minutes); // Manipulation resistant193}194```195196### ERC-4626 Inflation Attack197```solidity198// VULNERABLE: first depositor manipulates share price199// Attacker mints 1 wei shares, then donates large amount to vault200// share price becomes very high → subsequent depositors get 0 shares201202// FIXED: virtual shares + assets203uint256 internal constant VIRTUAL_SHARES = 1e6;204uint256 internal constant VIRTUAL_ASSETS = 1e6;205206function convertToShares(uint256 assets) public view returns (uint256) {207 uint256 supply = totalSupply + VIRTUAL_SHARES;208 return assets * supply / (totalAssets() + VIRTUAL_ASSETS);209}210```211212## Audit Methodology213214### Phase 1: Scope & Recon2151. Define audit scope: contracts, functions, interactions2162. Review specification and architecture documentation2173. Understand trust model: admin roles, upgrade paths, emergency mechanisms2184. Set up local environment with all dependencies219220### Phase 2: Automated Analysis2215. Run Slither: detect common vulnerabilities, generate inheritance graph2226. Run Mythril: symbolic execution for deep vulnerability detection2237. Run Aderyn: Solidity static analyzer for spec violations2248. Run Halmos: symbolic testing for complex assertions2259. Run semgrep with custom rules226227### Phase 3: Manual Review22810. Storage layout review: collision risks, upgrade compatibility22911. Access control review: privilege escalation paths, role hierarchy23012. Business logic review: correctness, edge cases, integer handling23113. External dependency review: oracle, bridge, token interactions23214. Economic analysis: incentive alignment, MEV exposure, game theory233234### Phase 4: Fuzz & Invariant23515. Parameterized fuzzing with Foundry23616. Invariant tests with Echidna or Medusa23717. Stateful fuzzing with Foundry fuzz23818. Differential testing with reference implementation239240### Phase 5: Formal Verification24119. Certora CVL for critical invariants (solvency, access control)24220. Scribble for annotation-based formal specs24321. Halmos for symbolic testing of complex logic244245### Phase 6: Report & Remediation24622. Document findings with severity, impact, exploit scenario, fix24723. Retest fixes after remediation24824. Final report with methodology, findings, and risk assessment249250### Audit Tools Comparison251| Tool | Type | Best For | Limitations |252|------|------|----------|-------------|253| Slither | Static analysis | First-pass vulnerability detection, inheritance analysis | False positives, limited deep logic |254| Mythril | Symbolic execution | Complex state-exploration bugs | Slow, state explosion |255| Echidna | Property-based fuzzing | Invariant testing with custom properties | Requires writing properties |256| Foundry fuzz | Parameterized fuzzing | Input-range fuzzing, stateful tests | Less directed than Echidna |257| Certora | Formal verification | Critical invariants, solvency proofs | Expensive, requires CVL DSL |258| Halmos | Symbolic testing | Bounded verification of assertions | Not fully automated |259| Aderyn | Static analysis | Solidity spec compliance | Limited depth |260261## Formal Verification262263### Certora CVL Example264```cvl265// Certora Verification Language: define invariants266rule total_supply_invariant() {267 // totalSupply must equal sum of all balances268 uint256 total = totalSupply();269 uint256 sum = 0;270 address user;271 // Quantified assertion over all users (handled by Certora)272 assert total == currentContract.balance + sumOfAllUserBalances();273}274275rule no_double_withdrawal(address user) {276 uint256 balance_before = balanceOf(user);277 uint256 amount = balance_before / 2;278 279 withdraw(amount);280 withdraw(amount);281 282 uint256 balance_after = balanceOf(user);283 assert balance_after == 0;284}285```286287## Economic Security288289### Game Theory Analysis Framework290```291Protocol economic security:292├── Nash equilibrium analysis293│ ├── Does a rational user have incentive to act honestly?294│ └── Is there a profitable deviation path?295├── Attack cost vs. profit296│ ├── How much capital required for exploit?297│ └── What is the expected profit from exploit?298├── MEV analysis299│ ├── What MEV opportunities exist?300│ └── Can MEV disrupt protocol equilibrium?301└── Composability risk302 ├── What other protocols does this interact with?303 └── Can a failure cascade through the system?304```305306## Incident Response307308### Emergency Response Playbook309```solidity310// Emergency pause pattern311contract Pausable {312 bool public paused;313 address public guardian;314315 modifier whenNotPaused() {316 require(!paused, "PAUSED");317 _;318 }319320 function pause() external {321 require(msg.sender == guardian, "NOT_GUARDIAN");322 paused = true;323 emit EmergencyPaused(msg.sender);324 }325326 function unpause() external {327 require(msg.sender == guardian, "NOT_GUARDIAN");328 paused = false;329 emit EmergencyUnpaused(msg.sender);330 }331}332```333334### Incident Response Phases335```3361. DETECT: Monitoring alert, community report, or security partner notification337 - Forta bot detects anomalous activity338 - Tenderly alert on unexpected state changes339 - Community report via Discord/Immunefi3403412. ASSESS: Guardian multi-sig evaluates severity (15-30 min)342 - Is there an active exploit?343 - What is compromised? (contract, key, oracle, bridge?)344 - What is the damage scope? (TVL at risk)3453463. PAUSE: Guardian pauses affected contracts347 - Emergency pause kill switch (guardian only)348 - Stop deposits, withdraws, liquidations as needed349 - Can't pause critical owner functions (timelock bypass)3503514. COMMUNICATE: Pre-prepared message template352 - "We are aware of an issue with [contract]. All funds are safe. Paused while investigating."353 - Twitter/Discord/Governance forum within 30 min354 - Regular updates every 2 hours3553565. MITIGATE: Emergency proposal with fix357 - Upgrade contract (if upgradeable) or deploy new version358 - Requires timelock delay (unless emergency bypass)359 3606. RESUME: Governance vote to unpause + validate fix361 - Multi-sig unpause after fix confirmed362 - Bug bounty payout for reporter3633647. POST-MORTEM: Public incident report within 7 days365 - Root cause analysis366 - Timeline of events367 - Fix details368 - Lessons learned369```370371## Rules3721. Always start with threat modeling before writing any code — identify assets, trust boundaries, attack surfaces3732. Audit pipeline: scope → manual review → automated tooling → fuzz/invariant → formal verification → report3743. Economic security is as important as code security — analyze game theory and incentive alignment3754. Bug bounty programs follow Immunefi severity: Critical (up to $1M+), High ($50K-$100K), Medium ($5K-$20K), Low ($1K-$5K)3765. Incident response: freeze/pause contract → assess damage → communicate → fork coordination → post-mortem → compensation3776. Formal verification complements but does NOT replace manual review and fuzz testing3787. Always verify signature malleability (low-s for ECDSA), nonce reuse, and signature replay protection3798. Cross-chain bridges require additional security layers: rate limiting, circuit breakers, tiered security3809. ERC-4626 vaults must prevent inflation attacks with virtual shares + assets38110. Flash loan resistance requires TWAP pricing, not spot prices for critical operations38211. Upgradeable contracts must have disabled initializers on implementation contracts38312. All admin functions should be behind timelock + multi-sig, never single-key control38413. Oracle prices must be validated for freshness (staleness threshold) and deviation38514. Economic security analysis must model worst-case market conditions, not average38615. Bug bounties must cover the protocol's total value secured (TVS) for adequate incentives387388## Implementation Examples389390### Security Analysis (Solidity — Reentrancy Guard)391```solidity392contract ProtectedVault {393 using SafeERC20 for IERC20;394 uint256 private _status = 1; // 1=unlocked 2=locked395 modifier nonReentrant() {396 require(_status == 1, "Reentrant call");397 _status = 2; _;398 _status = 1;399 }400 function withdraw(uint256 amount) external nonReentrant {401 uint256 bal = balances[msg.sender];402 require(bal >= amount, "Insufficient");403 balances[msg.sender] = bal - amount; // Effects first404 token.safeTransfer(msg.sender, amount); // Interaction last405 }406}407```408409### Formal Verification — Certora CVL410```cvl411methods {412 function totalAssets() external returns (uint256);413 function totalSupply() external returns (uint256);414}415invariant solvency()416 totalAssets() >= totalSupply()417 filtered on f { f.contract != currentContract }418```419 - references/bug-bounty-program.md — Bug Bounty Programs for Blockchain Projects420 - references/economic-security.md — Economic Security in Blockchain Systems421 - references/formal-verification-deep.md — Formal Verification for Smart Contracts422 - references/incident-response.md — Blockchain Incident Response423 - references/smart-contract-security.md — Smart Contract Security424 - references/threat-modeling.md — Threat Modeling for Blockchain Systems425 - references/blockchain-vulnerability-catalog.md — Common Blockchain Vulnerabilities Catalog426 - references/cross-chain-security.md — Cross-Chain Security Considerations427 - references/flash-loan-attack-patterns.md — Flash Loan Attack Patterns428429## Architecture Decision Trees430431```432Blockchain Security Approach433├── Audit phase?434│ ├── Pre-development → Threat model + formal spec435│ ├── Post-development → Smart contract audit + fuzzing436│ ├── Pre-deployment → Comprehensive security review + bug bounty437│ └── Post-deployment → Continuous monitoring + incident response438├── Vulnerability type?439│ ├── Reentrancy → ReentrancyGuard, checks-effects-interactions440│ ├── Access control → OpenZeppelin AccessControl, multisig441│ ├── Oracle manipulation → TWAP, multiple sources, circuit breaker442│ └── Math errors → SafeMath (pre-0.8), overflow checks (0.8+)443├── Formal verification needed?444│ ├── Yes (high-value) → Certora / Halmos (rule-based verification)445│ ├── Yes (ZK circuits) → Circom compiler checks, zkVerify446│ └── No → Standard audit + fuzz testing447└── Bug bounty program?448 ├── Yes → Immunefi / HackerOne (up to 10% of TVL)449 └── No → Internal audits only (higher residual risk)450```451452**Decision criteria**: Evaluate TVL at risk, regulatory requirements, team security maturity, and budget.453454## Implementation Patterns455456### Reentrancy Protection457```solidity458// blockchain-security/contracts/ReentrancyGuard.sol459pragma solidity ^0.8.20;460461abstract contract ReentrancyGuard {462 uint256 private constant _NOT_ENTERED = 1;463 uint256 private constant _ENTERED = 2;464 uint256 private _status;465466 modifier nonReentrant() {467 require(_status != _ENTERED, "ReentrancyGuard: reentrant call");468 _status = _ENTERED;469 _;470 _status = _NOT_ENTERED;471 }472}473```474475### Access Control with Timelock476```solidity477// blockchain-security/contracts/TimelockController.sol478contract TimelockController {479 uint256 public constant MIN_DELAY = 2 days;480 uint256 public constant GRACE_PERIOD = 14 days;481 mapping(bytes32 => bool) public queuedTransactions;482483 event Queued(bytes32 indexed txHash, address target, uint256 value, bytes data, uint256 executeTime);484 event Executed(bytes32 indexed txHash);485486 function queue(address target, uint256 value, bytes calldata data) external onlyRole(PROPOSER_ROLE) {487 bytes32 txHash = keccak256(abi.encode(target, value, data, block.timestamp + MIN_DELAY));488 queuedTransactions[txHash] = true;489 emit Queued(txHash, target, value, data, block.timestamp + MIN_DELAY);490 }491492 function execute(address target, uint256 value, bytes calldata data) external onlyRole(EXECUTOR_ROLE) {493 bytes32 txHash = keccak256(abi.encode(target, value, data, block.timestamp));494 require(queuedTransactions[txHash], "Not queued");495 delete queuedTransactions[txHash];496 (bool success,) = target.call{value: value}(data);497 require(success, "Execution failed");498 emit Executed(txHash);499 }500}501```502503## Production Considerations504505- **Audit frequency**: Full audit before mainnet deploy; re-audit on major upgrade (> 20% code change).506- **Bug bounty**: Launch Immunefi bounty (up to 10% TVL); scope all contracts and frontend.507- **Monitoring**: Deploy Forta/OpenZeppelin Defender Sentinel for transaction monitoring.508- **Incident response**: Pre-defined IR playbook; pause contracts within 30 min of exploit detection.509- **Insurance**: Purchase DeFi insurance (Nexus Mutual, Sherlock) for TVL coverage.510- **Responsible disclosure**: Maintain security.txt; private disclosure channel for vulnerability reports.511512## Anti-Patterns513514| Anti-Pattern | Consequence | Solution |515|---|---|---|516| Skipping threat model | Miss architecture-level vulnerabilities | Mandatory threat model before code |517| Only automated audits | Miss logic bugs | Manual review + automated + fuzzing |518| No timelock on upgrades | Compromised owner upgrades malicious code | Enforce minimum 48h timelock |519| Fixing bugs without re-audit | New bugs introduced | Re-audit > 20% code changes |520| No pause mechanism | Can't stop exploit in progress | Implement pausable + emergency stop |521522## Performance Optimization523524- **Gas-efficient access control**: Use bitmap-based roles (BitMaps) instead of array for role management.525- **Batch verification**: Verify multiple signatures in single operation for multisig.526- **Storage-efficient audits**: Use event-based audit trail instead of on-chain storage for non-critical logs.527- **Off-chain monitoring**: Use The Graph subgraph for security monitoring; avoid on-chain overhead.528- **Selective audit scope**: Focus formal verification on critical paths (token transfers, liquidations).529530## Security Considerations531532- **Checks-effects-interactions**: Always follow pattern: validate → update state → external calls.533- **Proxy security**: Use transparent proxy (EIP-1967) to avoid function selector collisions.534- **Access control**: Implement role-based access with OpenZeppelin AccessControl; avoid `onlyOwner`.535- **Signature replay**: Include domain separator, nonce, and chain ID; validate expiry.536- **Randomness**: Use Chainlink VRF for on-chain randomness; never use block.timestamp or blockhash.537- **Governance attack resistance**: Implement flash loan resistant voting; time-weighted voting power.538539## Phase540blockchain → blockchain-security