40 lines
1.3 KiB
Markdown
40 lines
1.3 KiB
Markdown
---
|
||
title: "ReentrancyGuard"
|
||
type: concept
|
||
tags: []
|
||
last_updated: 2026-05-01
|
||
---
|
||
|
||
## Definition
|
||
ReentrancyGuard 是 OpenZeppelin 提供的修饰器(modifier),通过在函数入口设置 mutex 锁,防止合约函数在执行过程中被递归调用(re-entrancy),从而避免重入攻击。
|
||
|
||
## Implementation
|
||
```solidity
|
||
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
|
||
|
||
contract Vault is ReentrancyGuard {
|
||
function withdraw() external nonReentrant {
|
||
// ...
|
||
msg.sender.call{value: amount}("");
|
||
// 递归调用此函数会被 revert
|
||
}
|
||
}
|
||
```
|
||
|
||
## Limitations
|
||
- **不是万能药**:ReentrancyGuard 防止同一合约被递归调用,但不防止**跨合约**重入(跨合约重入需配合 ChecksEffectsInteractions 原则)
|
||
- **Gas 成本**:每次 nonReentrant 检查约消耗 200 gas
|
||
- **OpenZeppelin v5 改进**:v5 版本优化了检查逻辑,降低了 gas 成本
|
||
|
||
## 与 ChecksEffectsInteractions 的关系
|
||
两者互补:
|
||
- ChecksEffectsInteractions 是**设计原则**——正确顺序的结构化思维
|
||
- ReentrancyGuard 是**工程手段**——即使违反 CEI 也能防止单合约重入
|
||
|
||
最佳实践:**同时使用两者**,Guard 作为最后防线,CEI 作为代码结构规范。
|
||
|
||
## Sources
|
||
- [[engineering-solidity-smart-contract-engineer]]
|
||
- [[The-DAO]]
|
||
- [[OpenZeppelin]]
|