首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这个修饰符nonReentrant是如何工作的?

这个修饰符nonReentrant是如何工作的?
EN

Ethereum用户
提问于 2021-10-24 12:26:25
回答 1查看 6K关注 0票数 1

这是地址0x0d4535644fFeC908e39a711A01852Be40Bfe1C97的源代码,修饰符nonReentrant能防止重入漏洞吗?

代码语言:javascript
复制
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;

constructor () internal {
    // The counter starts at one to prevent changing it from zero to a non-zero
    // value, which is a more expensive operation.
    _guardCounter = 1;
}

/**
 * @dev Prevents a contract from calling itself, directly or indirectly.
 * Calling a `nonReentrant` function from another `nonReentrant`
 * function is not supported. It is possible to prevent this from happening
 * by making the `nonReentrant` function external, and make it call a
 * `private` function that does the actual work.
 */
modifier nonReentrant() {
    _guardCounter += 1;
    uint256 localCounter = _guardCounter;
    _;
    require(localCounter == _guardCounter);
}

}

EN

回答 1

Ethereum用户

回答已采纳

发布于 2021-10-24 12:53:51

它基本上检查localCounter的值只增加了一个。这意味着函数只被调用一次(在事务中)。

实际的函数在_;上执行。在此之前,它将计数器增加1,并将值分配给局部变量(与全局变量_guardCounter相反)。如果函数自身调用,则代码再次进入此阶段,计数器再次增加一个(全局和本地)。

在函数完成执行后,它确保本地计数器与全局计数器相同。只有当函数只被调用一次时,本地值才是相同的,否则全局计数器已经增加了多次。如果它被多次调用,则执行将恢复。

票数 5
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/112128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档