...by Daniel Szego
"Simplicity is the ultimate sophistication."
Leonardo da Vinci

Friday, March 23, 2018

Solidity security patterns - uint underflow

As integer overflow is considered in solidity as one of a huge problems, in real life overflow happens rarely, actually because the values causing overflows are pretty big. However, if you use uint variables underflow is a much more critical problem that can happen frequently. 

contract testContract
    uint public integer = 0;
    uint public sub;
    function minusOne() returns (uint){
        return integer -1;
    function checkSub(uint balance, uint amount2) returns (uint){
        sub = balance - amount2;
        require (sub > 0);
        return sub;

In the previous example calling minusOne() does not throw an error message, instead it returns with the biggest possible uint value: uint256: 115792089237316195423570985008687907853269984665640564039457584007913129639935

Similarly in the checkSub() function if you the amount2 is bigger than the balance variable, sub variable will underflow resulting a very huge integer number which will not trigger the require condition.