Smart contract auditing: Solidity, reentrancy, flash loans y DeFi exploits
· 3 min de lectura
Los smart contracts almacenan miles de millones en DeFi y son target prioritario. Aprende el stack Solidity/EVM, patrones de ataque (reentrancy, oracle manipulation, flash loan abuse), herramientas (Slither, Mythril, Foundry) y casos famosos (DAO, Poly Network, Ronin).
Los smart contracts son programas que ejecutan lógica financiera en blockchains públicas (Ethereum, Polygon, Arbitrum, BSC, Solana). En 2026 DeFi (Decentralized Finance) maneja más de 100 mil millones de USD en valor bloqueado en protocolos como Uniswap, Aave, Compound, Lido. Un bug en un smart contract no se parchea con un patch: puede causar pérdidas instantáneas de millones, irreversibles por diseño (blockchain immutability). Eso ha convertido el smart contract auditing en una de las especializaciones mejor pagadas de la industria: auditors experimentados facturan 200-500 USD/hora, y los bug bounties en DeFi pagan rutinariamente 100k-1M+ USD por hallazgos críticos.
Esta lección cubre el stack Solidity/EVM, los patrones de ataque canónicos (reentrancy, oracle manipulation, flash loan abuse, access control, integer overflow), las herramientas modernas (Slither, Mythril, Foundry, Echidna), casos famosos (DAO 2016, Parity 2017, Poly Network 2021, Ronin 2022, Euler 2023), y la metodología profesional de auditing. Es la lección de arranque de la Tanda 7, enfocada en especializaciones técnicas profundas.
Pruebas en testnets o environments propios. Interactuar maliciosamente con smart contracts productivos ajenos puede ser delito según jurisdicción, y los funds robados son trazables en blockchain.
El stack smart contract#

Workflow típico:
- Solidity (lenguaje): el más usado. Alternativas: Vyper, Yul assembly.
- Compilation: solc compila a EVM bytecode.
- Deployment: transaction crea contract en blockchain, código immutable.
- Interaction: users envían transactions llamando funciones.
- State: variables almacenadas en storage persistente.
Cada transaction cuesta gas (transacción fee). Loops caros, optimization importante.
EVM essentials#
Ethereum Virtual Machine:
- Stack-based execution.
- 256-bit word size.
- Memory (volátil per transaction) vs Storage (persistente, caro).
- CALL opcode para invocar otros contracts.
- No floating point; math en integers.
- Gas limit per transaction prevents infinite loops.
Reversions: si function revierte, state changes se deshacen (atomicity). Important para defense.
Patrones de ataque clásicos#
Reentrancy#
El clásico, descubrimiento inicial con DAO hack 2016 (60M USD). Pattern:
// VULNERABLE
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount);
(bool ok,) = msg.sender.call{value: amount}(""); // external call
require(ok);
balances[msg.sender] -= amount; // update DESPUÉS
}
Attacker deploys contract que, en fallback de receive(), llama withdraw otra vez antes de que el update happens. Funds drained multiple times.
Fix (checks-effects-interactions pattern):
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount; // update ANTES
(bool ok,) = msg.sender.call{value: amount}("");
require(ok);
}
O usar ReentrancyGuard de OpenZeppelin.
Oracle manipulation#
Protocols basan prices on oracles (Chainlink, custom). Si oracle manipulable → attacker fakes prices, exploits trades.
Common vector: TWAP (time-weighted average price) oracles manipulable con flash loans spiking price momentarily.
Flash loan abuse#
Flash loans (Aave, dYdX): borrow sin colateral, repay en same transaction. Enables:
- Price manipulation.
- Governance attacks (vote con tokens borrowed).
- Arbitrage malicious.
- Combo attacks orquestados.
Flash loan + reentrancy + oracle manipulation = recurrent combo.
Access control#
Functions marked public cuando deberían ser onlyOwner. Common beginner mistake. Famous: Parity wallet 2017 (300M USD frozen porque init function pública).
Integer overflow/underflow#
Solidity <0.8.0 no tenía checked math. Addition overflowing wrapped around. Modernos (0.8.0+) revert automatically pero contracts antiguos vulnerable.
Front-running (MEV)#
Transactions en mempool visibles. Bots front-run profitable transactions insertando sus propias con higher gas. MEV (Maximal Extractable Value) es industry en sí misma. Flashbots, MEV-Boost mitigate partially.
Sandwich attacks#
Specific MEV: attacker places buy order antes + sell order después de user's buy, extracting slippage.
Delegatecall abuse#
delegatecall executes external code en context de calling contract (storage, msg.sender). Si uncontrolled → attacker overwrites storage. Parity 2 incident canónico.
Signature replay#
Signed messages re-usable si no nonce. Attack: capture signature, replay después.
DoS attacks#
- Blocking withdraw by pushing to array con infinite growth.
- Gas limit exhaustion en critical functions.
- Griefing attacks disrupting normal operation.
Herramientas modernas#

