# 合约案例

## 减法下溢、加法上溢和乘法下溢

``````// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.10;
contract Overflow {
uint8 public count = 1;

function set(uint8 _count) public {
count = _count;
}

function sub(uint8 input) public {
count -= input;
}

function mul(uint8 input) public {
count = 255；
count *= input;
}

count = 255;
count += input;
}

}``````

## 防止策略

### 检查预期结果是否一致。

``````contract FixOverflow {
uint8 public count = 1;
function set(uint8 _count) public {
count = _count;
}

function sub(uint8 input) public {
count = sub(count, input);
}

function mul(uint8 input) public {
count =  mul(count,input);
}

count = 255;
}

function sub(uint8 a, uint8 b) internal pure returns (uint8) {
require(b &lt;= a, "Underflow!");
return a -b;
}

function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
require( c>=a, "Overflow!");
return c;
}

function mul(uint8 a, uint8 b) internal pure returns (uint8) {
if (a == 0) {
return 0;
}
uint8 c = a *b;
require( c / a == b, "Overflow!");
return c;
}
}``````

### 或直接使用openzeppelin数学库。

``````pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol"; //[Remix环境]

contract FixedOverflow {
uint256 public count = 1;
function set(uint256 _count) public {
count = _count;
}

function sub(uint256 input) public {
count = SafeMath.sub(count, input, "Overflow!");
}

function mul(uint256 input) public {
count = 2**256 -1;
count =  SafeMath.mul(count,input);
}

count = 2**256 -1;
}
}
``````

• 发表于 2022-08-06 01:50
• 阅读 ( 156 )
• 学分 ( 2 )
• 分类：Solidity

Johnathan

PHD

12 篇文章, 1315 学分