Michael.W基于Foundry精读Openzeppelin第57期——ReentrancyGuard.sol

news2025/3/1 13:18:15

Michael.W基于Foundry精读Openzeppelin第57期——ReentrancyGuard.sol

      • 0. 版本
        • 0.1 ReentrancyGuard.sol
      • 1. 目标合约
      • 2. 代码精读
        • 2.1 constructor()
        • 2.2 modifier nonReentrant()

0. 版本

[openzeppelin]:v4.8.3,[forge-std]:v1.5.6

0.1 ReentrancyGuard.sol

Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/security/ReentrancyGuard.sol

ReentrancyGuard库是一个用来防御函数重入的工具库。函数被修饰器nonReentrant修饰可确保其无法被嵌套(重入)调用。本库的代码逻辑上只实现了一个重入锁,所以被nonReentrant修饰的函数之间也是无法相互调用的。

1. 目标合约

继承ReentrancyGuard合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/src/security/MockReentrancyGuard.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/security/ReentrancyGuard.sol";

contract MockReentrancyGuard is ReentrancyGuard {
    uint public counter;

    function addWithoutNonReentrant() external {
        _add();
    }

    function callWithoutNonReentrant(address target, bytes calldata calldata_) external {
        _call(target, calldata_);
    }

    function addWithNonReentrant() external nonReentrant {
        _add();
    }

    function callWithNonReentrant(address target, bytes calldata calldata_) external nonReentrant {
        _call(target, calldata_);
    }

    function _call(address target, bytes calldata calldata_) private {
        (bool ok, bytes memory returnData) = target.call(calldata_);
        require(ok, string(returnData));
        counter += 10;
    }

    function _add() private {
        ++counter;
    }
}

全部foundry测试合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/security/ReentrancyGuard/ReentrancyGuard.t.sol

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/security/ReentrancyGuard/Reentrant.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

contract Reentrant {
    address private target;

    constructor(address targetAddress){
        target = targetAddress;
    }

    function callback(bytes calldata calldata_) external {
        (bool ok, bytes memory returnData) = target.call(calldata_);
        if (!ok) {
            // pull the revert msg out of the return data of the call
            uint len = returnData.length;
            if (len > 4 && bytes4(returnData) == bytes4(keccak256(bytes("Error(string)")))) {
                // get returnData[4:] in memory bytes
                bytes memory encodedRevertMsg = new bytes(len - 4);
                for (uint i = 4; i < len; ++i) {
                    encodedRevertMsg[i - 4] = returnData[i];
                }
                revert(abi.decode(encodedRevertMsg, (string)));
            } else {
                revert();
            }
        }
    }
}

2. 代码精读

2.1 constructor()
	// 常量标识,标志着合约方法"未被进入"的状态
    uint256 private constant _NOT_ENTERED = 1;
    // 常量标识,标志着合约方法"已被进入"的状态
    uint256 private constant _ENTERED = 2;
    
    // 标识合约被进入状态的全局变量
    // 注:该处使用uint256类型而不是bool的原因见下
    uint256 private _status;

    // 初始化函数
    constructor() {
        // 将合约状态设置为"未被进入"
        _status = _NOT_ENTERED;
    }

为什么_status不选择bool类型而使用uint256类型?

答:更新bool类型的gas消耗要比uint256或者其他占满一个word(32字节)的类型都贵。每一个写操作都会携带额外的SLOAD读出slot中的值,接着更新其中bool类型对应的bit,最后才进行slot的回写。这是编译器对合约升级和指针混叠的一种防御措施,无法禁用。

尽管将具有flag属性的状态变量设定为非0值会使得合约部署费用增高,但却可以减少每次调用被nonReentrant修饰方法的gas消耗。

2.2 modifier nonReentrant()

用于防重入的修饰器,防止合约方法直接或间接调用自身。

注:合约内两个被该修饰器修饰的方法无法进行相互调用。可通过将各自逻辑封装成private函数,并用nonReentrant修饰的external函数封装以上private函数来解决部分需求。

    modifier nonReentrant() {
        // 进入方法前的准备工作
        _nonReentrantBefore();
        _;
        // 执行完整个方法后的收尾工作
        _nonReentrantAfter();
    }

    // 进入方法前的准备工作
    function _nonReentrantBefore() private {
        // 要求进入函数前合约标识状态为"未进入",即之前没有与本合约中被nonReentrant修饰的方法交互过。	
        // 注:此处的检查会将产生重入的调用revert
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // 将合约标识状态更改为"已进入"
        _status = _ENTERED;
    }

    // 执行完整个方法后的收尾工作
    function _nonReentrantAfter() private {
        // 将合约标识状态更改回"未进入"。由于合约标识状态最后又改回了前值,
        // 即本次方法调用的结果并没有导致该slot的值发生变化,此处将触发gas的返还。
        // 具体细节参见:https://eips.ethereum.org/EIPS/eip-2200
        _status = _NOT_ENTERED;
    }

