码迷,mamicode.com
首页 > 其他好文 > 详细

Solidity safesub防止溢出

时间:2018-04-05 11:44:14      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:git   fun   abc   function   require   safe   color   div   .so   

在Solidity中两个无符号整型数字相减结果如果为负则会溢出,很严重的问题。所以在做数字运算时可以用DSSafeAddSub来保证运算的安全。

 

pragma solidity ^0.4.21;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract DSSafeAddSub {
    function safeToAdd(uint a, uint b) pure internal returns (bool) {
        return (a + b >= a);
    }
    function safeAdd(uint a, uint b) pure internal returns (uint) {
        require(safeToAdd(a, b));
        return (a + b);
    }

    function safeToSubtract(uint a, uint b) pure internal returns (bool) {
        return (b <= a);
    }

    function safeSub(uint a, uint b) pure internal returns (uint) {
        require(safeToSubtract(a, b));
        return (a - b);
    }
}
contract Uint_vs_Uint8 is usingOraclize,DSSafeAddSub{
    uint public uint_num;
    uint8 public uint8_num;
    string public str = "abc";
    uint public result = uint_num - uint8_num; // 2
    uint public uintVal = parseInt(str,2); // 0
    uint public sub;
    uint public safesub;
    
    function setUint_num() public {
        uint_num = 10;
    }
    
    function setUint8_num() public {
        uint8_num = 2;
    }
    
    function subFun() public {
        sub = uint8_num - uint_num; //溢出 115792089237316195423570985008687907853269984665640564039457584007913129639928
    }
    
    function safesubFun() public {
        safesub = safeSub(uint8_num, uint_num); // 0
    }
}

 

Solidity safesub防止溢出

标签:git   fun   abc   function   require   safe   color   div   .so   

原文地址:https://www.cnblogs.com/huahuayu/p/8720112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!