Skip to content
Business logic Write-up Intermediate

[web3] Tidal Finance Logic Error Bug Fix Postmortem. This is a postmortem of a vulnerability… | by Immunefi | Nov, 2021 | Medium

A logic error in Tidal Finance's staking contract allowed a malicious user to claim more rewards than they were entitled to. The attacker could deposit after a payout was finalised and then call doPayout to increase their reward amount without a corresponding reward debt, potentially stealing unearned rewards.

medium.com

Published on medium.com

Tidal Finance

Immunefi, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

Tidal Finance is a decentralized discretionary mutual cover protocol that lets the DeFi community hedge against the failure of any DeFi protocol or asset. The vulnerability described here sat in the project's staking contract, deployed on Polygon, and concerned the way staking rewards are paid out.

Reward payout in that contract is a four-part sequential process: startPayout, setPayout, doPayout and finishPayout. The most important of the four is doPayout, because that is where a user's reward is calculated. The contract tracks two per-user values: user.rewardAmount, the reward figure generated by normal staking, and user.rewardDebt, which records how much of that reward has already been accounted for. The final payout is meant to result from the subtraction user.rewardAmount - user.rewardDebt.

At the time of the report, approximately 300 million Tidal tokens were locked in the staking contract.

Setup

Whitehat Csanuragjain submitted the vulnerability to Immunefi on July 31, 2021. The report does not describe any particular tooling, accounts or environment beyond the staking contract itself, which is identified by a commit in the Tidal Finance contracts repository. The described attack involves an admin who initiates payouts and a malicious user who enters the pool and later calls doPayout with an asset index and a wallet address as arguments.

Finding it

The issue is a logic error: it allowed a malicious user to claim more rewards from staking than they were entitled to. What makes it interesting is that the attacker does not need to have made any payment into the pool for the affected asset index. The flaw becomes reachable once a payout for an asset index has been finalised, because the reward debt is then not updated and stays at 0.

Exploitation

The steps to execute the attack are as follows.

Step 1: the admin initiates a payout for Asset Index 0

The admin starts the payout process for Asset Index 0. This is the ordinary administrative action that opens the four-part sequence.

Step 2: the four payout functions run in order and the payout is marked as finished

startPayout, setPayout, doPayout and finishPayout are called in sequential order, and the payout is marked as finished. From this point the asset index has a finalised payout.

Step 3: the attacker enters the pool and deposits an arbitrary amount

Once Asset Index 0 is finished, a malicious user enters the pool and deposits some arbitrary amount. The deposit gives the attacker a position in the pool after the payout was finalised.

Step 4: after some time, the attacker calls doPayout

After some amount of time, say a year, the malicious user calls doPayout with the Asset Index 0 and an attacker wallet address as an argument.

Step 5: the reward is allocated without a matching debt

Despite the fact that the malicious user has not made any payment, the user's reward is calculated in the user.rewardAmount variable, but user.rewardDebt is still 0. The system therefore cannot tell that the reward has already been allocated.

In other words, because the asset index had a finalised payout, user.rewardAmount increased without a corresponding increase in user.rewardDebt. Because the value of any unset variable in Solidity is 0, the attacker now has more rewards than they should be entitled to. The normal staking process generates a reward figure stored in user.rewardAmount, and the final payout should result from the subtraction user.rewardAmount - user.rewardDebt, but that subtraction does not properly occur because user.rewardDebt is mistakenly at 0.

The exploit cannot simply be run repeatedly: the bug depends on how much reward accumulates from staking and on what percentage of the pool is owned at the time an attacker decides to execute an attack.

Root cause

The mistake is a logic error in the reward accounting. The line that updates the reward debt already existed in the code, but it was not activated at the right point in the logic flow. When a payout for an asset index had been finalised, doPayout increased user.rewardAmount while user.rewardDebt was still 0. The subtraction that is supposed to net the two values therefore had nothing to subtract, and the attacker's claim was not reduced by what had already been allocated.

Impact

