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

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

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神。
以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。
同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下!
如果需要转发,麻烦注明作者。十分感谢!

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

  • 11
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 赖春华是一位专注于Cloud Foundry云平台研究的学者。Cloud Foundry是一种开放源代码的云平台,旨在简化开发、部署和运维应用程序。赖春华通过对Cloud Foundry进行研究,可以得出以下几点结论。 首先,Cloud Foundry具有很高的灵活性和可扩展性。它可以支持多种编程语言和框架,并且可以运行于多个云提供商的基础设施上。这意味着开发人员可以选择自己喜欢的工具和环境来构建和部署应用程序,而不受限于特定的技术栈或云服务提供商。 其次,Cloud Foundry提供了完整的开发、部署和运维工具链。它包括了一套完整的命令行工具和用户界面,可以帮助开发人员快速创建、部署和管理应用程序。这些工具提供了自动化的部署过程、监控和日志记录功能,使得应用程序开发和运维变得更加简单和高效。 另外,Cloud Foundry还具有高可靠性和弹性。它使用容器化技术来隔离应用程序,确保它们能够在不同的环境中平稳运行。同时,它具有自动扩展功能,可以根据应用程序的负载情况来自动调整资源的分配,以保证应用程序的性能和稳定性。 最后,通过研究Cloud Foundry,赖春华发现它可以在多个行业和场景中应用。无论是企业内部的应用程序还是公有云上的应用程序,Cloud Foundry都可以为其提供可靠的支持和高效的运维。它的开放性和灵活性使得开发人员能够快速响应市场变化和用户需求。 总之,赖春华的Cloud Foundry云平台研究表明,Cloud Foundry是一种强大而灵活的云平台,可以帮助开发人员简化应用程序的开发、部署和运维过程,并提供高可靠性和弹性的支持。它具有广泛的适用性,对于各种规模和行业的应用程序都能够提供有效的解决方案。 ### 回答2: 赖春华云平台研究一主要涉及cloud foundry云平台的研究。Cloud Foundry是一种开源的云平台,它为应用程序开发人员提供了一种简单、高效、灵活的方式来部署、运行和管理应用程序。这种平台具有很多优点,使得它成为各种企业和组织的首选。 首先,Cloud Foundry提供了一种容器化的方法来打包和部署应用程序。它使用容器技术,如Docker,将应用程序与其依赖项隔离开来,并提供了一种可移植和可扩展的部署方式。这使得应用程序的部署变得简单而高效。 其次,Cloud Foundry具有高度的自动化和可编程性。它提供了丰富的API和命令行工具,使得开发人员能够通过代码来管理和配置整个平台。这种可编程性带来了更高的灵活性和可扩展性,使得开发人员能够根据自己的需求自定义和扩展平台功能。 另外,Cloud Foundry提供了强大的监控和日志管理功能。开发人员可以通过平台的监控工具来实时监测应用程序的性能和健康状态,及时发现问题并作出调整。同时,平台还提供了日志管理功能,帮助开发人员跟踪和分析应用程序的日志信息,以便定位和解决问题。 最后,Cloud Foundry具有良好的可扩展性和可靠性。它支持多种云服务提供商,如AWS、Azure和Google Cloud,使得开发人员能够根据自己的需求选择合适的云环境。同时,平台还支持多个应用程序实例的部署和自动负载均衡,以确保应用程序的高可用性和弹性扩展性。 总之,赖春华云平台研究一主要关注cloud foundry云平台的各种功能和优势。这种平台提供了简单、高效、灵活的应用程序部署和管理方式,支持容器化技术、自动化和可编程性,具有强大的监控和日志管理功能,以及良好的可扩展性和可靠性。 ### 回答3: 赖春华是一位研究Cloud Foundry云平台的专家。Cloud Foundry是一个开源的云平台,支持开发人员在云中构建、部署和扩展应用程序。它提供了一个统一的平台,可以简化应用程序的生命周管理,并提供了一致性和可靠性。 赖春华研究Cloud Foundry云平台主要是为了探索其在实际应用中的优势和挑战。该云平台具有许多优点,比如可扩展性、灵活性和安全性。它可以自动处理应用程序的部署和扩展,减轻了开发人员的负担。此外,Cloud Foundry还支持多种编程语言和框架,使开发人员能够使用自己最熟悉的工具开发应用程序。 然而,赖春华也认识到Cloud Foundry云平台存在一些挑战。首先,它需要一定的学习和理解成本,开发人员需要掌握其相关概念和工具。其次,云平台的集成和部署可能需要一些时间和资源。此外,由于云平台中涉及到多个组件和服务,确保其稳定性和性能也是一个挑战。 为了解决这些挑战,赖春华提出了一些建议。首先,他建议开发人员在使用Cloud Foundry之前应该进行充分的学习和了解,并提供适当的培训和支持。其次,他建议云平台的部署和集成应该进行良好的规划和测试,确保其稳定性和可靠性。最后,他还建议云平台的使用应该与其他开发人员进行交流和分享经验,从而共同解决问题和改进。 总的来说,赖春华的研究主要关注于Cloud Foundry云平台的优势和挑战,并提供了一些解决方案和建议。通过研究云平台,他希望能够为开发人员提供更好的工具和平台,从而加快应用程序的开发和部署。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值