Slither#
Static analyzer de Trail of Bits. Fastest first pass:
pip install slither-analyzer
slither contracts/
# Devuelve: reentrancy vulns, missing access controls, best practices
Detectors para 100+ patterns. Imperdible para toda audit.
Mythril#
Symbolic execution. Explora paths posibles:
pip install mythril
myth analyze contracts/MyContract.sol
# Tiempo mayor pero deeper analysis
Foundry#
Development framework moderno, test en Solidity:
curl -L https://foundry.paradigm.xyz | bash
foundryup
forge init project
forge test -vvv
forge test --fuzz-runs 10000
Forge fuzz testing integrado: writes property tests, framework genera inputs random testing invariants.
Echidna#
Property-based fuzzer dedicado:
contract Test {
function echidna_balance_nonzero() public view returns (bool) {
return address(this).balance > 0;
}
}
Echidna busca inputs rompiendo property.
Manticore#
Symbolic execution alternative.
Tenderly#
Observability platform: transaction debugging, simulations.
Etherscan#
Blockchain explorer: contract source (si verified), transaction history.
Casos famosos#
- The DAO (2016): reentrancy, 60M USD, Ethereum hard fork creating ETC.
- Parity multisig (2017): 300M USD permanently frozen por init function bug.
- MakerDAO Black Thursday (2020): oracle issues + gas spike durante crash.
- bZx (2020): múltiples flash loan exploits.
- Harvest Finance (2020): oracle manipulation, 24M.
- Poly Network (2021): 611M USD stolen y returned.
- Wormhole (2022): cross-chain bridge, 325M.
- Ronin Network (2022): 625M USD, North Korea attribution (Axie Infinity).
- Nomad Bridge (2022): 190M.
- Euler Finance (2023): 197M exploited, mayoría returned.
- Multichain (2023): 125M+ en varios incidents.
- LastPass (2022) → cryptocurrency theft (2023+): secrets leak led to on-chain theft.
- Numerous DeFi hacks 2024-2026: pattern persists, mitigation improves slowly.
Trail of Bits, ConsenSys Diligence, OpenZeppelin, Trail of Bits, CertiK publish auditing public blog posts analyzing each incident.
Metodología de audit#
Industry-standard approach:
Fase 1 - Scope:
- Qué contracts, cuales features, deadlines.
- Access a documentation, previous audits.
- Communication channels con dev team.
Fase 2 - Review inicial:
- Architecture understanding.
- Business logic comprehension.
- Integrations (oracles, external contracts).
Fase 3 - Static analysis:
- Slither.
- Linting.
- Manual code review.
Fase 4 - Dynamic testing:
- Foundry/Hardhat tests.
- Fuzz testing con Echidna.
- Symbolic execution con Mythril.
Fase 5 - Attack scenarios:
- Red team specific exploits.
- Flash loan attack simulations.
- Economic attack modeling.
Fase 6 - Report:
- Findings prioritized (Critical/High/Medium/Low/Info).
- Specific code references.
- Recommendations.
- Remediation verification en follow-up.
Bug bounty en DeFi#
Programs principales:
- Immunefi: dominant platform, DeFi-focused, pays largest bounties.
- Code4rena: contests competitivos.
- Sherlock: contest-based auditing.
- HackerOne / direct programs: various.
Top payouts documented en Immunefi:
- MakerDAO: $10M scoping.
- Aave: $1M crítico.
- Compound: $1M crítico.
- Yearn: $1M crítico.
Múltiples auditors han ganado 500k+ USD en single hallazgo.
Walkthrough: audit canónica#
Para fijar el patrón, un flujo contra contract DeFi staking típico:
Paso 1 — contexto: review README, understand business logic, identify external dependencies (oracles, bridges, tokens).
Paso 2 — Slither pass:
slither contracts/Staking.sol --exclude-dependencies
# Output: 3 reentrancy warnings, 1 timestamp dependence, 2 unused returns
Paso 3 — manual review:
- Check cada función
external/public. - Review state changes order.
- Verify access modifiers (onlyOwner, onlyRole).
- Identify value transfers (call, transfer, send).
Paso 4 — fuzz tests Foundry:
function testFuzzWithdraw(uint amount) public {
deposit(1000 ether);
vm.assume(amount < 1000 ether);
withdraw(amount);
assertEq(balanceOf(user), 1000 ether - amount);
}
Paso 5 — exploit PoC:
Para cada finding, write actual exploit contract demonstrating:
contract Exploit {
Staking victim;
function attack() external payable {
victim.deposit{value: 1 ether}();
victim.withdraw(1 ether); // triggers reentrancy
}
receive() external payable {
if (address(victim).balance > 0) {
victim.withdraw(1 ether);
}
}
}
Paso 6 — report draft:
Each finding: severity, impact, PoC, recommendation con code example.
Paso 7 — discussion con team: debrief, clarify, remediate, re-review.
Paso 8 — final report + publication (con permission del team).
Economic attacks#
Beyond code bugs, attacks económicos:
- Governance capture: buy voting power to pass malicious proposals.
- Treasury draining: multi-step orchestration de protocol funds.
- Liquidity migration: move funds en coordinated way disrupting markets.
- Yield manipulation: game rewards distribution.
Require understanding de tokenomics + game theory beyond pure code review. Auditors mejores combinan both.
Errores comunes del developer#
- No usar OpenZeppelin libraries (reinventing wheel, introducing bugs).
- Compiler version pin sin updates (bugs en old solc).
- Centralized ownership sin timelock / multisig.
- Insufficient test coverage.
- No invariant testing.
- Ignoring compiler warnings.
- Hardcoded addresses en production.
- No bug bounty program.
Errores comunes del auditor#
- Rushing through code (adequate time crítico).
- Missing economic attack vectors (focus en code, no en game theory).
- Overlooking external dependencies.
- No testing actual exploits (just theoretical).
- Report lacking specificity.
Preguntas frecuentes#
¿Vale la pena carrera en smart contract auditing?#
Yes, actively. High demand, high pay, growth sustained. Entry: participate Code4rena, build portfolio, contribute community.
¿Solidity vs Rust (Solana)?#
Both relevant. Solidity dominates EVM chains (Ethereum + L2s + BSC + Polygon). Rust (Anchor framework) Solana ecosystem. Rust para Starknet también. Ethereum larger market.
¿Immutability es problema o feature?#
Both. Feature: trustless, no central authority can change. Problema: bugs irreparables. Mitigation: upgradeable proxy patterns (OpenZeppelin), timelocks, admin controls with multisig.
¿Formal verification?#
Mathematical proofs of correctness. Tools: Certora, K-Framework. Expensive (100k+ USD) but highest assurance. Para critical protocols (MakerDAO, Aave) viable.
¿Cross-chain bridges son más riesky?#
Yes significantly. Bridge hacks dominated 2022: Ronin, Wormhole, Nomad, Multichain. Complex systems, multiple attack surfaces. Mitigation ongoing con native bridges + verifiable proofs.
¿Dónde practico?#
El laboratorio signinbleed de whoami-labs incluye deployed contracts vulnerables representative: reentrancy, access control, oracle manipulation. Testnet environment. Practice exploitation + remediation.
¿Ethereum vs L2s security differences?#
L2s (Arbitrum, Optimism, Base, zkSync) inherit security Ethereum base layer, pero add specific risks: bridge contracts, sequencer centralization, proof systems. Audit scope depends on L2 specifically.
¿Zero-knowledge proofs en audits?#
Emerging area. ZK circuits (Circom, Noir) tienen their own vuln classes. Specialized auditors required (ZK Security, Veridise). Mercado growing rápidamente.
¿MEV mitigation estado actual?#
Ongoing. Flashbots SUAVE, Protect RPC, MEV-Boost intentan reducir harmful MEV. Perfect solution absent, pero significantly improved vs peak era 2021-2022.
¿Formal verification cost-benefit?#
High cost (100k-500k USD typical engagement). Para protocols manejando 100M+ TVL, cost-effective. Smaller protocols: comprehensive audit + fuzzing sufficient usually.
¿Centralized vs decentralized auditing?#
Trad firms (Trail of Bits, OpenZeppelin, ConsenSys Diligence): deep expertise, high quality, slower, expensive. Decentralized (Code4rena, Sherlock): competitive contests, faster, broader eye coverage. Many protocols use both.
Resumen#
- Smart contracts manejan 100B+ USD en DeFi; bugs = losses inmediatas irreversibles.
- Stack: Solidity → EVM bytecode → deployed → user transactions.
- Patrones: reentrancy, oracle manipulation, flash loans, access control, delegatecall, MEV.
- Herramientas: Slither (static), Mythril (symbolic), Foundry (testing + fuzzing), Echidna (property-based).
- Casos: DAO 2016, Parity 2017, Poly 2021, Ronin 2022 (625M), Euler 2023, multiples anuales.
- Metodología: scope → review → static → dynamic → attack scenarios → report.
- Bug bounty: Immunefi, Code4rena, Sherlock pagando 100k-1M+ regularmente.
- Carrera growing, salarios competitivos, demand sustained.
La próxima lección entra en kernel exploitation moderno, saliendo del mundo DeFi para volver al low-level classical pero con techniques 2026 que bypassen protections como SMEP, SMAP, KASLR y CFI implementadas en kernels modernos. Es un salto desde high-level smart contract bugs hacia el otro extremo del spectrum, donde cada byte importa y el debugging requiere comprensión profunda de arquitecturas x86-64 y ARM64 modernas en el contexto de sistemas operativos actuales usados masivamente en producción a lo largo del mundo real actual de infraestructura corporativa global contemporánea de estos años en curso.