Ethereum Smart Contract Safe Math Checks


An overflow/underflow happens when an arithmetic operation reach the maximum or minimum size of the type. 

An overflow condition gives incorrect results and, particularly if the possibility has not been anticipated, can compromise a program’s reliability and security.

SafeMath is a solidity math library especially designed to support safe math operations: safe means that it prevents overflow when working with uint. You can find it in zeppelin-solidity SafeMath.



pragma solidity 0.4.24;


// @title SafeMath
// @dev Math operations with safety checks that throw on error
library SafeMath {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }

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

    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;
    }
}



Reference.
https://ethereumdev.io/safemath-protect-overflows/

Comments

Popular posts from this blog

Solidity Hash of Structs (Testing hash uniqueness)

Is Making the Crypto Space Legally Compliant Paving the Road to Mass (Blockchain) Adoption?

Parity installation on Ubuntu Virtual Machine