Files
nexus/wiki/concepts/Reentrancy.md
2026-04-21 00:02:55 +08:00

41 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
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]]