Skip to content
Business logic Audit finding Advanced

The way fees are accounted can break the sorted list order

The fee accounting mechanism in eBTC can cause the sorted list of CDPs to become unordered because new CDPs receive a higher stake than older ones, leading to different rates of change in their collateral ratios. An attacker could potentially exploit this to cause a denial of service or manipulate redemption order, though the report's proof of concept only shows a tiny ordering break under extreme conditions.

0xBeirao Follow

Originally disclosed on Code4rena

Submitted by 0xBeirao

eBTC borrows the corrected stake mechanism from Liquity for reward distributions. (paper)

Doing a pure collateral proportionnal redistribution will over-rewards fresh cdps, and under-rewards older troves. The redistribution must deal with the fact that some fraction of a cdp’s entire collateral is the accumulated reward from previous liquidations, and this fraction varies across cdps.

The corrected stake was introduced by Liquity to correct for this.

The intuition behind the choice of corrected stake is that the corrected stake effectively models the fresh trove’s collateral as a total collateral, which includes ‘virtual’ accumulated rewards. The corrected stake earns rewards for the trove as if the trove had been in the system from the beginning - thus maintaining proportional reward growth.

(Source)

eBTC makes some modifications to the original design that make the protocol vulnerable to an order break in the sorted list.

Let’s explain why.

Initially totalStake == totalCollateral, this is because no fees have been taken yet. Then, as the stETH value increases the protocol takes 50%. (if stETH apr is 5% then eBTC takes 2,5% as fees): CdpManagerStorage.sol#L509-L521.

function _calcSyncedGlobalAccounting(
    uint256 _newIndex,
    uint256 _oldIndex
) internal view returns (uint256, uint256, uint256) {
    if (_newIndex > _oldIndex && totalStakes > 0) {
        /// @audit-ok We don't take the fee if we had a negative rebase
        (
            uint256 _feeTaken,
            uint256 _deltaFeePerUnit,
            uint256 _perUnitError
        ) = calcFeeUponStakingReward(_newIndex, _oldIndex);

        // calculate new split per stake unit
        uint256 _newPerUnit = systemStEthFeePerUnitIndex + _deltaFeePerUnit;
        return (_feeTaken, _newPerUnit, _perUnitError);
    } else {
        return (0, systemStEthFeePerUnitIndex, systemStEthFeePerUnitIndexError);
    }
}

The _feeTaken goes directly to the protocol and reduces the totalCollateral value. (because internal accounting uses shares for internal accounting aka wstETH) CdpManagerStorage.sol#L585:

activePool.allocateSystemCollSharesToFeeRecipient(_feeTaken);

Because the stake is calculated like this: CdpManagerStorage.sol#L454

stake = (_coll * totalStakesSnapshot) / totalCollateralSnapshot;

Now the new CDP stake will be higher than old cdp stakes since totalStakesSnapshot has not moved but totalCollateralSnapshot has decreased.

⇒ Since the debt redistributions and fee payments depend on the stake to distribute funds, we can intuitively understand that new CDPs will pay more fees than the old ones. Therefore, new cpds NICR (Nominal Individual Collateral Ratio = shares/debt) will decrease at a higher rate than old ones.

This can cause old CDPs to cross newer ones and break list order.

This list order break make the insertion position not unique anymore, this can lead to more and more disorder in the list that leads to unexpected behaviours such as DOS and bad redemption order.

Proof of Concept

This poc only takes advantage of splitting fees to break the list order, but note that debt redistribution events exacerbate this problem.