A malicious user could claim an unearned share of the rewards generated by staking activity, taking rewards for staking they never did. Approximately 300 million Tidal tokens were locked in the staking contract at the time. Because the trigger condition requires multiple requirements to be met during a claim and payout process, it is unclear how much could have been stolen with additional claims. The exploit also depends on how much reward accumulates from staking and on the percentage of the pool owned at the moment of the attack, so it cannot simply be run repeatedly.

Fix

The fix was already present in the code itself but not activated at the right point in the logic flow. The Tidal team duplicated the line

Solidity
user.rewardDebt = user.amount.mul(poolInfo.accRewardPerShare).div(UNIT_PER_SHARE);

and moved it up so that it is included in the if statement if (payoutInfo[assetIndex_][payoutId].finished). The reward debt amount is now updated after payout, which ensures that it does not remain 0. With the debt properly updated, a malicious user cannot take rewards generated from staking that they are not entitled to.

Tidal Finance quickly patched the bug and paid out a $25,000 USDT bounty to the whitehat.

Variants to test

  1. Look for reward or dividend accounting that subtracts a per-user debt from a per-user accrued amount. Check whether the debt is written on every path that increases the accrued amount, including paths taken after an epoch, round or payout has been finalised. A positive result is a path where the accrued amount rises while the debt stays at its default value.
  2. Check the ordering of state updates around finalisation flags such as finished. If a branch guarded by a finalised flag skips the debt update, a user who joins after finalisation can claim against rewards they never contributed to. A positive result is a claim that succeeds for a user whose deposit postdates the finalisation.
  3. Test whether the claim function can be called with an arbitrary asset index and an arbitrary recipient address. If the caller can direct the payout to a wallet of their choosing, the accounting error becomes directly monetisable. A positive result is a payout to an address that never staked in that index.
  4. Vary the timing and size of the deposit relative to the accumulated reward, since the report notes the outcome depends on accumulated rewards and the attacker's share of the pool. A positive result is a claim that scales with accumulated rewards rather than with the attacker's own contribution.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

What happened, in plain words

Tidal Finance is a service in the world of DeFi. DeFi, short for decentralised finance, is a set of financial applications that run on a blockchain instead of inside a bank. Tidal Finance describes itself as a decentralised discretionary mutual cover protocol: in everyday terms, it lets people buy protection (cover) against another DeFi project or asset failing, a bit like an insurance pool run by code rather than by a company.

Part of Tidal's system was a staking contract. A contract here is not a paper document: it is a small program that lives on a blockchain and holds funds. Staking means locking your tokens into such a program for a while, and in return the program pays you rewards, similar to interest on a savings account. A token is a digital unit of value on a blockchain; Tidal tokens are the project's own token.

The bug was a logic error in that staking contract. A logic error means the code does what it was written to do, but the rules it enforces are wrong: nothing crashes, no password is broken, the program simply follows a flawed sequence of steps. In this case the flawed sequence let a malicious user claim more staking rewards than they had earned. At the time, roughly 300 million Tidal tokens were locked in the staking contract.

The whitehat Csanuragjain reported the issue to Immunefi on July 31, 2021. A whitehat is a security researcher who finds bugs and reports them to the owner instead of abusing them. Immunefi is a bug bounty platform: projects publish a program, researchers report bugs through it, and the project pays a reward, called a bounty, for valid findings. Tidal Finance patched the bug quickly and paid a $25,000 USDT bounty. USDT is a stablecoin, a token designed to stay close in value to the US dollar.

From the original on medium.com

The image above is the header of the bugfix review post, titled "Tidal Finance Logic Error Bugfix Review", published by Immunefi.

The product and the feature involved

To follow the bug you only need to understand one feature: paying out staking rewards.

In the Tidal staking contract, paying rewards is a four-part sequence of functions. A function is a named block of code in a contract that can be triggered, either by a person sending a transaction or by another piece of code. The four functions are:

  1. startPayout
  2. setPayout
  3. doPayout
  4. finishPayout

The most important one for this story is doPayout, because that is where a user's reward is calculated.

The contract keeps two numbers for each user:

  • user.rewardAmount: the reward figure generated by normal staking, that is, how much reward the user has accrued.
  • user.rewardDebt: a record of how much of that reward has already been accounted for, so it is not paid twice.

