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第14期——SafeMath.sol

  • Michael.W
  • 发布于 2023-07-28 16:08
  • 阅读 2570

SafeMath库是对solidity中uint256的加、减、乘、除和取模运算的一层封装。由于solidity 0.8之前的uint256运算是不做溢出检查,许多基于0.8版本之前的项目都会使用该库。0.8版本之后solidity编译器内置了整形数溢出检查,所以SafeMath库也不再被广泛使用。

0. 版本

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

0.1 SafeMath.sol

Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/utils/math/SafeMath.sol

SafeMath库是对solidity中uint256的加、减、乘、除和取模运算的一层封装。由于solidity 0.8之前的uint256运算是不做溢出检查,许多基于0.8版本之前的项目都会使用该库。0.8版本之后solidity编译器内置了整形数溢出检查,所以SafeMath库也不再被广泛使用。

注:此版本的SafeMath库必须是基于solidity 0.8及之后的编译器版本使用。

1. 目标合约

封装SafeMath library成为一个可调用合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/src/utils/math/MockSafeMath.sol

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

import "openzeppelin-contracts/contracts/utils/math/SafeMath.sol";

contract MockSafeMath {
    using SafeMath for uint;

    function tryAdd(uint a, uint b) external pure returns (bool, uint) {
        return a.tryAdd(b);
    }

    function trySub(uint a, uint b) external pure returns (bool, uint) {
        return a.trySub(b);
    }

    function tryMul(uint a, uint b) external pure returns (bool, uint) {
        return a.tryMul(b);
    }

    function tryDiv(uint a, uint b) external pure returns (bool, uint) {
        return a.tryDiv(b);
    }

    function tryMod(uint a, uint b) external pure returns (bool, uint) {
        return a.tryMod(b);
    }

    function add(uint a, uint b) external pure returns (uint){
        return a.add(b);
    }

    function sub(uint a, uint b) external pure returns (uint) {
        return a.sub(b);
    }

    function mul(uint a, uint b) external pure returns (uint){
        return a.mul(b);
    }

    function div(uint a, uint b) external pure returns (uint) {
        return a.div(b);
    }

    function mod(uint a, uint b) external pure returns (uint) {
        return a.mod(b);
    }

    function sub(
        uint a,
        uint b,
        string memory errorMessage
    ) external pure returns (uint){
        return a.sub(b, errorMessage);
    }

    function div(
        uint a,
        uint b,
        string memory errorMessage
    ) external pure returns (uint) {
        return a.div(b, errorMessage);
    }

    function mod(
        uint a,
        uint b,
        string memory errorMessage
    ) external pure returns (uint) {
        return a.mod(b, errorMessage);
    }
}

全部foundry测试合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/utils/math/SafeMath.t.sol

2. 代码精读

2.1 tryAdd(uint256 a, uint256 b) && trySub(uint256 a, uint256 b) && tryMul(uint256 a, uint256 b) && tryDiv(uint256 a, uint256 b) && tryMod(uint256 a, uint256 b)

  • tryAdd(uint256 a, uint256 b):计算两数之和。如果加法产生溢出,返回false和0,否则返回true和结果;
  • trySub(uint256 a, uint256 b):计算两数之差。如果减法产生溢出,返回false和0,否则返回true和结果;
  • tryMul(uint256 a, uint256 b):计算两数之积。如果乘法产生溢出,返回false和0,否则返回true和结果;
  • tryDiv(uint256 a, uint256 b):计算两数之商。如果除法产生溢出,返回false和0,否则返回true和结果;
  • tryMod(uint256 a, uint256 b):计算两数的取模运算,即求余数。如果模运算产生溢出,返回false和0,否则返回true和结果。
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 计算和
            uint256 c = a + b;
            // 如果a>和,则发生整形溢出。返回false和0
            if (c < a) return (false, 0);
            // 返回true和计算结果
            return (true, c);
        }
    }

    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 如果减数>被减数,发生整形溢出。返回false和0
            if (b > a) return (false, 0);
            // 返回true和计算结果 
            return (true, a - b);
        }
    }

    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 如果a为0,乘积必然为0。返回true和0
            if (a == 0) return (true, 0);
            // 计算乘积c
            uint256 c = a * b;
            // 做除法检查是否溢出。如果乘积c除以a不等于b,产生溢出。返回false和0
            if (c / a != b) return (false, 0);
            // 返回true和乘积c
            return (true, c);
        }
    }

    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 如果除数为0,直接返回false和0
            if (b == 0) return (false, 0);
            // 由于被除数和非0除数都是uint256,必然除法不会产生溢出。直接返回true和运算结果
            return (true, a / b);
        }
    }

    // 注:同tryDiv()的内在判断逻辑一致
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 如果除数为0,直接返回false和0
            if (b == 0) return (false, 0);
            // 由于被除数和非0除数都是uint256,必然除法不会产生溢出。直接返回true和取模运算结果
            return (true, a % b);
        }
    }

foundry代码验证