foundry代码验证:

contract ReentrancyGuardTest is Test {
    MockReentrancyGuard private _testing = new MockReentrancyGuard();
    Reentrant private _reentrant = new Reentrant(address(_testing));

    function test_LocalCall() external {
        // A and B are both local external methods in one contract

        // case 1: A without nonReentrant -> B without nonReentrant
        // [PASS]
        // call {addWithoutNonReentrant} in {callWithoutNonReentrant}
        assertEq(_testing.counter(), 0);
        bytes memory calldata_ = abi.encodeCall(_testing.addWithoutNonReentrant, ());
        _testing.callWithoutNonReentrant(address(_testing), calldata_);
        uint counterValue = _testing.counter();
        assertEq(counterValue, 1 + 10);

        // case 2: A without nonReentrant -> B with nonReentrant
        // [PASS]
        // call {addWithNonReentrant} in {callWithoutNonReentrant}
        calldata_ = abi.encodeCall(_testing.addWithNonReentrant, ());
        _testing.callWithoutNonReentrant(address(_testing), calldata_);
        assertEq(_testing.counter(), counterValue + 1 + 10);
        counterValue = _testing.counter();

        // case 3: A with nonReentrant -> B without nonReentrant
        // [PASS]
        // call {addWithoutNonReentrant} in {callWithNonReentrant}
        calldata_ = abi.encodeCall(_testing.addWithoutNonReentrant, ());
        _testing.callWithNonReentrant(address(_testing), calldata_);
        assertEq(_testing.counter(), counterValue + 1 + 10);

        // case 4: A with nonReentrant -> B with nonReentrant
        // [REVERT]
        // call {addWithNonReentrant} in {callWithNonReentrant}
        calldata_ = abi.encodeCall(_testing.addWithNonReentrant, ());
        // the provided string in `require(bool,string)` is abi-encoded as if it was a call to a function `Error(string)`
        bytes memory encodedRevertMsg = abi.encodeWithSignature("Error(string)", "ReentrancyGuard: reentrant call");
        vm.expectRevert(encodedRevertMsg);
        _testing.callWithNonReentrant(address(_testing), calldata_);
    }

    function test_ExternalCall() external {
        // A and B are both local external methods in one contract
        // C is an external method in another contract

        // case 1: A without nonReentrant -> B -> C without nonReentrant
        // [PASS]
        // {callWithoutNonReentrant} -> {Reentrant.callback} -> {addWithoutNonReentrant}
        assertEq(_testing.counter(), 0);
        bytes memory calldata_ = abi.encodeCall(
            _reentrant.callback,
            (
                abi.encodeCall(_testing.addWithoutNonReentrant, ())
            )
        );
        _testing.callWithoutNonReentrant(address(_reentrant), calldata_);
        uint counterValue = _testing.counter();
        assertEq(counterValue, 1 + 10);

        // case 2: A without nonReentrant -> B -> C with nonReentrant
        // [PASS]
        // {callWithoutNonReentrant} -> {Reentrant.callback} -> {addWithNonReentrant}
        calldata_ = abi.encodeCall(
            _reentrant.callback,
            (
                abi.encodeCall(_testing.addWithNonReentrant, ())
            )
        );
        _testing.callWithoutNonReentrant(address(_reentrant), calldata_);
        assertEq(_testing.counter(), counterValue + 1 + 10);
        counterValue = _testing.counter();

        // case 3: A with nonReentrant -> B -> C without nonReentrant
        // [PASS]
        // {callWithNonReentrant} -> {Reentrant.callback} -> {addWithoutNonReentrant}
        calldata_ = abi.encodeCall(
            _reentrant.callback,
            (
                abi.encodeCall(_testing.addWithoutNonReentrant, ())
            )
        );
        _testing.callWithNonReentrant(address(_reentrant), calldata_);
        assertEq(_testing.counter(), counterValue + 1 + 10);

        // case 4: A with nonReentrant -> B -> C with nonReentrant
        // [REVERT]
        // {callWithNonReentrant} -> {Reentrant.callback} -> {addWithNonReentrant}
        calldata_ = abi.encodeCall(
            _reentrant.callback,
            (
                abi.encodeCall(_testing.addWithNonReentrant, ())
            )
        );
        // the provided string in `require(bool,string)` is abi-encoded as if it was a call to a function `Error(string)`
        bytes memory encodedRevertMsg = abi.encodeWithSignature("Error(string)", "ReentrancyGuard: reentrant call");
        vm.expectRevert(encodedRevertMsg);
        _testing.callWithNonReentrant(address(_reentrant), calldata_);
    }
}

