--- title: "Reentrancy" type: concept tags: [smart-contract, vulnerability, security] sources: [blockchain-security-auditor] last_updated: 2026-04-20 --- ## Definition 重入攻击(Reentrancy)是一种智能合约安全漏洞,攻击者通过在外部调用期间重新进入同一合约来操纵状态,导致同一笔资金被多次提取。 ## Vulnerability Pattern ```solidity // VULNERABLE: External call BEFORE state update function withdraw() external { uint256 amount = balances[msg.sender]; (bool success,) = msg.sender.call{value: amount}(""); balances[msg.sender] = 0; // State updated AFTER external call } ``` ## Attack Mechanism 1. 攻击者部署恶意合约 2. 将资金存入目标合约 3. 调用 withdraw() 4. 目标合约执行外部调用(发送 ETH) 5. 恶意合约的 receive() 在状态更新前被触发 6. 重新调用 withdraw() 7. 由于状态未更新,攻击者可再次提取资金 ## Mitigation - **Checks-Effects-Interactions**:先更新状态,再执行外部调用 - **ReentrancyGuard**:OpenZeppelin 提供的重入锁修饰符 - **Pull Payment**:使用 PullPayment 模式替代直接发送 ## Connections - [[Smart Contract Vulnerability]] ← is_type_of ← [[Reentrancy]] - [[Checks-Effects-Interactions]] ← prevents ← [[Reentrancy]] - [[ReentrancyGuard]] ← prevents ← [[Reentrancy]]