function test_H1() public {
  vm.pauseGasMetering();

  address firstUser;
  address lastUser;
  bytes32 firstCdpId;
  bytes32 lastCdpId;

  uint loop = 100;

  /// let's open 100 cdps and save the 1st and last index
  for (uint256 i = 0; i < loop; i++) {
      (uint256 oldIndex, uint256 newIndex) = _applyIndexChange(2000000000000000); // 0,2% stETH increase
      // get a random user
      address user = _utils.getNextUserAddress();
      vm.startPrank(user);

      // Randomize collateral amount used
      vm.deal(user, 10 ether * 1000);
      collateral.approve(address(borrowerOperations), 10 ether*1000);
      collateral.deposit{value: 10 ether * 1000}();

      uint shareAmount = 10 ether;
      uint256 collAmount = collateral.getPooledEthByShares(shareAmount);

      uint256 borrowedAmount;
      if (i == loop - 1)
          // here we compute borrowedAmount to make lastCdpId NCIR very close to firstCdpId NICR
          borrowedAmount = (1e20 * (shareAmount - collateral.getSharesByPooledEth(2e17))) / cdpManager.getSyncedNominalICR(firstCdpId);   // borrowedAmount = 0.65764 ether;
      else
          borrowedAmount = 0.5 ether;

      bytes32 id = borrowerOperations.openCdp(borrowedAmount, "hint", "hint", collAmount);

      if (i == 0)        {firstUser = user; firstCdpId = id;}
      if (i == loop - 1) {lastUser = user ; lastCdpId = id;}

      vm.stopPrank();
  }

  logNICR(firstCdpId, lastCdpId);
  // NICR 1st trove should be < NICR last trove
  assertLe(cdpManager.getSyncedNominalICR(firstCdpId), cdpManager.getSyncedNominalICR(lastCdpId));

  /// Let's increase the stETH by 40% and open a last cdp
  (uint256 oldIndex, uint256 newIndex) = _applyIndexChange(400000000000000000); // 40% stETH increase
  // get a random user
  address user = _utils.getNextUserAddress();
  vm.startPrank(user);

  uint256 collAmount = 10 ether;
  // deal ETH and deposit for collateral
  vm.deal(user, collAmount * 1000);
  collateral.approve(address(borrowerOperations), collAmount);
  collateral.deposit{value: collAmount * 1000}();

  uint borrowedAmount = 0.5 ether;
  borrowerOperations.openCdp(borrowedAmount, "hint", "hint", collAmount);
  vm.stopPrank();

  logNICR(firstCdpId, lastCdpId);
  // NICR 1st trove should be < NICR last cdp but it's not the case
  assertLe(cdpManager.getSyncedNominalICR(firstCdpId), cdpManager.getSyncedNominalICR(lastCdpId));
}

function logNICR(bytes32 firstCdpId, bytes32 lastCdpId) public {
  console.log("---------------------------------- 1st cdp");
  console.log("getCdpStake         : ", cdpManager.getCdpStake(firstCdpId));
  console.log("getCdpCollShares    : ", cdpManager.getCdpCollShares(firstCdpId));
  console.log("getSyncedNominalICR : ", cdpManager.getSyncedNominalICR(firstCdpId));
  console.log("---------------------------------- last cdp");
  console.log("getCdpStake         : ", cdpManager.getCdpStake(lastCdpId));
  console.log("getCdpCollShares    : ", cdpManager.getCdpCollShares(lastCdpId));
  console.log("getSyncedNominalICR : ", cdpManager.getSyncedNominalICR(lastCdpId));
  console.log("---");
  console.logInt(int(int(cdpManager.getSyncedNominalICR(firstCdpId))-int(cdpManager.getSyncedNominalICR(lastCdpId))));
  console.log("----------------------------------");
}

This test fails on the last assertion, meaning that the list is no longer sorted.

Recommended Mitigation Steps

This is hard to fix because the sorted list was not designed to work this way.

I haven’t been able to find a quick fix that preserves the list order with a fair redistribution.

Even if it is less fair for borrowers, a proportional distribution (without the corrected stake) can solve this problem but it will be an incomplete solution.

The eBTC team needs to rethink the fee/debt redistribution to maintain the list order.

Sources

https://github.com/liquity/dev/blob/main/papers/Efficient_Order-Preserving_Redistribution_of_Troves.pdf

Alex the Entreprenerd (Badger) commented:

The conclusion is wrong.

But the finding showed that the feeSplit math is incorrect, which is a severe finding.

rayeaster (Badger) commented:

It is more like a precision issue using Solidity instead of a fundamental design problem.

