Fix underflow in modexp gas calculation #883
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
In
calc_iter_count()
, which is part of the modexp precompile gas calculation, the most-significant bit of the exponent is added to the intermediate result. The MSB is computed usingU256::from(exp.bits()) - U256::from(1))
in:This works only if the exponent is non-zero; subtracting
1
from zero results in an underflow, leading to inaccurate gas requirements for specific inputs.Geth computes the MSB as follows; notice the condition
bitlen > 0
:This PR changes the underflowing subtraction into a
saturating_sub
so that an underflow never occurs.Performance / NEAR gas cost considerations
Testing
Fuzzing.
How should this be reviewed
A test has been added to
modexp.rs
which asserts that the required gas for the specified input is65536
; an equivalent Go program which uses Geth to demonstrate this is provided below:Additional information