Michael.W基于Foundry精读Openzeppelin

2024年08月13日更新 120 人订阅
专栏简介 Michael.W基于Foundry精读Openzeppelin第8期——Context.sol Michael.W基于Foundry精读Openzeppelin第1期——Address.sol Michael.W基于Foundry精读Openzeppelin第2期——StorageSlot.sol Michael.W基于Foundry精读Openzeppelin第3期——Arrays.sol Michael.W基于Foundry精读Openzeppelin第4期——Base64.sol Michael.W基于Foundry精读Openzeppelin第5期——Counters.sol Michael.W基于Foundry精读Openzeppelin第6期——Strings.sol Michael.W基于Foundry精读Openzeppelin第7期——Timers.sol Michael.W基于Foundry精读Openzeppelin第9期——Multicall.sol Michael.W基于Foundry精读Openzeppelin第10期——Create2.sol Michael.W基于Foundry精读Openzeppelin第11期——Math.sol Michael.W基于Foundry精读Openzeppelin第12期——SafeCast.sol Michael.W基于Foundry精读Openzeppelin第13期——Checkpoints.sol Michael.W基于Foundry精读Openzeppelin第14期——SafeMath.sol Michael.W基于Foundry精读Openzeppelin第15期——SignedMath.sol Michael.W基于Foundry精读Openzeppelin第16期——SignedSafeMath.sol Michael.W基于Foundry精读Openzeppelin第17期——BitMaps.sol Michael.W基于Foundry精读Openzeppelin第18期——DoubleEndedQueue.sol Michael.W基于Foundry精读Openzeppelin第19期——EnumerableSet.sol Michael.W基于Foundry精读Openzeppelin第20期——EnumerableMap.sol Michael.W基于Foundry精读Openzeppelin第21期——ERC165.sol (番外篇)Michael.W基于Foundry精读Openzeppelin第22期——内联汇编staticcall Michael.W基于Foundry精读Openzeppelin第23期——ERC165Checker.sol Michael.W基于Foundry精读Openzeppelin第24期——ERC165Storage.sol Michael.W基于Foundry精读Openzeppelin第25期——IERC1820Registry.sol Michael.W基于Foundry精读Openzeppelin第26期——ERC1820Implementer.sol Michael.W基于Foundry精读Openzeppelin第27期——Escrow.sol Michael.W基于Foundry精读Openzeppelin第28期——ConditionalEscrow.sol Michael.W基于Foundry精读Openzeppelin第29期——RefundEscrow.sol Michael.W基于Foundry精读Openzeppelin第30期——ECDSA.sol Michael.W基于Foundry精读Openzeppelin第31期——IERC1271.sol Michael.W基于Foundry精读Openzeppelin第32期——SignatureChecker.sol Michael.W基于Foundry精读Openzeppelin第33期——EIP712.sol Michael.W基于Foundry精读Openzeppelin第34期——MerkleProof.sol Michael.W基于Foundry精读Openzeppelin第35期——Ownable.sol Michael.W基于Foundry精读Openzeppelin第36期——Ownable2Step.sol Michael.W基于Foundry精读Openzeppelin第37期——AccessControl.sol Michael.W基于Foundry精读Openzeppelin第38期——AccessControlEnumerable.sol Michael.W基于Foundry精读Openzeppelin第39期——ERC20.sol Michael.W基于Foundry精读Openzeppelin第40期——ERC20Burnable.sol Michael.W基于Foundry精读Openzeppelin第41期——ERC20Capped.sol Michael.W基于Foundry精读Openzeppelin第42期——draft-ERC20Permit.sol Michael.W基于Foundry精读Openzeppelin第43期——Pausable.sol Michael.W基于Foundry精读Openzeppelin第44期——ERC20Pausable.sol Michael.W基于Foundry精读Openzeppelin第45期——ERC20FlashMint.sol Michael.W基于Foundry精读Openzeppelin第46期——ERC20Snapshot.sol Michael.W基于Foundry精读Openzeppelin第47期——SafeERC20.sol Michael.W基于Foundry精读Openzeppelin第48期——TokenTimelock.sol Michael.W基于Foundry精读Openzeppelin第49期——ERC20Wrapper.sol Michael.W基于Foundry精读Openzeppelin第50期——ERC20Votes.sol Michael.W基于Foundry精读Openzeppelin第51期——ERC20VotesComp.sol Michael.W基于Foundry精读Openzeppelin第52期——ERC4626.sol Michael.W基于Foundry精读Openzeppelin第53期——ERC20PresetFixedSupply.sol Michael.W基于Foundry精读Openzeppelin第54期——ERC20PresetMinterPauser.sol Michael.W基于Foundry精读Openzeppelin第55期——PaymentSplitter.sol Michael.W基于Foundry精读Openzeppelin第56期——VestingWallet.sol Michael.W基于Foundry精读Openzeppelin第57期——ReentrancyGuard.sol Michael.W基于Foundry精读Openzeppelin第58期——PullPayment.sol Michael.W基于Foundry精读Openzeppelin第59期——Proxy.sol Michael.W基于Foundry精读Openzeppelin第60期——Clones.sol Michael.W基于Foundry精读Openzeppelin第61期——ERC1967Upgrade.sol Michael.W基于Foundry精读Openzeppelin第62期——ERC1967Proxy.sol Michael.W基于Foundry精读Openzeppelin第63期——Initializable.sol Michael.W基于Foundry精读Openzeppelin第64期——UUPSUpgradeable.sol Michael.W基于Foundry精读Openzeppelin第65期——TransparentUpgradeableProxy.sol Michael.W基于Foundry精读Openzeppelin第66期——ProxyAdmin.sol Michael.W基于Foundry精读Openzeppelin第67期——BeaconProxy.sol Michael.W基于Foundry精读Openzeppelin第68期——UpgradeableBeacon.sol

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

  • Michael.W
  • 发布于 2024-06-12 09:33
  • 阅读 1943

ReentrancyGuard库是一个用来防御函数重入的工具库。函数被修饰器nonReentrant修饰可确保其无法被嵌套(重入)调用。本库的代码逻辑上只实现了一个重入锁,所以被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神。 以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。 同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下! 如果需要转发,麻烦注明作者。十分感谢!

1.jpeg

公众号名称:后现代泼痞浪漫主义奠基人

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论