The following statement is worth more thinking: we can intuitively understand that new CDPs will pay more fees than the old ones. Therefore, new cpds NICR (Nominal Individual Collateral Ratio = shares/debt) will decrease at a higher rate than old ones.

Yes, higher stake leads to more fees, but it is NOT equal to “decrease at a higher rate”, actually the relative ratio of NICR between two CDPs always keep the same “theoretically” by the stake mechanism.

Note: please see sponsor’s original comment for full details regarding this.

If we could manually syncAccounting for the first CDP along the poc test path (i.e., always sync its collateral for every index increase in the loop) or simply set the loop number to 1000 instead of 100, the list order will not break at the end of the poc test.

And the break require some delicate conditions like significant increase of the Lido stETH index, e.g., 40% increase means about 10 years at the current staking reward apr.

I suggest to mark it as “acknowledged”.

ronnyx2017 (Judge) commented:

Thanks for the careful and clear math prove from @rayeaster, it’s very helpful to show the underlying mechanism of the issue based. It’s amazing. And I want to add a comment for s2 in T3. There is no need to worry about the impact of c and s1 on Sn and Cn1 in T1, as they grow proportionally. The mathematical calculations in T3 are completely correct, and you can further prove this. I have actually done it myself, but I’m not very good at writing mathematical formulas using Markdown. So, I’m only providing this conclusion to prevent any doubts about this.

And I add one line at the end of logNICR function in the original poc:

console.log(cdpManager.getSyncedNominalICR(firstCdpId) * 1e18 / cdpManager.getSyncedNominalICR(lastCdpId));

The console log can clearly show why the sponsor says it’s a precision issue:

Logs:
before
  ---------------------------------- 1st cdp
  getCdpStake         :  9800399201596806387
  getCdpCollShares    :  9800399201596806387
  getSyncedNominalICR :  1791162047648499053200
  ---------------------------------- last cdp
  getCdpStake         :  10760678217311938700
  getCdpCollShares    :  9833333333333333333
  getSyncedNominalICR :  1791162047648499053418
  ---
  -218
  999999999999999999
  ----------------------------------
 after
  ---------------------------------- current cdp
  getCdpStake         :  7660143815713583482
  getCdpCollShares    :  6125000000000000000
  getSyncedNominalICR :  1225000000000000000000
  ----------------------------------
  ---------------------------------- 1st cdp
  getCdpStake         :  9800399201596806387
  getCdpCollShares    :  9800399201596806387
  getSyncedNominalICR :  1567266791692436672600
  ---------------------------------- last cdp
  getCdpStake         :  10760678217311938700
  getCdpCollShares    :  9833333333333333333
  getSyncedNominalICR :  1567266791692436672219
  ---
  381
  1000000000000000000
  ----------------------------------

In fact, this variation is not linear. It requires the growth of the index to occur at an extremely precise value in order to generate this error.

