Safemath to Protect From Overflows
Considering security is a big part of writing good Ethereum smart contracts. A common problem when dealing with numeric operations is the risk of overflow. In this article we will introduce to the SafeMath library available in the open zeppelin smart contracts collection.
What is an overflow?
An overflow/underflow happens when an arithmetic operation reach the maximum or minimum size of the type. For example if you store your number in the uint256 type, it means your number will be stored in a 256 bits unsigned number ranging from 0 to 2^256. In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
The most common result of an overflow is that the least significant representable bits of the result are stored; the result is said to wrap around the maximum (i.e. modulo power of two).
An overflow condition gives incorrect results and, particularly if the possibility has not been anticipated, can compromise a program’s reliability and security.
Let’s protect!
This could happen whenever you are doing arithmetic operations such as + , – , * . When using the SafeMath library, the results of this operations will be checked and an error will be thrown stopping the execution of your smart contract.
Here is the code:
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
To use a Solidity library, just type inside of your contract and you can then call the public functions defined by your library:
using SafeMath for uint256;
For example this little smart contracts that does nothing but just storing safely the result of an addition:
contract MyContract {
using SafeMath for uint256;
uint256 result;
function SafeAdd(uint256 a, uint256 b) {
result = 0;
result = a.add(b);
}
}
Don’t hesitate to use the SafeMath library to protect from inputs that could make your contract do unexpected things after overflow or underflow leading arithmetic operations.