UNION rewards issuance can be maximized without providing credit
The reward calculation only updates when a user calls stake, unstake, or withdrawRewards, so a staker can wait a long time, then briefly lend to themselves to become a member and immediately withdraw rewards, receiving the maximum multiplier for the entire period without bearing credit risk or paying interest. This inflates UNION emissions and dilutes honest holders.
Source: https://github.com/sherlock-audit/2022-10-union-finance-judging/issues/49
Found by
hyh
Summary
UNION rewards accounting is run on user direct request and stake/unstake only, and due to this can be gamed to obtain maximal rewards without any involvement in UNION, and in a risk-free way.
Vulnerability Detail
Reward calculation currently is being invoked only as a part of user-facing stake(), unstake() and withdrawRewards(). Notice that withdrawRewards() calculates the rewards for msg.sender, so it cannot be triggered automatically by a script for all active users to refresh their accounting. This way UNION rewards are calculated only per user request and there are no updates on key account state changing operations.
This combination allows a malicious user to receive rewards with maximal 2x multiplier without participating in UNION, particularly without bearing any credit risk or interest expenses.
Say Bob the staker wants to maximize UNION rewards and minimize the corresponding risk. Bob stakes and do nothing else for a prolonged period, say 2 years. Then he becomes a member, loans to himself the full stake via another account and immediately calls withdrawRewards(), obtaining rewards for the whole 2 year period, his full stake, with the maximal multiplier, i.e. with _getRewardsMultiplier of 2.
Impact
Bloated UNION rewards emissions attacker initiates dilute holdings of the honest members who do not time their withdrawRewards() calls to the points of reward multiplier maximization.
This is monetary loss for all UNION holders (as total emission is increased), and particularly for the stakers who actually use the system (as specifically new emission is increased), i.e. in result the attacker steals from all holders/stakers by inflating UNION emission.
Setting severity to be high as there are no specific preconditions for the attack, it can be carried out by any UNION staker.
Code Snippet
The only function that updates the rewards due to a particular user is Comptroller's _calculateRewardsByBlocks().
_calculateRewardsByBlocks() calculates the rewards based on the current state of a user:
function _calculateRewardsByBlocks(
address account,
address token,
uint256 pastBlocks,
Info memory userInfo,
UserManagerState memory userManagerState,
UserManagerAccountState memory userManagerAccountState
) internal view returns (uint256) {
IUserManager userManagerContract = _getUserManager(token);
// Lookup account state from UserManager
userManagerAccountState.totalStaked = userManagerContract.getStakerBalance(account);
userManagerAccountState.totalLocked = userManagerContract.getTotalLockedStake(account);
userManagerAccountState.isMember = userManagerContract.checkIsMember(account);
uint256 inflationIndex = _getRewardsMultiplier(
userManagerAccountState.totalStaked,
userManagerAccountState.totalLocked,
userManagerAccountState.totalFrozen,
userManagerAccountState.isMember
);
return
userInfo.accrued +
_calculateRewards(
account,
token,
userManagerState.totalStaked,
userManagerAccountState.totalStaked,
userManagerAccountState.pastBlocksFrozenCoinAge,
pastBlocks,
inflationIndex
);
}
Specifically, inflationIndex is based solely on the current state of user's account:
inflationIndex = _getRewardsMultiplier(
userManagerAccountState.totalStaked,
userManagerAccountState.totalLocked,
userManagerAccountState.totalFrozen,
userManagerAccountState.isMember
)
_calculateRewards() multiplies the whole (curInflationIndex - startInflationIndex).wadMul(effectiveStakeAmount) by the inflationIndex:
function _calculateRewards(
address account,
address token,
uint256 totalStaked,
uint256 userStaked,
uint256 frozenCoinAge,
uint256 pastBlocks,
uint256 inflationIndex
) internal view returns (uint256) {
uint256 startInflationIndex = users[account][token].inflationIndex;
if (userStaked * pastBlocks < frozenCoinAge) revert FrozenCoinAge();
if (userStaked == 0 || totalStaked == 0 || startInflationIndex == 0 || pastBlocks == 0) {
return 0;
}
uint256 effectiveStakeAmount = (userStaked * pastBlocks - frozenCoinAge) / pastBlocks;
uint256 curInflationIndex = _getInflationIndexNew(totalStaked, pastBlocks);
if (curInflationIndex < startInflationIndex) revert InflationIndexTooSmall();
return (curInflationIndex - startInflationIndex).wadMul(effectiveStakeAmount).wadMul(inflationIndex);
}
inflationIndex = _getRewardsMultiplier(...) is based on the current state of a user:
function _getRewardsMultiplier(
uint256 userStaked,
uint256 lockedStake,
uint256 totalFrozen_,
bool isMember_
) internal pure returns (uint256) {
if (isMember_) {
if (userStaked == 0 || totalFrozen_ >= lockedStake) {
return memberRatio;
}
uint256 effectiveLockedAmount = lockedStake - totalFrozen_;
uint256 effectiveStakeAmount = userStaked - totalFrozen_;
uint256 lendingRatio = effectiveLockedAmount.wadDiv(effectiveStakeAmount);
return lendingRatio + memberRatio;
} else {
return nonMemberRatio;
}
}
_calculateRewardsByBlocks() is invoked in Comptroller only as a part of two call sequences:
calculateRewards() -> calculateRewardsByBlocks() -> _calculateRewardsByBlocks(),
withdrawRewards() -> _calculateRewardsByBlocks().
Comptroller's calculateRewards() and calculateRewardsByBlocks() are public views, not used elsewhere:
/**
* @dev Calculate unclaimed rewards based on blocks
* @param account User address
* @param token Staking token address
* @param futureBlocks Number of blocks in the future
* @return Unclaimed rewards
*/
function calculateRewardsByBlocks(
address account,
address token,
uint256 futureBlocks
) public view override returns (uint256) {
IUserManager userManager = _getUserManager(token);
// Lookup account stataddress accounte from UserManager
(
UserManagerAccountState memory userManagerAccountState,
Info memory userInfo,
uint256 pastBlocks
) = _getUserInfoView(userManager, account, token, futureBlocks);
// Lookup global state from UserManager
UserManagerState memory userManagerState = _getUserManagerState(userManager);
return
_calculateRewardsByBlocks(account, token, pastBlocks, userInfo, userManagerState, userManagerAccountState);
}
/**
* @dev Calculate currently unclaimed rewards
* @param account Account address
* @param token Staking token address
* @return Unclaimed rewards
*/
function calculateRewards(address account, address token) external view override returns (uint256) {
return calculateRewardsByBlocks(account, token, 0);
}
This way the only rewards accounting update is Comptroller's withdrawRewards(), which is onlyUserManager, and is called via user facing UserManager's stake(), unstake() and withdrawRewards():
function withdrawRewards(address account, address token)
external
override
whenNotPaused
onlyUserManager(token)
returns (uint256)
{
IUserManager userManager = _getUserManager(token);
// Lookup account state from UserManager
(
UserManagerAccountState memory userManagerAccountState,
Info memory userInfo,
uint256 pastBlocks
) = _getUserInfo(userManager, account, token, 0);
// Lookup global state from UserManager
UserManagerState memory userManagerState = _getUserManagerState(userManager);
uint256 amount = _calculateRewardsByBlocks(
account,
token,
pastBlocks,
userInfo,
userManagerState,
userManagerAccountState
);
/**
* @dev collect staker rewards from the comptroller
*/
function withdrawRewards() external whenNotPaused nonReentrant {
comptroller.withdrawRewards(msg.sender, stakingToken);
}
function stake(uint96 amount) public whenNotPaused nonReentrant {
IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken);
comptroller.withdrawRewards(msg.sender, stakingToken);
function unstake(uint96 amount) external whenNotPaused nonReentrant {
Staker storage staker = stakers[msg.sender];
// Stakers can only unstaked stake balance that is unlocked. Stake balance
// becomes locked when it is used to underwrite a borrow.
if (staker.stakedAmount - staker.locked < amount) revert InsufficientBalance();
comptroller.withdrawRewards(msg.sender, stakingToken);
I.e. there are no others means to actualize the rewards, the users can update whenever they want and this can be the only update for them.
This allows to remove both credit risk and interest expenses. I.e. there is no dilemma either lend to self and pay the interest or lend to someone else and bear the credit risk: it's possible to do nothing, wait for any desired time, then lend to self for 1 block, neither paying any meaningful interest, nor bearing any credit risk, and reap the UNION rewards for the whole period with the maximal multiplier.
Tool used
Manual Review
Recommendation
Member registration and trust utilization change, i.e. borrowings and repayments, should trigger reward accounting update to correctly reflect the timing of changes in the reward formula.
As the most direct mitigation consider adding the staker's reward update to registerMember, updateLocked and debtWriteOff functions that change the account state and the values of the corresponding reward formula components.
registerMember():
function registerMember(address newMember) public virtual whenNotPaused {
if (stakers[newMember].isMember) revert NoExistingMember();
uint256 count = 0;
uint256 vouchersLength = vouchers[newMember].length;
// Loop through all the vouchers to count how many active vouches there
// are that are greater than 0. Vouch is the min of stake and trust
for (uint256 i = 0; i < vouchersLength; i++) {
Vouch memory vouch = vouchers[newMember][i];
Staker memory staker = stakers[vouch.staker];
if (staker.stakedAmount > 0) count++;
if (count >= effectiveCount) break;
}
if (count < effectiveCount) revert NotEnoughStakers();
+ comptroller.withdrawRewards(newMember, stakingToken);
stakers[newMember].isMember = true;
IUnionToken(unionToken).burnFrom(msg.sender, newMemberFee);
emit LogRegisterMember(msg.sender, newMember);
}
updateLocked():
function updateLocked(
address borrower,
uint96 amount,
bool lock
) external onlyMarket {
uint96 remaining = amount;
for (uint256 i = 0; i < vouchers[borrower].length; i++) {
Vouch storage vouch = vouchers[borrower][i];
uint96 innerAmount;
if (lock) {
// Look up the staker and determine how much unlock stake they
// have available for the borrower to borrow. If there is 0
// then continue to the next voucher in the array
uint96 stakerLocked = stakers[vouch.staker].locked;
uint96 stakerStakedAmount = stakers[vouch.staker].stakedAmount;
uint96 availableStake = stakerStakedAmount - stakerLocked;
uint96 lockAmount = _min(availableStake, vouch.trust - vouch.locked);
if (lockAmount == 0) continue;
// Calculate the amount to add to the lock then
// add the extra amount to lock to the stakers locked amount
// and also update the vouches locked amount and lastUpdated block
innerAmount = _min(remaining, lockAmount);
+ comptroller.withdrawRewards(vouch.staker, stakingToken);
stakers[vouch.staker].locked = stakerLocked + innerAmount;
vouch.locked += innerAmount;
vouch.lastUpdated = uint64(block.number);
} else {
// Look up how much this vouch has locked. If it is 0 then
// continue to the next voucher. Then calculate the amount to
// unlock which is the min of the vouches lock and what is
// remaining to unlock
uint96 locked = vouch.locked;
if (locked == 0) continue;
innerAmount = _min(locked, remaining);
// Update the stored locked values and last updated block
+ comptroller.withdrawRewards(vouch.staker, stakingToken);
stakers[vouch.staker].locked -= innerAmount;
vouch.locked -= innerAmount;
vouch.lastUpdated = uint64(block.number);
}
debtWriteOff():
function debtWriteOff(
address staker,
address borrower,
uint96 amount
) external {
if (amount == 0) revert AmountZero();
uint256 overdueBlocks = uToken.overdueBlocks();
uint256 lastRepay = uToken.getLastRepay(borrower);
// This function is only callable by the public if the loan is overdue by
// overdue blocks + maxOverdueBlocks. This stops the system being left with
// debt that is overdue indefinitely and no ability to do anything about it.
if (block.number <= lastRepay + overdueBlocks + maxOverdueBlocks) {
if (staker != msg.sender) revert AuthFailed();
}
Index memory index = voucherIndexes[borrower][staker];
if (!index.isSet) revert VoucherNotFound();
Vouch storage vouch = vouchers[borrower][index.idx];
if (amount > vouch.locked) revert ExceedsLocked();
+ comptroller.withdrawRewards(staker, stakingToken);
// update staker staked amount
stakers[staker].stakedAmount -= amount;
stakers[staker].locked -= amount;
totalStaked -= amount;
// update vouch trust amount
vouch.trust -= amount;
vouch.locked -= amount;
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 reward multiplier is based on the user's current state at the time of withdrawal, but reward accounting is not updated when key state changes (like becoming a member or changing locked stake) occur, allowing users to retroactively apply a higher multiplier to past blocks.
Impact
The attacker inflates UNION emissions, causing monetary loss for all UNION holders and particularly for stakers who actually use the system; the text states there are no specific preconditions and any staker can carry it out.
What the attacker needed
A UNION staker account; a second account to lend to self; no other specific preconditions
The fix
Reward accounting should be updated on member registration and on changes to locked stake and debt write-offs, so that the multiplier reflects the state at the time rewards were earned.
How it was found
- Stake tokens and do nothing else for a prolonged period.
- Become a member by registering.
- Loan to yourself the full stake via another account.
- Immediately call withdrawRewards().
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.
Rewards in this system are only calculated when you personally trigger an update, such as by staking or withdrawing. A user can leave their stake idle for a long time, then quickly perform a small action that makes them eligible for a higher reward rate, and immediately collect rewards for the whole idle period at that higher rate. This means they get more rewards than they should, which increases the total number of tokens issued and reduces the value of everyone else's tokens.
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.