And I also want to provide a poc test for the amazing math prove from @rayeaster, thanks again.

      function test_H2prove() public {
        vm.pauseGasMetering();

        address cdp1_user;
        address cdp2_user;
        bytes32 cdp1_id;
        bytes32 cdp2_id;

        // stake someting to init
        {
            address _nobody = prepareUser();
            vm.prank(_nobody);
            borrowerOperations.openCdp(1.337 ether, "hint", "hint", 31.415 ether);
            _applyIndexChange(1000000000000000); // +0.1% index
        }

        // T0
        {
            cdpManager.syncGlobalAccountingAndGracePeriod();
            uint Sn = cdpManager.totalStakesSnapshot();
            uint Cn0 = cdpManager.totalCollateralSnapshot();
            console.log(Sn, Cn0);
        }

        // const
        uint c = 10 ether;
        uint d = 0.5 ether;

        // T1
        cdp1_user = prepareUser();
        vm.prank(cdp1_user);
        cdp1_id = borrowerOperations.openCdp(d, "hint", "hint", c);
        // uint s1 = cdpManager.getCdpCollShares(cdp1_id);
        // console.log(s1);

        // T2
        {
            int delta_p1 = 2000000000000000; // +0.2% index
            _applyIndexChange(delta_p1);
            cdpManager.syncGlobalAccountingAndGracePeriod();
            // vm.prank(cdp1_user);
            // cdpManager.syncAccounting(cdp1_id);
        }

        // T3
        cdp2_user = prepareUser();
        vm.prank(cdp2_user);
        // c = 17 ether;
        // d = 1.1 ether;
        cdp2_id = borrowerOperations.openCdp(d, "hint", "hint", c);
        // uint s2 = cdpManager.getCdpCollShares(cdp2_id);
        // console.log(s2);

        // after T3, we should calc NICR rate
        uint wad = 1e18;
        {
            uint cdp1_NICR_T3 = cdpManager.getSyncedNominalICR(cdp1_id);
            uint cdp2_NICR_T3 = cdpManager.getSyncedNominalICR(cdp2_id);
            uint rate_T3 = cdp1_NICR_T3 * wad / cdp2_NICR_T3;
            console.log(rate_T3);
        }

        // T4
        {
            int delta_p2 = 400000000000000000; // +40% index
            _applyIndexChange(delta_p2);
            cdpManager.syncGlobalAccountingAndGracePeriod();
            // dump rate after T4
            uint cdp1_NICR_T4 = cdpManager.getSyncedNominalICR(cdp1_id);
            uint cdp2_NICR_T4 = cdpManager.getSyncedNominalICR(cdp2_id);
            uint rate_T4 = cdp1_NICR_T4 * wad / cdp2_NICR_T4;
            console.log(rate_T4);
            // console.log(cdpManager.getCdpCollShares(cdp1_id), cdpManager.getCdpCollShares(cdp2_id));
        }
      }

rayeaster (Badger) commented:

@ronnyx2017 - Thanks for the great proof test!

It helps to spark an interesting idea. Do you think it would help to use sth like cdpManager.getSyncedNominalICR(firstCdpId) * 1e18 / cdpManager.getSyncedNominalICR(lastCdpId) to compare the NICR as an additional check?

Note: please see sponsor’s original comment for full details.

ronnyx2017 (Judge) commented:

Aha, I think this check may be idealistic. The poc we are currently discussing only involves a single rounding situation, but the actual scenario may be much more complex. Each syncAccounting after a rebase introduces rounding, but I believe this will actually alleviate the impact of the issue.

rayeaster (Badger) commented:

If we add bad debt redistribution into the play, the ratio of NICR between CDPs would change but will NOT go to the extent that reverse the ordering.

Note: please see sponsor’s original comment for full details.

So the whole story would be:

  • Split fee distribution would keep the NICR ratio the same
  • Bad debt redistribution would change the NICR ratio a bit but still remain the ordering

ronnyx2017 (Judge) decreased severity to Medium and commented:

The impact based on bad debt redistribution is valid, but it can’t break the cdp order. Considering the fixes already introduced in Liquity, I suggest considering the impact of this issue in long-running systems. Therefore, I mark this issue as medium.


The original report as published on Code4rena, by 0xBeirao. 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 fee mechanism reduces totalCollateralSnapshot without updating totalStakesSnapshot, so new CDPs get a higher stake than older ones, causing their collateral ratios to change at different rates and potentially breaking the sorted order.

What the attacker needed

Significant stETH index increase; multiple CDPs opened

The fix

The eBTC team needs to rethink the fee/debt redistribution to maintain the list order, as no quick fix was found.

How it was found

  1. Open 100 CDPs with small stETH index increases between each.
  2. Increase the stETH index by 40%.
  3. Open another CDP with a collateral amount chosen to make its NICR close to the first CDP's NICR.
  4. Check that the first CDP's NICR is less than or equal to the last CDP's NICR; the test fails, showing the list is no longer sorted.

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.

In eBTC, borrowers open collateralized debt positions (CDPs) that are kept in a sorted list by their collateral ratio. The report found that the way fees are taken can make newer CDPs have a slightly different ratio than older ones, which can break the sorting. This could cause problems like failed transactions or unfair liquidations, but the effect is very small and requires extreme conditions.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by 0xBeirao

View all

2 more disclosed reports, best first.

More from eBTC Zap Router

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.