Skip to content
Smart contracts Audit finding Intermediate

Risk of silent overflow in reserves update

The buy and sell functions cast uint256 values to uint128 without checking for overflow, so a trade with large amounts could silently wrap the virtual reserves. This would break the constant-product pricing invariant and lead to incorrect price calculations, potentially causing financial losses.

sashik_eth Follow with codeslide, Kaysoft and 22 others

Originally disclosed on Code4rena

Submitted by sashik_eth, also found by codeslide, Kaysoft, W0RR1O, georgits, btk, lukris02, 0x6980, tnevler, 0xAgro, matrix_0wl, catellatech, Sathish9098, ayden, 0x4non, adriro, Madalad, Kenshin, giovannidisiena, devscrooge, sayan, SaeedAlipoor01988, tsvetanovv, Cryptor, and matrix_0wl

https://github.com/code-423n4/2023-04-caviar/blob/main/src/PrivatePool.sol#L230-L231

https://github.com/code-423n4/2023-04-caviar/blob/main/src/PrivatePool.sol#L323-L324

Vulnerability details

The buy() and sell() functions update the virtualBaseTokenReserves and virtualNftReserves variables during each trade. However, these two variables are of type uint128, while the values that update them are of type uint256. This means that casting to a lower type is necessary, but this casting is performed without first checking that the values being cast can fit into the lower type. As a result, there is a risk of a silent overflow occurring during the casting process.

    function buy(uint256[] calldata tokenIds, uint256[] calldata tokenWeights, MerkleMultiProof calldata proof)
        public
        payable
        returns (uint256 netInputAmount, uint256 feeAmount, uint256 protocolFeeAmount)
    {
        // ~~~ Checks ~~~ //

        // calculate the sum of weights of the NFTs to buy
        uint256 weightSum = sumWeightsAndValidateProof(tokenIds, tokenWeights, proof);

        // calculate the required net input amount and fee amount
        (netInputAmount, feeAmount, protocolFeeAmount) = buyQuote(weightSum);
        ...
        // update the virtual reserves
        virtualBaseTokenReserves += uint128(netInputAmount - feeAmount - protocolFeeAmount);
        virtualNftReserves -= uint128(weightSum);
        ...

Impact

If the reserves variables are updated with a silent overflow, it can lead to a breakdown of the xy=k equation. This, in turn, would result in a totally incorrect price calculation, causing potential financial losses for users or pool owners.

Proof of Concept

Consider the scenario with a base token that has high decimals number described in the next test (add it to the test/PrivatePool/Buy.t.sol):

    function test_Overflow() public {
        // Setting up pool and base token HDT with high decimals number - 30
        // Initial balance of pool - 10 NFT and 100_000_000 HDT
        HighDecimalsToken baseToken = new HighDecimalsToken();
        privatePool = new PrivatePool(address(factory), address(royaltyRegistry), address(stolenNftOracle));
        privatePool.initialize(
            address(baseToken),
            nft,
            100_000_000 * 1e30,
            10 * 1e18,
            changeFee,
            feeRate,
            merkleRoot,
            true,
            false
        );

        // Minting NFT on pool address
        for (uint256 i = 100; i < 110; i++) {
            milady.mint(address(privatePool), i);
        }
        // Adding 8 NFT ids into the buying array
        for (uint256 i = 100; i < 108; i++) {
            tokenIds.push(i);
        }
        // Saving K constant (xy) value before the trade
        uint256 kBefore = uint256(privatePool.virtualBaseTokenReserves()) * uint256(privatePool.virtualNftReserves());

        // Minting enough HDT tokens and approving them for pool address
        (uint256 netInputAmount,, uint256 protocolFeeAmount) = privatePool.buyQuote(8 * 1e18);
        deal(address(baseToken), address(this), netInputAmount);
        baseToken.approve(address(privatePool), netInputAmount);

        privatePool.buy(tokenIds, tokenWeights, proofs);

        // Saving K constant (xy) value after the trade
        uint256 kAfter = uint256(privatePool.virtualBaseTokenReserves()) * uint256(privatePool.virtualNftReserves());

        // Checking that K constant succesfully was changed due to silent overflow
        assertEq(kBefore, kAfter, "K constant was changed");
    }

Also add this contract into the end of Buy.t.sol file for proper test work:

    contract HighDecimalsToken is ERC20 {
        constructor() ERC20("High Decimals Token", "HDT", 30) {}
    }

Recommended Mitigation Steps

Add checks that the casting value is not greater than the uint128 type max value:

File: PrivatePool.sol
229:         // update the virtual reserves
+            if (netInputAmount - feeAmount - protocolFeeAmount > type(uint128).max) revert Overflow();
230:         virtualBaseTokenReserves += uint128(netInputAmount - feeAmount - protocolFeeAmount);
+            if (weightSum > type(uint128).max) revert Overflow();
231:         virtualNftReserves -= uint128(weightSum);

File: PrivatePool.sol
322:         // update the virtual reserves
+            if (netOutputAmount + protocolFeeAmount + feeAmount > type(uint128).max) revert Overflow();
323:         virtualBaseTokenReserves -= uint128(netOutputAmount + protocolFeeAmount + feeAmount);
+            if (weightSum > type(uint128).max) revert Overflow();
324:         virtualNftReserves += uint128(weightSum);

outdoteth (Caviar) acknowledged

Alex the Entreprenerd (judge) commented:

The Warden has identified a risky underflow due to unsafe casting, the underflow would cause the invariants of the protocol to be broken, causing it to behave in undefined ways, most likely allowing to discount tokens (principal)

I have considered downgrading to Medium Severity

However, I believe that in multiple cases the subtractions netInputAmount - feeAmount - protocolFeeAmount which could start with netInputAmount > type(uint128).max would not necessarily fall within a uint128

For this reason, I believe the finding to be of High Severity.

outdoteth (Caviar) mitigated:

Fixed in https://github.com/outdoteth/caviar-private-pools/pull/10.

Status: Mitigation confirmed. Full details in reports from rbserver, KrisApostolov, and rvierdiiev.


The original report as published on Code4rena, by sashik_eth. 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 code casts uint256 trade amounts to uint128 for the virtual reserves without first checking that the values fit within uint128.

Impact

The pricing invariant could break, leading to totally incorrect price calculations and potential financial losses for users or pool owners; the judge rated it high severity.

What the attacker needed

Base token with very high decimals; pool with large virtual reserves; ability to execute a buy or sell trade

The fix

The issue was fixed by adding checks that each value being cast does not exceed the maximum uint128 value before updating the reserves.

How it was found

  1. Deploy a base token with a very high number of decimals and initialise a private pool with large reserves.
  2. Mint NFTs to the pool and prepare an array of token IDs to buy.
  3. Record the product of the virtual reserves before the trade.
  4. Mint and approve enough base tokens for the quoted buy amount.
  5. Call buy and record the product of the virtual reserves afterwards.
  6. Observe that the product is unchanged, showing the reserves were corrupted by silent overflow.

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 smart contract stores some numbers in a smaller container than the values being put into it. If a value is too big, it wraps around to a small number without any error, like an odometer rolling over. That corrupts the pool's pricing maths and could let someone trade at a wrong price.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by sashik_eth

View all

5 more disclosed reports, best first.

More from Caviar Private Pools

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.