Solidity – SafeMath Safe Add Function Assertions Against Overflows

Architectureoverflowsolidity

Looking at the following safeAdd function, which is common in many smart contracts out there, it seems that only a and c are compared. But can't it be that b will be the uint that will cause an overflow?

  function safeAdd(uint a, uint b) internal returns (uint) {
    uint c = a + b;
    assert(c >= a);
    return c;
  }

Why is compering only a and c is sufficient?

assert(c >= b && c >= a);  <- Why not like this?

Best Answer

Firstly, kudos to the OpenZeppelin safeMath library parts of which I've used in my code.

Given that addition is commutative, it doesn't really matter which you use. The answer will either be equal or greater than both and so valid, or less than both, invalid.

Say we have an uint3 (for simplicity but not a valid Solidity type) where overflow is mod 8:

1+7 = 0 0 < 2 && 0 < 7

7+1 = 0 0 < 2 && 0 < 7

Overflowed

0+7 = 7 7 > 0 && 7 >= 7

7+0 = 7 7 >= 7 && 7 > 0

-edit-

Aside from the question, I might add that I use this pattern in solidity 0.4.10 (or above) to separate side effects and validation rather than a more expensive function call.

uint _check = c; // where c is a variable being updated
    c = a + b;
assert(c >= _check);
Related Topic