The final payout is meant to be the subtraction user.rewardAmount - user.rewardDebt. Think of a loyalty card at a coffee shop: rewardAmount is the number of free coffees you have earned so far, and rewardDebt is the number you have already collected. What you can still claim is the difference. If the second number is wrong, you can collect coffees you never earned.

Finding it

The issue is a logic error that allowed a malicious user to claim more rewards from staking than they were entitled to. What makes it interesting is that the attacker does not need to have made any payment into the pool for the affected asset index. An asset index is simply a numbered slot that identifies which asset a payout refers to; here the relevant one is Asset Index 0. A pool is the shared pot of staked funds that rewards are paid from.

The flaw becomes reachable once a payout for an asset index has been finalised. Finalised means the payout process for that index has run all the way through and been marked as finished. After that point, the reward accounting for that index behaves differently from the normal staking path, and that difference is the bug.

Exploitation

The steps to execute the attack are as follows.

Step 1: the admin initiates a payout for Asset Index 0

The admin starts the payout process for Asset Index 0. An admin is the account with administrative rights over the contract. This is the ordinary administrative action that opens the four-part sequence; nothing malicious happens here. It is included because the bug only appears after a payout has gone through.

Step 2: the four payout functions run in order and the payout is marked as finished

startPayout, setPayout, doPayout and finishPayout are called in sequential order, and the payout is marked as finished. From this point the asset index has a finalised payout. In plain terms: the contract now has a flag saying "this payout is done", and later code can check that flag and take a different branch.

Step 3: the attacker enters the pool and deposits an arbitrary amount

Once Asset Index 0 is finished, a malicious user enters the pool and deposits some arbitrary amount. The deposit gives the attacker a position in the pool after the payout was finalised.

Step 4: after some time, the attacker calls doPayout

After some amount of time, say a year, the malicious user calls doPayout with the Asset Index 0 and an attacker wallet address as an argument. An argument is a value handed to a function when it is called, so here the attacker chooses both which index to claim against and which wallet should receive the result. The report gives a year only as an example of the waiting time.

Step 5: the reward is allocated without a matching debt

Despite the fact that the malicious user has not made any payment, the user's reward is calculated in the user.rewardAmount variable, but user.rewardDebt is still 0. The system therefore cannot tell that the reward has already been allocated.

In other words, because the asset index had a finalised payout, user.rewardAmount increased without a corresponding increase in user.rewardDebt. Because the value of any unset variable in Solidity is 0, the attacker now has more rewards than they should be entitled to. Solidity is the programming language smart contracts are commonly written in, and in Solidity a variable that has never been assigned a value starts at 0 rather than being empty or undefined. So a debt that was never written looks exactly like a debt of zero, which reads as "nothing has been paid out yet".

The normal staking process generates a reward figure stored in user.rewardAmount, and the final payout should result from the subtraction user.rewardAmount - user.rewardDebt, but that subtraction does not properly occur because user.rewardDebt is mistakenly at 0. Going back to the coffee card: the card says you earned ten free coffees, the "already collected" box was never filled in, so the shop hands over all ten even though some were already taken.

The exploit cannot simply be run repeatedly: the bug depends on how much reward accumulates from staking and on what percentage of the pool is owned at the time an attacker decides to execute an attack. In other words, it is not an unlimited money printer; the size of the gain depends on the state of the pool when the claim is made.

Root cause

The mistake is a logic error in the reward accounting. The line that updates the reward debt already existed in the code, but it was not activated at the right point in the logic flow. When a payout for an asset index had been finalised, doPayout increased user.rewardAmount while user.rewardDebt was still 0. The subtraction that is supposed to net the two values therefore had nothing to subtract, and the attacker's claim was not reduced by what had already been allocated.

A useful comparison is a checklist where one box is meant to be ticked before the next step. The box exists on the form, but it sits below the step that uses it, so it is always empty when it matters.

Impact

A malicious user could claim an unearned share of the rewards generated by staking activity, taking rewards for staking they never did. Approximately 300 million Tidal tokens were locked in the staking contract at the time. Because the trigger condition requires multiple requirements to be met during a claim and payout process, it is unclear how much could have been stolen with additional claims. The exploit also depends on how much reward accumulates from staking and on the percentage of the pool owned at the moment of the attack, so it cannot simply be run repeatedly.