contract SafeMathTest is Test {
    MockSafeMath msm = new MockSafeMath();

    function test_TryAdd() external {
        (bool flag,uint res) = msm.tryAdd(1, 2);
        assertTrue(flag);
        assertEq(res, 3);
        // overflow
        (flag, res) = msm.tryAdd(type(uint).max, 1);
        assertFalse(flag);
        assertEq(res, 0);
    }

    function test_TrySub() external {
        (bool flag,uint res) = msm.trySub(3, 1);
        assertTrue(flag);
        assertEq(res, 2);
        // overflow
        (flag, res) = msm.trySub(1, 2);
        assertFalse(flag);
        assertEq(res, 0);
    }

    function test_TryMul() external {
        (bool flag,uint res) = msm.tryMul(2, 3);
        assertTrue(flag);
        assertEq(res, 6);
        // overflow
        (flag, res) = msm.tryMul(type(uint).max, 2);
        assertFalse(flag);
        assertEq(res, 0);
    }

    function test_TryDiv() external {
        (bool flag,uint res) = msm.tryDiv(7, 2);
        assertTrue(flag);
        assertEq(res, 3);
        // overflow
        (flag, res) = msm.tryDiv(1, 0);
        assertFalse(flag);
        assertEq(res, 0);
    }

    function test_TryMod() external {
        (bool flag,uint res) = msm.tryMod(7, 2);
        assertTrue(flag);
        assertEq(res, 1);
        // overflow
        (flag, res) = msm.tryMod(1, 0);
        assertFalse(flag);
        assertEq(res, 0);
    }
}

2.2 add(uint256 a, uint256 b) && mul(uint256 a, uint256 b)

  • add(uint256 a, uint256 b):计算两数之和。如果加法产生溢出,直接revert;
  • mul(uint256 a, uint256 b):计算两数之积。如果乘法产生溢出,直接revert。
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        // 封装solidity内置"+"运算符
        return a + b;
    }

    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // 封装solidity内置"*"运算符
        return a * b;
    }

foundry代码验证

contract SafeMathTest is Test {
    MockSafeMath msm = new MockSafeMath();

    function test_Add() external {
        assertEq(msm.add(1, 2), 3);
        // overflow
        vm.expectRevert();
        msm.add(type(uint).max, 1);
    }

    function test_Mul() external {
        assertEq(msm.mul(3, 2), 6);
        // overflow
        vm.expectRevert();
        msm.mul(type(uint).max, 2);
    }
}

2.3 sub(uint256 a, uint256 b) && div(uint256 a, uint256 b) && mod(uint256 a, uint256 b) && sub(uint256 a, uint256 b, string memory errorMessage) && div( uint256 a, uint256 b, string memory errorMessage) && mod(uint256 a, uint256 b, string memory errorMessage)

  • sub(uint256 a, uint256 b):计算两数之差。如果减法产生溢出,直接revert;
  • div(uint256 a, uint256 b):计算两数之商。如果除法产生溢出(除数为0),直接revert;
  • mod(uint256 a, uint256 b):计算两数的余数。如果除法产生溢出(除数为0),直接revert;
  • sub(uint256 a, uint256 b, string memory errorMessage):计算两数之差。如果产生溢出,以自定义消息revert;
  • div( uint256 a, uint256 b, string memory errorMessage):计算两数之商。如果产生溢出,以自定义消息revert;
  • mod(uint256 a, uint256 b, string memory errorMessage):计算两数的余数。如果产生溢出,以自定义消息revert。
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        // 封装solidity内置"-"运算符
        return a - b;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // 封装solidity内置"/"运算符
        return a / b;
    }

    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        // 封装solidity内置"%"运算符
        return a % b;
    }

    // 注:该方法已弃用,因为自定义revert消息作为参数会引起更多额外的memory分配。如果想自定义溢出消息,可以使用trySub()
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            // 如果减数>被减数,以errorMessage revert
            // 注:由于这里调用了opcode `revert`,在发生revert时会返还剩余gas。而使用solidity内置减法发生revert时,会调用不合法opcode直接消耗掉剩余的gas
            require(b <= a, errorMessage);
            // 返回二者之差
            return a - b;
        }
    }

    // 注:该方法已弃用,因为自定义revert消息作为参数会引起更多额外的memory分配。如果想自定义溢出消息,可以使用tryDiv()
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 如果除数=0,以errorMessage revert
            // 注:由于这里调用了opcode `revert`,在发生revert时会返还剩余gas。而使用solidity内置除法发生revert时,会调用不合法opcode直接消耗掉剩余的gas
            require(b > 0, errorMessage);
            // 返回二者之商
            return a / b;
        }
    }

    // 注:该方法已弃用,因为自定义revert消息作为参数会引起更多额外的memory分配。如果想自定义溢出消息,可以使用tryMod()
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        // 关闭solidity 0.8的整数运算溢出检查
        unchecked {
            // 如果除数=0,以errorMessage revert
            // 注:由于这里调用了opcode `revert`,在发生revert时会返还剩余gas。而使用solidity内置取模运算符发生revert时,会调用不合法opcode直接消耗掉剩余的gas
            require(b > 0, errorMessage);
            // 返回两数的余数
            return a % b;
        }
    }
}

foundry代码验证

contract SafeMathTest is Test {
    MockSafeMath msm = new MockSafeMath();

    function test_Sub() external {
        assertEq(msm.sub(3, 2), 1);
        // overflow
        vm.expectRevert();
        msm.sub(1, 2);

        // with error message
        assertEq(msm.sub(3, 2, "error message"), 1);
        vm.expectRevert("error message");
        msm.sub(1, 2, "error message");
    }

    function test_Div() external {
        assertEq(msm.div(7, 2), 3);
        // overflow
        vm.expectRevert();
        msm.div(1, 0);

        // with error message
        assertEq(msm.div(7, 2, "error message"), 3);
        vm.expectRevert("error message");
        msm.div(1, 0, "error message");
    }

    function test_Mod() external {
        assertEq(msm.mod(7, 2), 1);
        // overflow
        vm.expectRevert();
        msm.mod(1, 0);

        // with error message
        assertEq(msm.mod(7, 2, "error message"), 1);
        vm.expectRevert("error message");
        msm.mod(1, 0, "error message");
    }
}

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

1.jpeg

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

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

0 条评论

请先 登录 后评论