...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego

Tuesday, January 2, 2018

Solidity and Truffle Tips and Tricks - Overflows and safe arithmetic


One of the problem is with the solidity language that overflow or underflow of an integer value is not really checked at the moment. As a result, providing wrong values by chance or at a hacking attack can very easily cause unexpected behavior. As an example, considering the following function: 

    function add(uint8 _a, uint8 _b) returns (uint8) {
        return _a + _b;
    }

As add(100,10) result in 110 as expected add(255,10) results in 9 which is not surely intended as a result. If in such a situation, it is rather expected that an error is thrown indicating overflow, than for instance the following safe add function can be used:

    function addSafe(uint8 _a, uint8 _b) returns (uint8) {
        assert((_a + _b >= _a) && (_a + _b >= _b));
        return _a + _b;
    }