Skip to content
DoS Audit finding Advanced

In Stable2LUT1::getRatiosFromPriceLiquidity , in extreme cases, updateReserve will start breaking

In an extreme price range of the Stable2LUT1 lookup table, the reserve correction step in updateReserve becomes larger than the reserve itself, causing an arithmetic underflow that reverts the function. Even with a smaller step size, the Newton iteration fails to converge and returns zero, making the price calculation unusable.

Egis_Security Follow

Originally disclosed on Code4rena

Submitted by Egis_Security

This is one of the edge cases in getRatiosFromPriceLiquidity:

if (price < 0.001083e6) {
                                    revert("LUT: Invalid price");
                                } else {
                                    return
                                        PriceData(
                                            0.27702e6,
                                            0,
                                            9.646293093274934449e18,
                                            0.001083e6,
                                            0,
                                            2000e18,
                                            1e18);
                                }

The range where the price can be is very large, between 0.27702e6 (highPrice) and 0.001083e6 (lowPrice). If we are closer to the lowPrice, then pd.currentPrice is set to pd.lutData.lowPrice:

if (pd.lutData.highPrice - pd.targetPrice > pd.targetPrice - pd.lutData.lowPrice) {
            // targetPrice is closer to lowPrice.
            scaledReserves[j] = scaledReserves[i] * pd.lutData.lowPriceJ / pd.lutData.precision;

            // set current price to lowPrice.
            pd.currentPrice = pd.lutData.lowPrice;
        }

In this case, the current price is much smaller than the target price and because of this, updateReserve will have to do a very large correction of the reserve in order to converge on the target price.

Because of these large corrections, the reserve will become so small, that the next time the reserve has to be updated, the amount that it has to be reduced by will be larger than the reserve itself, resulting in a panic underflow and bricking the function.

This revert happens because of two reasons:

  1. Because of the large range that the price can be in, thus using such a small lowPrice as pd.currentPrice makes the difference between pd.targetPrice so large that the corrections become very large and underflow before convergence can be achieved.
  2. lowPriceJ is extremely large. In this case it’s 2000e18, which makes the step size very large and thus, the code will attempt extreme corrections of the reserve, resulting in a revert.

It’s important to note, that even if lowPriceJ is significantly reduced, the function won’t revert, but it will never converge on a price and this can only be fixed by reducing the gap between highPrice and lowPrice effectively reducing the range for that specific price.

We wanted to showcase both issues and that even if the underflow (lowPriceJ issue) is resolved that the estimated ranges still are too large, thus making the price impossible to converge.

The below tests showcase both the original code (underflow) and how reducing lowPriceJ doesn’t fix the real problem.

Proof of Concept

Test case for underflow: paste the following inside BeanstalkStable2LiquidityTest and run forge test --match-contract BeanstalkStable2LiquidityTest --mt test_calcReserveAtRatioLiquiditExtreme -vvvv:

function test_calcReserveAtRatioLiquiditExtreme() public view {
        uint256[] memory reserves = new uint256[](2);
        reserves[0] = 1e18;
        reserves[1] = 1e18;
        uint256[] memory ratios = new uint256[](2);
        ratios[0] = 8;
        ratios[1] = 1;

        uint256 reserve0 = _f.calcReserveAtRatioLiquidity(reserves, 0, ratios, data);
    }

Logs:

  Target Price:  125000
  Original Current Price:  1083
  --------------------------------
  Reserve before step:  2000000000000000000000
  --------------------------------
  Reserve:                2000000000000000000000
  Amount to decrease by:  893822359084720968727
  Current Price at iteration  0 1993
  Reserve:                1106177640915279031273
  Amount to decrease by:  887258462712414537152
  Current Price at iteration  1 10817
  Reserve:                218919178202864494121
  Amount to decrease by:  823610307119851952292

As you can see, the code attempts massive corrections to the reserve in order to achieve convergence, but the amount to decrease the reserve is too large and the function underflows.

Test case when lowering lowPriceJ: run the same test as before, but change lowPriceJ to 10e18, for example purposes:

if (price < 0.001083e6) {
                                    revert("LUT: Invalid price");
                                } else {
                                    return
                                        PriceData(
                                            0.27702e6,
                                            0,
                                            9.646293093274934449e18,
                                            0.001083e6,
                                            0,
                                      ->    10e18,
                                            1e18);
                                }

Logs:

Target Price:  125000
  Original Current Price:  1083
  --------------------------------
  Reserve before step:  10000000000000000000
  --------------------------------
  Reserve:                10000000000000000000
  Amount to decrease by:  158841687633952488
  Current Price at iteration  0 272070
  ...
  Reserve:                20736004517896372313
  Amount to increase by:  8588323693661738
  Current Price at iteration  254 131644
  END OF NEWTON's METHOD