Fix

The fix was already present in the code itself but not activated at the right point in the logic flow. The Tidal team duplicated the line

Solidity
user.rewardDebt = user.amount.mul(poolInfo.accRewardPerShare).div(UNIT_PER_SHARE);

and moved it up so that it is included in the if statement if (payoutInfo[assetIndex_][payoutId].finished). The reward debt amount is now updated after payout, which ensures that it does not remain 0. With the debt properly updated, a malicious user cannot take rewards generated from staking that they are not entitled to.

Line by line, in plain words:

  • user.rewardDebt = ... sets the "already accounted for" figure for the user. This is the box on the coffee card that was previously left empty.
  • user.amount is the amount the user has staked, the size of their position.
  • .mul(poolInfo.accRewardPerShare) multiplies that amount by the reward accumulated per unit of stake in the pool. mul is short for multiply.
  • .div(UNIT_PER_SHARE) divides by the size of one share unit, so the result is expressed in the right scale. div is short for divide.
  • The whole line therefore recalculates the user's debt from their stake and the pool's accumulated reward, and stores it.
  • if (payoutInfo[assetIndex_][payoutId].finished) is a condition that checks whether the payout for this asset index and payout id has been marked finished. Putting the debt update inside this condition means the debt is updated after payout.

Tidal Finance quickly patched the bug and paid out a $25,000 USDT bounty to the whitehat.

Variants to test

These are the same checks a reviewer would run against similar code elsewhere, explained for a newcomer.

  1. Look for reward or dividend accounting that subtracts a per-user debt from a per-user accrued amount. Check whether the debt is written on every path that increases the accrued amount, including paths taken after an epoch, round or payout has been finalised. An epoch or round is just a numbered period in a reward cycle. A positive result is a path where the accrued amount rises while the debt stays at its default value.
  2. Check the ordering of state updates around finalisation flags such as finished. A flag is a stored true/false marker. If a branch guarded by a finalised flag skips the debt update, a user who joins after finalisation can claim against rewards they never contributed to. A positive result is a claim that succeeds for a user whose deposit postdates the finalisation.
  3. Test whether the claim function can be called with an arbitrary asset index and an arbitrary recipient address. If the caller can direct the payout to a wallet of their choosing, the accounting error becomes directly monetisable. A positive result is a payout to an address that never staked in that index.
  4. Vary the timing and size of the deposit relative to the accumulated reward, since the report notes the outcome depends on accumulated rewards and the attacker's share of the pool. A positive result is a claim that scales with accumulated rewards rather than with the attacker's own contribution.

Glossary

  • Admin: the account with administrative rights over a contract, able to trigger actions such as starting a payout.
  • Argument: a value passed to a function when it is called, for example an asset index or a wallet address.
  • Asset index: a numbered slot identifying which asset a payout refers to.
  • Blockchain: a shared, append-only record of transactions maintained by many computers.
  • Bounty: a reward paid by a project for a valid security report.
  • Bug bounty platform: a service where projects publish programs and researchers submit vulnerability reports.
  • Contract (smart contract): a program deployed on a blockchain that can hold funds and run logic.
  • DeFi: decentralised finance, financial applications that run on a blockchain rather than through a bank.
  • Epoch / round: a numbered period in a reward cycle.
  • Finalised: marked as complete, so later code can check a flag and take a different branch.
  • Flag: a stored true/false marker in a contract.
  • Function: a named block of code in a contract that can be triggered.
  • Logic error: a bug where the code runs as written but the rules it enforces are wrong.
  • Pool: the shared pot of staked funds that rewards are paid from.
  • Solidity: the programming language commonly used to write smart contracts, in which unset variables default to 0.
  • Stablecoin: a token designed to stay close in value to a reference currency such as the US dollar.
  • Staking: locking tokens in a contract for a period in return for rewards.
  • Token: a digital unit of value on a blockchain.
  • USDT: a stablecoin designed to track the US dollar.
  • Variable: a named storage slot in a program that holds a value.
  • Whitehat: a security researcher who reports bugs to the owner rather than abusing them.

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.