The constant product invariant can be broken.
The constant product invariant of a liquidity pool can be broken because the sync function updates reserves without updating the LP token supply. An attacker can donate tokens and call sync to make removeLiquidityImbalanced revert, causing a temporary denial of service for that function.
qpzm Follow with CRIMSON-RAT-REACH
Originally disclosed on Code4rena
Submitted by qpzm, also found by CRIMSON-RAT-REACH
https://github.com/code-423n4/2023-07-basin/blob/main/src/functions/ConstantProduct2.sol#L65-L66 https://github.com/code-423n4/2023-07-basin/blob/main/src/Well.sol#L590-L598 https://github.com/code-423n4/2023-07-basin/blob/main/src/Well.sol#L695-L702 https://github.com/code-423n4/2023-07-basin/blob/main/src/Well.sol#L541 https://github.com/code-423n4/2023-07-basin/blob/main/src/Well.sol#L562 https://github.com/code-423n4/2023-07-basin/blob/main/src/Well.sol#L582
Description
Let reserves returned by Well._getReserves() as x, y and Well.tokenSupply() as k. They must maintain the invariant x * y * EXP_PRECISION = k ** 2. However, the reserves can increase without updating the token supply if a user transfers one token of the well and call Well.sync(). We can sync the reserves and balances using Well.sync, but there is no way to sync Well.tokenSupply() ** 2 to x * y * EXP_PRECISION.
Impact
ConstantProduct2.calcReserve assumes Well.tokenSupply equals to reserves[0] * reserves[1]. This exception breaks the assumption and reverts normal transactions. For example, when Well.totalSupply is less than reserves[0] * reserves[1], Well.removeLiquidityImbalanced may revert.
- Comment out minting initial liquidity in
TestHelper.sol. https://github.com/code-423n4/2023-07-basin/blob/main/test/TestHelper.sol#L107
function setupWell(Call memory _wellFunction, Call[] memory _pumps, IERC20[] memory _tokens) internal {
// ...
// @audit comment out the line 107 to see apparently
// Add initial liquidity from TestHelper
// addLiquidityEqualAmount(address(this), initialLiquidity);
}
- Add the test in
Well.AddLiquidity.t.solas below. https://github.com/code-423n4/2023-07-basin/blob/main/test/Well.AddLiquidity.t.sol#L9
contract WellAddLiquidityTest is LiquidityHelper {
function setUp() public {
setupWell(2);
}
// @audit add this test
function test_tokenSupplyError() public {
IERC20[] memory tokens = well.tokens();
Balances memory userBalance;
Balances memory wellBalance = getBalances(address(well), well);
console.log(wellBalance.lpSupply); // 0
mintTokens(user, 10000000e18);
vm.startPrank(user);
tokens[0].transfer(address(well), 100);
tokens[1].transfer(address(well), 100);
vm.stopPrank();
userBalance = getBalances(user, well);
console.log(userBalance.lp); // 0
addLiquidityEqualAmount(user, 1);
userBalance = getBalances(user, well);
console.log(userBalance.lp); // 1e6
well.sync(); // reserves = [101, 101]
uint256[] memory amounts = new uint256[](tokens.length);
amounts[0] = 1;
// FAIL: Arithmetic over/underflow
vm.prank(user);
well.removeLiquidityImbalanced(type(uint256).max, amounts, user, type(uint256).max);
}
}
- I commented the reason of underflow. https://github.com/code-423n4/2023-07-basin/blob/main/src/Well.sol#L562
function removeLiquidityImbalanced(
uint256 maxLpAmountIn,
uint256[] calldata tokenAmountsOut,
address recipient,
uint256 deadline
) external nonReentrant expire(deadline) returns (uint256 lpAmountIn) {
IERC20[] memory _tokens = tokens();
uint256[] memory reserves = _updatePumps(_tokens.length);
for (uint256 i; i < _tokens.length; ++i) {
_tokens[i].safeTransfer(recipient, tokenAmountsOut[i]);
reserves[i] = reserves[i] - tokenAmountsOut[i];
}
// @audit
// 1e6 - sqrt(101 * (101 - 1) * 1000000 ** 2)
// <=> 1e6 - 100498756
lpAmountIn = totalSupply() - _calcLpTokenSupply(wellFunction(), reserves);
if (lpAmountIn > maxLpAmountIn) {
revert SlippageIn(lpAmountIn, maxLpAmountIn);
}
_burn(msg.sender, lpAmountIn);
_setReserves(_tokens, reserves);
emit RemoveLiquidity(lpAmountIn, tokenAmountsOut, recipient);
}
Recommended Mitigation Steps
In Well.sync(), mint (reserves[0] * reserves[1] * ConstantProduct2.EXP_PRECISION).sqrt() - totalSupply() Well tokens to msg.sender.
This keeps the invariant that Well.tokenSupply() ** 2 equals to reserves[0] * reserves[1] * ConstantProduct2.EXP_PRECISION as long as the swap fee is 0.
publiuss (Basin) confirmed via duplicate issue #210
This is a good find. However it is hard to find rationalization for HIGH impact. Root issue is: attacker can make it so that there is more funds in the pool than there are supposed to be. The loser of the donation + sync() transaction is the attacker! LP providers will be able to redeem their shares with either:
removeLiquidityOneToken()removeLiquidity()Specifically,
removeLiquidityImbalancedwill revert because of underflow, but there is no loss or freeze of funds. Therefore it seems clear that maximum severity would be Medium, because a one specific functionality is blocked. For High, according to the C4 severity guidelines warden must demonstrate a viable loss of funds or breaking the core of the protocol. That is not the case here.
After careful consideration, I’m going to disagree with @trust1995, here is why.
The nature of a DoS is that it is temporary. Either because it takes resources from the attacker to maintain the DoS, or because the victim can eventually change its configuration to stop the DoS.
In this case, the DoS is permanent. The attacker can disable a certain functionality permanently and in all pools. The only possible remedy for Moonwell would be to convince all LPs to remove liquidity, and then to add it again in fixed Wells, which is completely unrealistic.
To me, losing forever a feature is worse than not being able to operate at all for a short period of time. You don’t ever fully recover. Moreover, the invariant of the pools is also broken forever.
There are no severities between Medium and High, so if I have to choose, I’ll have to choose High for this one.
I appreciate the thought you have put into the submission.
However, I believe “losing a feature, forever” is not a HIGH severity rationalization, and there is no case law in C4 to support that it is. I refer you to the two leading severity standards, the C4 standard and the Immunefi standard. Here is how C4 differentiates between Med and High:
2 — Med: Assets not at direct risk, but the function of the protocol or its availability could be impacted, or leak value with a hypothetical attack path with stated assumptions, but external requirements. 3 — High: Assets can be stolen/lost/compromised directly (or indirectly if there is a valid attack path that does not have hand-wavy hypotheticals).
Clearly this is a “function of the protocol or its availability could be impacted” scenario.
Here’s how Immunefi would classify the issue:
Low - Contract fails to deliver promised returns, but doesn’t lose value: This is when the code doesn’t work as intended (i.e. there is some logic error but that logic error doesn’t affect the protocol’s funds or user funds). Another example would be an external function that is meant to return a value does not return the correct thing, however, this value is not used elsewhere in application logic.
The last thing I would say is the following plot twist - we are actually NOT even losing a functionality forever. There is an easy bypass to calling
removeLiquidityImbalanced(). Instead, simply call the two functions:
- removeLiquidity() - remove any balanced amount of liquidity
- removeLiquidityOneToken() - remove any remaining liquidity of the higher between the token amounts.
In a worst case scenario, the frontend can implement imbalanced withdrawals with these two calls or just the 2nd call.
Most judges would consider it QA as there is basically no impact, inconvenience at most. To call it a HIGH would be, from my professional opinion, unthinkable.
lokithe5th (Warden) commented:
Please forgive me if this is inappropriate @alcueca and @trust1995 , but I might add the following evidence for consideration:
Fixing the imbalance is trivial, and will likely happen by accident if another user adds liquidity. This is because of the same mechanism as described in this PoC.
This boils down to a quirk of this specific implementation: when there is a discrepancy between the reserves and the
totalSupply, it is corrected in the next call toaddLiquidityorswapFrom.However, it must be noted that this may open up the contract to more consistent DoS attacks: the attacker can donate and force underflow, and then regain their attack funds by calling
addLiquidityorswapFrom, but at the cost of removing the block. This would be a risky attack, as any user can front-run and steal the attacker’s donation.
alcueca (Judge) decreased severity to Medium and commented:
Thanks @lokithe5th, it is true that the DoS is not permanent and easily reversed. Downgraded to Medium.
This was addressed by modifying the
sync()function to to have the signaturesync(address recipient, uint256 minLpAmountOut)and mint LP tokens torecipientaddress to prevent the invariant from breaking. It now behaves like ashift(...)for adding liquidity instead of swapping.
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
The sync function updates reserves without minting or burning LP tokens, so the invariant between reserves and totalSupply is not maintained.
Impact
The removeLiquidityImbalanced function reverts due to underflow, but other withdrawal functions still work and the denial of service is temporary and can be reversed by adding liquidity or swapping.
What the attacker needed
Attacker can transfer tokens to the pool; attacker can call sync
The fix
The sync function was modified to mint LP tokens to a recipient, preventing the invariant from breaking.
How it was found
- Comment out the initial liquidity minting in the test helper.
- Add a test that transfers tokens directly to the well and calls sync.
- Call removeLiquidityImbalanced and observe the arithmetic underflow revert.
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 liquidity pool holds two tokens and tracks shares (LP tokens) that represent ownership. The pool's math assumes the product of token reserves equals the square of the LP token supply. If someone sends tokens directly to the pool and calls sync, the reserves increase but the LP supply stays the same, breaking that assumption. This can make one withdrawal function fail, but other withdrawal methods still work.
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.