The logs are compacted as they are very large, but the idea is this:

  1. Target price is again much larger than current price.
  2. During the first correction, the price moves by a very large amount, making it much larger than target price.
  3. Now updateReserves has to do corrections in the other direction (increase the reserve), so that the prices can converge on the target price, but this never happens, as Newton’s method ends after 255 iterations and leaves the loop.
  4. calcReserveAtRatioLiquidity will return 0, as reserve is never initialized anywhere, effectively making the function useless.

Tools Used

Foundry

Recommended Mitigation Steps

To completely fix both issues, lowPriceJ must be lowered and the estimated range must be narrowed down.

Assessed type

DoS

Brean0 (Basin) confirmed

0xsomeone (judge) decreased severity to Low and commented:

The Warden outlines a misbehavior that arises from the edge case price configuration outlined in Issue #25. I consider both issues to stem from the extreme difference between the upper and lower price bounds, as eliminating this gap would resolve both issues and thus be considered the root cause of both.

This particular submission once again relies on direct interaction with the Stable2LUT1 contract and does not adequately demonstrate the issue in a production environment. A demonstration of either this one or exhibit #25 will be considered acceptable to consider them acceptable per my comment on #25.

deth (warden) commented:

@0xsomeone - Here are our arguments why this is a valid Medium and it is not a duplicate of #25:

Why this is valid:

  1. The case may be an edge case, but it is in the Stable2LUT1 and must be considered.
  2. The PoC provided is the only one that can be provided as of now, as currently Beanstalk (the integrator of the function) doesn’t have any production ready code built around the Stable2 contract (the caller of getRatiosFromPriceLiquidity). Thus, we cannot provide a production ready PoC since there is nothing to base it off of.
  3. The issue should be considered a Medium, as it breaks core functionality completely, making any call to getRatiosFromPriceLiquidity unusable, which can have a large impact on all integrators that use/will use the function. Thus, with a low likelihood and High impact, we believe this a valid Medium.

Why this isn’t a duplicate:

  1. The root between the two issues are different. One occurs in getRatiosFromPriceLiquidity and the other in getRatiosFromPriceSwap. If #25 is fixed this issue will still persist and vice-versa.

nickkatsios (Basin) commented:

We would tend to agree with classifying this issue as Medium severity. While the likelihood of it occurring in a real production environment is low, it effectively renders the well function unusable. According to the severity documentation, which states that “assets are not at direct risk, but the protocol’s function or availability could be impacted,” this issue clearly falls within that category.

Instead of recalculating the data points for the lookup table, both issues were resolved by improving the step size, ensuring that the maxStep size can never exceed the j reserve. You can see the complete fix in this PR.

0xsomeone (judge) increased severity to Medium and commented:

See response in the primary submission Issue #25.

deth (warden) commented:

@0xsomeone - I don’t understand, how is the root cause is the same? If #25 is fixed, #22 persists and vice-versa. I understand that main driving force behind both issues is the same, but fixing one of them doesn’t fix the other, you can see the sponsors applied fixes to both functions independently.

0xsomeone (judge) commented:

@deth - While discussing with the Sponsor, we concluded that both issues stem from the extreme step sizes on the lower bounds of the respective curves. However, you are indeed correct in that the actual ratios are yielded by distinct functions and thus there is no actual correlation between the two submissions (i.e., it is not possible to fix both simultaneously with a single code change).

As such, I have proceeded with splitting this submission as a unique entry given that from a C4 perspective the issues do not strictly share a root cause. I greatly appreciate the due diligence!


The original report as published on Code4rena, by Egis_Security. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the very wide gap between the lookup table's high and low price bounds combined with an extremely large lowPriceJ step size, which makes the Newton correction overshoot and underflow the reserve.

Impact

The function reverts or returns zero, so any integrator relying on getRatiosFromPriceLiquidity for that price range cannot use it; the report notes the likelihood in production is low.

What the attacker needed

Price falls in the extreme low range; direct call to the Stable2LUT1 contract

The fix

The step size was improved so the maximum step can never exceed the j reserve, which the sponsor says resolved both issues.

How it was found

  1. Call calcReserveAtRatioLiquidity with equal reserves and ratios of 8 and 1 so the target price falls in the extreme low range.
  2. Observe the first correction reducing the reserve by an amount close to the whole reserve.
  3. Observe the next correction asking to reduce the reserve by more than remains, causing an underflow revert.
  4. Repeat with a much smaller lowPriceJ and observe the price overshooting and the loop ending after 255 iterations without convergence.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A lookup table gives starting values for a maths routine that adjusts reserves until the price matches a target. When the starting price is far from the target, each adjustment is huge, and one adjustment asks to remove more than the reserve holds, so the calculation crashes. A second version shows that even with smaller adjustments the routine never settles on the right price and gives back nothing useful.

What is DoS?

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.

More by Egis_Security

View all

2 more disclosed reports, best first.

More from Basin Invitational

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.