ps:
本人热爱图灵,热爱中本聪,热爱V神。
以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。
同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下!
如果需要转发,麻烦注明作者。十分感谢!

在这里插入图片描述
公众号名称:后现代泼痞浪漫主义奠基人

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1814624.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

docker-compose Install wiki

wiki 前言 最强大和可扩展的开源Wiki软件,使用Wiki.js漂亮而直观的界面,让编写文档成为一种乐趣 前提要求 安装 docker docker-compose 参考创建一键安装wiki wiki 安装目录/wikiwiki端口83admin 端口 84postgres 端口5432postgres 库 wikipostgres 用户 wikijspostgres 密…

【启明智显方案分享】ESP32-S3与GPT AI融合的智能问答嵌入式设备应用解决方案

一、引言 随着物联网&#xff08;IoT&#xff09;和人工智能&#xff08;AI&#xff09;技术的飞速发展&#xff0c;嵌入式设备正逐渐变得智能化。本解决方案是启明智显通过结合ESP32-S3的低功耗、高性能特性和GPT&#xff08;Generative Pre-trained Transformer&#xff09;…

简单了解java中线程的使用

线程 1、线程的相关概念 1.1、并行和并发 并行&#xff1a;在同一时刻&#xff0c;有多个任务在多个CPU上同时执行 并发&#xff1a;在同一时刻&#xff0c;有多个任务在单个CPU上交替执行 1.2、进程和线程 进程&#xff1a;就是在多任务管理系统中&#xff0c;每个独立执…

【MySQL】表的基本增删查改(结合案例)

文章目录 1.前言2.插入数据&#xff08;Create&#xff09;2.1案例2.2单行数据全列插入2.3多行数据指定列插入2.4插入否则更新2.5替换 3. 读取数据(Retireve)3.1案例3.2全列查询3.3指定列查询3.4查询字段为表达式3.5为查询结果起别名3.6去重3.7where条件3.7.1案例 3.8排序3.9筛…

Post Microsoft Build and AI Day 北京开发者日

Microsoft Build 开发者大会 Microsoft Build 开发者大会是微软每年一次的开发者技术盛会&#xff0c;旨在向全球开发者展示微软最新的技术、产品和服务。 刚刚过去的 2024 Microsoft Build 开发者大会围绕 Copilot、生成式 AI、应用程序安全、云平台、低代码等多个技术方向&a…

运维系列.在Docker中使用Grafana

运维专题 在Docker中使用Grafana - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:https://blog.csdn.net/qq_2855026…

Java对象的序列化与反序列化

序列化和反序列化是什么 当两个进程远程通信时&#xff0c;彼此可以发送各种类型的数据。无论是何种类型的数据&#xff0c;都会以二进制序列的形式在网络上传送。比如&#xff1a;我们可以通过http协议发生字符串信息&#xff1b;我们也可以在网络上直接发生Java对象。发送方…

【linux】信号(三)

本章节将会围绕信号处理进行展开讲解 目录 回顾一下&#xff1a;历史问题&#xff1a;内核态 VS 用户态地址空间&#xff1a;键盘的输出如何被检测到&#xff1a;OS如何正常运行&#xff1a;如何执行系统调用&#xff1a; 信号的处理&#xff1a;sigaction&#xff1a;信号的…

QML学习十九:ttf字体库使用

一、前言 在使用QML时&#xff0c;常常自定义按钮&#xff0c;按钮上有显示个图标&#xff0c;其实&#xff0c;那不是图标&#xff0c;是文本&#xff0c;如何显示&#xff1f; 本篇记录&#xff0c;如何导入阿里巴巴字体库&#xff0c;并调用显示。 二、阿里巴巴字体库下载…

分布式系统设计指南

