fix: pow checks mul's exponent precondition in the squaring loop (#276) - #286
Open
thedavidmeister wants to merge 2 commits into
Open
thedavidmeister wants to merge 2 commits into
thedavidmeister wants to merge 2 commits into
Conversation
Fixes #276. `pow` raises the integer part of `b` by exponentiation by squaring, and `LibDecimalFloatImplementation.mul` sums its operands' exponents in checked arithmetic. Squaring the base doubles its exponent every iteration, so a wide enough integer exponent walks that sum past `int256` and the squaring `mul` panics with `0x11` before any of `pow`'s own exponent checks run. The issue's counterexample is `1.06e67 e1348563571` raised to `-7.84e69`. `b` is negative so `pow` recurses on `1/a`, whose exponent is `-1348563705`, and the integer exponent is 233 bits wide: the base exponent reaches `-3.64e76` on the 224th squaring and the 225th overflows. Nothing on the `b * log10(a)` to `pow10` leg is implicated. The squaring loop runs first and never reaches it. Of the two ways out, letting the arithmetic saturate and leaving the error to the final `packArithmeticResult`, or putting the typed check ahead of the arithmetic, this takes the check. `mul`'s exponent range is a real precondition rather than an accident: its own fuzz tests already bound their exponents to stay inside it. It is named here as `MUL_EXPONENT_MIN` / `MUL_EXPONENT_MAX` and stated on `mul`. Saturating would instead widen a primitive that every arithmetic operation goes through into knowingly returning a wrong exponent, and would charge all of those callers for a check only `pow` needs, because `pow` is the one caller that iterates `mul` over its own output. So `pow`'s loop checks both running exponents before handing them to `mul`. Reaching the bound means the result is not representable. The base at iteration `i` is `a ** (2 ** i)` and the loop only reaches `i` when the integer exponent is at least `2 ** i`, so the final result's `log10` is at least the base's in magnitude; the same holds for the running result, which is `a ** m` for some `m` no greater than the integer exponent. A coefficient's 77 digits and the fractional leg's `|log10(a)|`, which an int32 exponent caps just over 2.1e9, are nothing against a bound of ~2.9e76. The sign of the out-of-range exponent is therefore the sign of the result's `log10` and names the error: `ExponentUnderflow` going down, `ExponentOverflow` going up. The issue's input now gives `ExponentUnderflow`. `MUL_EXPONENT_LIFT_MAX` is the headroom the bound leaves `mul` for lifting the summed exponent as it normalises the 512-bit product back to 256 bits. The bound on that lift is 79 and the allowance is 128. Tests: the issue's counterexample, and an overflow-direction counterpart built from a coefficient of 1 so the squaring doubles the exponent and nothing else, as concrete `pow` tests. Both are `Panic(0x11)` before and the named error after. `mul` is pinned at each end of its stated precondition with the coefficients that maximise the lift, which panics if the lift allowance is trimmed away. `testRoundTripFuzzPow` is unchanged and still catches no untyped revert at 60,000 runs. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Contributor
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 49 minutes. View limit detailsLimit details: You’ve used the included review currently available. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (4)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Closes #276.
The issue hypothesised the overflow was on the
b * log10(a)→pow10leg. It is not:powrecurses onpow(a.inv(), b.minus())for a negativeb, and the exponentiation-by-squaring loop runs beforelog10is ever called. Squaring doubles the base exponent each iteration, so after 224 squarings it is-3.6e76and the 225th squaring'sexponentA + exponentBinLibDecimalFloatImplementation.mulunderflowsint256(min-5.8e76) —Panic(0x11).mul's exponent range is a precondition, not an accident: its own fuzz tests already bound exponents toEXPONENT_MAX / 2to stay inside it, andpowis the only caller in the library that iteratesmulover its own output. So the typed check moves ahead of the arithmetic rather thanmulsaturating — saturating in a primitive every operation goes through would have it knowingly return a wrong exponent and charge every caller gas for a check onlypowneeds.pownow checks both the base and the running result againstmul's stated precondition at the top of each squaring iteration, revertingExponentOverfloworExponentUnderflowby the sign of the out-of-range exponent. The issue's counterexample givesExponentUnderflow.No input that previously succeeded can now revert: at iteration
ithe base isa**(2**i)and the loop only reachesiwhen the integer exponent is at least2**i, so the final result's|log10|is at least the base's; a coefficient's 77 digits and the fractional leg's int32-capped|log10(a)|are nothing against a bound of ~2.9e76.MUL_EXPONENT_LIFT_MAXis 128 rather than 76:mul's existing comment understates its own lift, whose worst case is 79 (78 digits of the product's high word plus one fromunabsUnsignedMulOrDivLossy). A 76 margin is off by one.QA
testPowExtremeIntegerExponentUnderflow(the issue's bit-exact repro) andtestPowExtremeIntegerExponentOverflow- both revertPanic(0x11)on main and give the named typed errors here; plustestMulExponentPreconditionUpperBoundaryandtestMulExponentPreconditionLowerBoundarypinningmul's precondition at each end with the coefficients that maximise the lift.checkPowSquaringExponentcalls makes both new pow tests fail with exactly the issue'sPanic(0x11);MUL_EXPONENT_LIFT_MAX = 0makes the upper boundary test panic and the lower faillift within allowance.Panicis a failure, already encoded in the pre-existingassertExpectedPowErrorallow-list, plus a step-by-step replay ofpow's squaring loop that located the overflow at the 225th squaring independently of the fix and supplied the exponents the tests pin.testRoundTripFuzzPowis untouched - not bounded, not skipped, not weakened, and clean at 60,000 runs.520 Solidity tests pass, 76 Rust.
forge fmt --check,forge lint -D warningsandslitherall clean.🤖 Generated with Claude Code