Files
nexus/wiki/concepts/ReentrancyGuard.md
2026-05-03 05:42:12 +08:00

1.3 KiB
Raw Blame History

title, type, tags, last_updated
title type tags last_updated
ReentrancyGuard concept
2026-05-01

Definition

ReentrancyGuard 是 OpenZeppelin 提供的修饰器modifier通过在函数入口设置 mutex 锁防止合约函数在执行过程中被递归调用re-entrancy从而避免重入攻击。

Implementation

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