# 智能合约整数溢出漏洞详解 ｜猿创征文

StevenX5 2022-07-02 10:58:46

## 漏洞原理

### 上溢

``````	0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
+ 	0x000000000000000000000000000000000001
------------------------------------------
= 	0x000000000000000000000000000000000000``````

### 下溢

``````    0x000000000000000000000000000000000000
- 	0x000000000000000000000000000000000001
------------------------------------------
= 	0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF``````

## 安全隐患

``````// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

// contract to test uint8 integer underflows and overflows
contract OverFlowUnderFlow {
uint8 public a = 0;
uint8 public b = 2**8-1;

// a will end up at 2**8-1
function underflow() public {
a -= 1;
}

// b will end up at 0
function overflow() public {
b += 1;
}
}``````

## 预防措施

``````// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}

function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}

function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}

function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}``````

``````// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "./SafeMath.sol";

// contract to test uint8 integer underflows and overflows
// fixed by using SafeMath
contract OverFlowUnderFlowFixed {
using SafeMath for uint;
uint public a = 0;
uint public b = 2**256-1;

// will throw
function underflow() public {
a = a.sub(1);
}

// will throw
function overflow() public {
}
}``````

...全文
161 1 打赏 收藏 举报

1 条回复

EargoChen 07-07

• 打赏
• 举报

183

2022-07-02 10:58

Hi，欢迎加入我们！

• 获取最官方最新最全的区块链、以太坊、Web3.0学习内容与资源
• 获取行业内更有价值的研讨会、公开课资源，或参与社区发起的主题活动课程
• 获得专业的以太坊、区块链、Web3.0相关技术资深专家/讲师的回复或指导，突破学习瓶颈
• 进行学习打卡、提问或回答问题，提高个人或在社区的影响力，将有机会与各大技术官方深度合作
• 参与丰富的社区活动，获得更多学习资源、行业资源等
• 结识更多行业伙伴，参与线上/线下课程、交流会，拓展行业交流圈

【最新活动】：

1、6月1日21:00-21:30，DappLearning Infura AMA（线上）点击查看详情