目录 一、分布式简介 二、分布式系统核心概念 2.1 CAP 理论 2.2 BASE 原理 三、分布式系统设计 3.1 微服务拆分 3.2 通信模型 3.3 负载均衡 3.4 数据一致性 3.5 容错限流 3.6 扩展性 3.7 监控预警 3.8 自动化运维 一、分布式简介 分布式系统是由单体应用发展而来的&#xff…

统计绘图 | 既能统计分析又能可视化绘制的技能

在典型的探索性数据分析工作流程中&#xff0c;数据可视化和统计建模是两个不同的阶段&#xff0c;而我们也希望能够在最终的可视化结果中将相关统计指标呈现出来&#xff0c;如何让将两种有效结合&#xff0c;使得数据探索更加简单快捷呢&#xff1f;今天这篇推文就告诉你如何…

使用 Scapy 库编写 TCP 窗口大小探测攻击脚本

一、介绍 1.1 概述 TCP窗口大小探测攻击是一种信息收集攻击&#xff0c;攻击者通过向目标服务器发送特制的TCP数据包&#xff0c;探测目标服务器的TCP接收窗口大小&#xff08;TCP Window Size&#xff09;。了解目标服务器的TCP接收窗口大小&#xff0c;可以帮助攻击者优化后…

Spring Web MVC之过滤器Filter和拦截器HandlerInterceptor的区别和用法

作用时机不一样 Spring 框架有一个很重要的类DispatcherServlet。这个类继承了HttpServlet&#xff0c;HttpServlet实现了Servlet接口。相当于图片中的Servlet。所有和Spring框架相关配置&#xff0c;例如注解、xml配置、其他数据库连接配置、bean配置、拦截器配置等其他配置&…

深度学习研究生的职业前景:未来趋势与机遇

deep learning 深度学习研究生的职业前景&#xff1a;未来趋势与机遇一、深度学习的应用领域1. 计算机视觉2. 自然语言处理&#xff08;NLP&#xff09;3. 数据分析4. 游戏开发5. 健康医疗 二、职业机遇与挑战1. 工作机会2. 竞争与挑战3. 薪资前景 三、职业发展策略对于深度学习…

国外创意二维码应用:飞利浦旧物翻新活动,传播可持续性消费的重要性!

你知道去年有超过1000万件礼物被扔进了垃圾场吗? 这些被丢弃的物品中有许多仍在使用&#xff0c;飞利浦希望改变这种浪费现象。 去年的地球日&#xff0c;飞利浦策划了一场名为“Better than New” 的二维码营销活动。他们发布了一个视频&#xff0c;通过这个短视频将所有最终…

钉钉魔点指纹考勤机多少钱一台,指纹门禁考勤一体机价格

钉钉魔点指纹考勤机一台多少钱呢&#xff0c;指纹门禁考勤一体机的价格又是多少 钉钉魔点 X2 智能指纹考勤门禁一体机的参考价格是 359 元。 其具体参数情况如下&#xff1a; 产品类型&#xff1a;属于指纹考勤门禁一体机&#xff1b; 验证方式&#xff1a;为电容指纹&…

4、优化阶段

优化概述 编译程序总框架&#xff1a; 优化:对程序进行各种等价变换&#xff0c;使得从变换后的程序出发&#xff0c;能生成更有效的目标代码。 等价:不改变程序的运行结果。 有效:目标代码运行时间短&#xff0c;占用存储空间小。 >目的 产生更高效的代码 >遵循的原则 …

618值得购买的东西有哪些?618四款必囤好物清单分享!

随着618购物狂欢节的脚步日益临近&#xff0c;身为数码领域的资深爱好者&#xff0c;我深感有必要为大家推荐一系列经过精心挑选的数码产品精选。无论是热衷于科技前沿的探索者&#xff0c;还是希望通过智能设备提升生活品质的时尚达人&#xff0c;本文所介绍的每一款数码产品都…

MT2096 数列分段

代码&#xff1a; #include <bits/stdc.h> using namespace std; const int N 1e5 10; int n, m; int a[N]; int ans 1; int main() {cin >> n >> m;for (int i 1; i < n; i)cin >> a[i];int num 0;for (int i 1; i < n; i){if (num a[i…

(1)图像识别yolov5—安装教程

目录 1、安装YOLOv5: 2、下载预训练模型: 3、识别示例图片: 1、安装YOLOv5: 首先,你需要在你的计算机上下载 YOLOv5 的文件包,下载链接:https://github.com/ultralytics/yolov5。下载后对压缩文件进行解压。 通常使用 YOLOv5 识别物体,需要安装必要的 依赖…