Integer overflow/underflow

Our token sale contract makes use of a safeMultiply() function, though at the time, we didn't explain its use further. The function is specifically used to protect against our first attack vector: integer overflow.

Here is a version of our buyTokens() function that does not use the call to safeMultiply():

function buyTokens(uint256 _numberOfTokens)
public
payable
{
require(msg.value == _numberOfTokens * tokenPrice);
require(tokenContract.balanceOf(this) >= _numberOfTokens);
emit Sell(msg.sender, _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
}

The msg.value, _numberOfTokens, and tokenPrice variables are all of the uint256 type. When their maximum value of 2256 is reached, they circle round back to zero. In the unsafe implementation, it would be possible in certain cases for a user to pass in a large enough value for _numberOfTokens such that the product on the right-hand side would overflow to the point where it could still equal msg.value. Our safeMultiply() implementation prevents this from happening.

Of course, in our implementation, the next call to require() would likely fail anyway with a large value for _numberOfTokens, but this should serve as an example of when such safety is required.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset