Skip to content
DoS Audit finding Intermediate

Because of rounding issues, users may not be able to withdraw airdrop tokens if their claim has been adjust()'ed upwards

A rounding error in the conversion between token amounts and voting shares can cause a user's claim to revert when they try to withdraw after an upward adjustment. An attacker could not directly exploit this, but the bug prevents legitimate users from claiming their tokens.

jkoppel Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-06-tokensoft-judging/issues/56

Found by

jkoppel

Summary

In order for a user to withdraw their claim, they must have enough voting tokens. However, because of rounding issues, if their voting shares are granted in multiple stages, namely by the owner adjust()-ing their share upwards, they will not have enough.

Vulnerability Detail

  1. Owner creates airdrop and grants a user a claim of 1000 tokens. The voting factor is 5, and the fractionDenominator is set to 10000.
  2. User initializes their distribution record. They are minted 1000*5/10000 = 0 voting tokens.
  3. Owner adjusts everyone's claim up to 1000. Each user is minted another 1000*5/10000=0 voting tokens.
  4. User fully vests
  5. User cannot withdraw anything because, in order to withdraw, they must burn 2000*5/10000= 1 voting token.

Impact

Unless all grants and positive adjust()'s are for exact multiples of fractionDenominator, users will be prevented from withdrawing after an upwards adjustment.

Note that many comments give example values of 10000 for fraction denominator and 15000 for voteFactor. Since the intention is to use voteFactor's which are not multiples of fractionDenonimator, rounding issues will occur.

Code Snippet

Rounding in tokensToVotes

https://github.com/sherlock-audit/2023-06-tokensoft/blob/main/contracts/contracts/claim/abstract/AdvancedDistributor.sol#L73

Solidity
  function tokensToVotes(uint256 tokenAmount) private view returns (uint256) {
    return (tokenAmount * voteFactor) / fractionDenominator;
  }

_inititializeDistributionRecord and adjust() both use tokensToVotes to mint

https://github.com/sherlock-audit/2023-06-tokensoft/blob/main/contracts/contracts/claim/abstract/AdvancedDistributor.sol#L84C1-L85C1

https://github.com/sherlock-audit/2023-06-tokensoft/blob/main/contracts/contracts/claim/abstract/AdvancedDistributor.sol#L126

tokensToVotes is again used to burn when executing a claim

https://github.com/sherlock-audit/2023-06-tokensoft/blob/main/contracts/contracts/claim/abstract/AdvancedDistributor.sol#L87

Solidity

  function _executeClaim(
    address beneficiary,
    uint256 totalAmount
  ) internal virtual override returns (uint256 _claimed) {
    _claimed = super._executeClaim(beneficiary, totalAmount);

    // reduce voting power through ERC20Votes extension
    _burn(beneficiary, tokensToVotes(_claimed));
  }

Tool used

Manual Review

Recommendation

Base votes on share of unclaimed tokens and not on a separate token.

Discussion

cr-walker

Good catch.

Solution: we'll burn the minimum of the expected quantity and current balance to get around these rounding issues.

cr-walker

Fixed by https://github.com/sherlock-audit/2023-06-tokensoft-judging/issues/56

dot-pengun

Escalate

This issue occurs when the admin sets the voteFactor to very low or which are not multiples. In several test files that the voteFactor is set to 2n * 10n ** 18n, 2n * 10n ** 4n, etc. (this is also mentioned in the issue above), so I believe the issue is essentially an admin error.

Also resolution in #41 resolves this issue.(https://github.com/SoftDAO/contracts/pull/9/commits/0cd8ff408632eabfc363da43255ffd4d2a8bd73e)

sherlock-admin2

Escalate

This issue occurs when the admin sets the voteFactor to very low or which are not multiples. In several test files that the voteFactor is set to 2n * 10n ** 18n, 2n * 10n ** 4n, etc. (this is also mentioned in the issue above), so I believe the issue is essentially an admin error.

Also resolution in #41 resolves this issue.(https://github.com/SoftDAO/contracts/pull/9/commits/0cd8ff408632eabfc363da43255ffd4d2a8bd73e)

You've created a valid escalation!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

jkoppel

dot-penguin points out some interesting information about the test values. But, as I'll explain below, I think relying on such information is at odds with the purpose of this entire contest.

While the example scenario used a low number, the issue appears with any value of voteFactor which is not an exact multiple of fractionDenominator. Comments suggest in multiple places (e.g.: https://github.com/sherlock-audit/2023-06-tokensoft/blob/main/contracts/contracts/claim/TrancheVestingSale_2_0.sol#L31 ) the values of 15000 for voteFactor and 10000 for fractionDenominator, which would exhibit this issue.

If you call this invalid admin error, then any bug that occurs in some settings but not all is also admin error. This bug is present for the overwhelming majority of possible settings of voteFactor, and there is nothing to indicate that only multiples should be used.

The purpose of audits is to catch bugs not already found. Saying "the tests didn't use values that found the bug" is not a reason for non-validity.

It is irrelevant that there is a larger design change that fixes both this and other issues.

dot-pengun

I agree that this is a vulnerability, I just think the definition of admin input validation in sherlock's docs is vague. I'm not sure if input validation is just for rug pulls or if it also includes things that can harm the protocol like this.

Admin Input/call validation: Protocol admin is considered to be trusted in most cases, hence issues where Admin incorrectly enters an input parameter. Example: Make sure interestPerMin > 1 ether as it is an important parameter. This is not a valid issue.

jkoppel

As I mentioned in the Discord, this is a contest where, for every single issue reported, I can see an argument by which that issue should be invalid. (For example, because of the Sweepable functionality, admin can manually fix any issue of funds getting stuck.) I agree that Sherlock's docs should be more clear about this --- and they have become better in my moderate amount of time on the platform. But in the past, errors like this have been deemed valid.

I have a software verification background, and I think there's a pretty simple definition that can apply here:

  1. Each function makes a promise: if you pass in inputs that satisfy its precondition, then some desired outcome will occur
  2. If a user calls a function in a way that doesn't satisfy its preconditions, nothing bad should happen
  3. If an admin calls a function in a way that doesn't satisfy its preconditions, all bets are off
  4. If an admin calls a function in a way that does satisfy its preconditions, no unintended bad effects should occur.

So the relevant question is: is "voteFactor must be a perfect multiple of fractionDenominator" in the communicated precondition for the various constructors? I think it's hard to argue yes, given that the example value violates that property.

Czar102

Please note that it's tokenAmount * voteFactor that needs to be a multiply of fractionDenominator. Hence, the values provided in the comment, i.e. voteFactor is 15000, it does not cause the bug right away. The admin just needs to set all claim amounts to an even number, then voteFactor * tokenAmount will always be a multiple of 30000 at the end of the vesting, making it divisible by the fractionDenominator. Auditors were free to assume that nothing is broken, as long as the admin inputs all pairs (tokenAmount, voteFactor) (voteFactor is constant), which is a question of admin input validation and comments do not give any example suggesting the admin could want to input invalid values here.

jkoppel

Consider a TranchVestingSale or PriceTierVestingSale airdrop where users control the initial amount granted.

User buys 1337 tokens.

Admin calls adjust(user, 5000).

But this causes the bug in question.

Actually, the admin should have called adjust(user, 5000 - (getDistributionRecord(user).total % 2)).

If calling adjust(user, 5000) is indeed considered an invalid input despite there being nothing in the docs or comments suggesting that calling adjust(user, 5000) may cause trapped funds, then this would be indeed an invalid issue.

But I suspect that most would not be willing to bite that bullet.

dot-pengun

I think this issue is not fundamentally caused by voteFactor not being a multiple of fractionDenominator, but rather by poor handling on adjust. In other words, it happens because initializeDistributionRecord is not performed correctly after the adjustment. Therefore, the protocol team fixed #41, and the revised commit shows that the issue is gone.

Czar102

If the user buys 1337 tokens, they get 2005 votes. Adjusting by 5000 should give the user 7500 more votes. Hence, the user has 7505, which is exactly what they need to withdraw all the amount. If the adjusted amount was positive and odd, the argument would make sense. Nice find.

The admin can still call adjust(user, -1), adjust(user, -1), adjust(user, 2) to resolve this. Hence, it is only gas that the admin loses, there is no fund loss or irreversible state change.

jkoppel

Thanks for working out my example more @Czar102. Yes, I did screw up. The argument to adjust() needs to be odd. So I can amend my statement: one would have to bite the bullet that adjust(user, amountToGiveToManyUsers / n) is invalid input, and so is adjust(user, someBaseAmount * 2 / 3), with the correct version being adjust(user, amountToGiveToManyUsers / n - (getDistributionRecord(user).total % 2)). This is not quite as large as a bullet to bite, but still a huge toothache if one does.

Re: @dot-pengun Yes, the logic in the fix to #41 is a good approach. adjust() is completely independent of initializeDistributionRecord(), so one solution is to apply the same fix here.

It is true that the admin can work around the issue if they understand it. But that argument also applies to literally every other issue in this contest.

KuTuGu

Escalate I want to emphasize that the precision of ERC20 tokens and votes is 18 decimals. The warden is wrong in the example mentioned above, the true value should be 1000e18 * 5 / 10000, not 1000 * 5 / 10000. For the dust value of 1000, tokensToVotes are 0, but this is meaningless because the tokenAmount itself is dust. In addition, if tokenAmount = 1.11...1e18, although there is a precision error in division, the error is only 1wei, which can be ignored. So I think the issue is low.

sherlock-admin2

Escalate I want to emphasize that the precision of ERC20 tokens and votes is 18 decimals. The warden is wrong in the example mentioned above, the true value should be 1000e18 * 5 / 10000, not 1000 * 5 / 10000. For the dust value of 1000, tokensToVotes are 0, but this is meaningless because the tokenAmount itself is dust. In addition, if tokenAmount = 1.11...1e18, although there is a precision error in division, the error is only 1wei, which can be ignored. So I think the issue is low.

The escalation could not be created because you are not exceeding the escalation threshold.

You can view the required number of additional valid issues/judging contest payouts in your Profile page, in the Sherlock webapp.

jkoppel

@KuTuGu What is the true value you are referring to?

I explained why calling adjust(user, someBaseAmount * 2 / 3) on a fully-vested user would cause a user to become unable to withdraw 100% of their funds. Can you find some flaw in this reasoning? Are you saying that 100% of a user's claimable token is "dust?"

KuTuGu

I'm saying that tokens have 1e18 decimals, 1000 tokens are 1000e18, not 1000, it doesn't have a result of 0 when calculating tokensToVotes, and since fractionDenominator is a multiple of 10, there is no precision error here

jkoppel

Sorry, I'm confused. I don't understand how that is relevant to the issue.

Let's be super-specific. Here's a Chisel session mimicking the tracking of vote tokens:

  1. User gets x=1000e18 / 3 tokens

uint256 x = 1000e18/3;

  1. User gets z=x*voteFactor/fractionDenominator voting tokens

uint256 z = x * 15000 / 10000;

  1. Admin calls adjust adjust(user, 1000e18/3)

x += 1000e18 / 3; z += (1000e18 / 3) * 15000 / 10000;

  1. User fully vests

  2. User tries to claim, burning all vote tokens

z -= x*votingFactor / fractionDenominator;

Traces:
  [3204] 0xBd770416a3345F91E4B34576cb804a576fa48EB1::run()
    └─ ← "Arithmetic over/underflow"

Are you saying this is not the math used to mint and burn voting shares, or that an arithmetic underflow when withdrawing is not a problem?

KuTuGu

As I said before, there is an error in division, but it is only 1wei and there is no significant loss

Solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../contracts/claim/BasicDistributor.sol";

contract MToken is ERC20 {
    constructor() ERC20("", "") {}
}

contract CounterTest is Test {
    MToken public token;
    BasicDistributor public distributor;
    uint256 constant amount = 1000 ether;
    address constant user = address(0xdead);

    function setUp() public {
        address[] memory recipients = new address[](1);
        uint256[] memory amounts = new uint256[](1);
        recipients[0] = user;
        amounts[0] = amount / 3;
        token = new MToken();
        distributor = new BasicDistributor(token, amount / 3, "", 1.5e18, recipients, amounts);
        deal(address(token), address(distributor), amount);
    }

    function testRoundIssue() public {
        assertEq(distributor.getClaimableAmount(user), amount / 3);
        assertEq(token.balanceOf(user), 0);
        distributor.adjust(user, int256(amount / 3 * 2));
        assertEq(distributor.getClaimableAmount(user), amount / 3 * 3);
        assertEq(token.balanceOf(user), 0);
        distributor.claim(user);
        assertEq(distributor.getClaimableAmount(user), 0);
        assertEq(token.balanceOf(user), amount / 3 * 3);
        assertEq(amount * 3 / 3 - token.balanceOf(user), 1);
    }
}

jkoppel

@KuTuGu Cool! That test behaves exactly as I expect! Now let's try something actually related to this issue.

For a little bit of context, this issue:

  1. Causes claim attempts to revert
  2. Requires that tokenAmount*votingFactor is not perfectly divisible by fractionDenominator.
  3. Involves a rounding error in voting tokens, not the claimed token

The scenario I wrote above:

  1. Uses a votingFactor of 15000, which is the one suggested by documentation
  2. Requires distributing an odd number of tokens to the user, and then adjusting by an odd number of tokens.

And this test:

  1. Does not look at voting tokens
  2. Does not check anything related to reversion
  3. Uses a votingFactor 10^14 times higher than the one proposed, one which is a perfect multiple of votingFactor
  4. Does not adjust by an odd number of tokens

It turns out that, if you run a test completely unrelated to the proposed issue, it will fail to exhibit the issue!

But it did successfully show that (amount/3)+(amount/3 * 2) == amount-1. There are also simpler tests of this.

Now let's modify it to actually relate to the issue:

Solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../contracts/claim/BasicDistributor.sol";

contract MToken is ERC20 {
    constructor() ERC20("", "") {}
}

contract CounterTest is Test {
    MToken public token;
    BasicDistributor public distributor;
    uint256 constant amount = 1000 ether;
    address constant user = address(0xdead);

    function setUp() public {
        address[] memory recipients = new address[](1);
        uint256[] memory amounts = new uint256[](1);
        recipients[0] = user;
        amounts[0] = amount / 3;
        token = new MToken();
        distributor = new BasicDistributor(token, amount / 3, "", 15000, recipients, amounts);
        deal(address(token), address(distributor), amount);
    }

    function testRoundIssue() public {
        distributor.adjust(user, int256(amount / 3));
        distributor.claim(user);
    }
}

Result:


Running 1 test for contracts/contracts/ContractTest.sol:CounterTest
[FAIL. Reason: ERC20: burn amount exceeds balance] testRoundIssue() (gas: 77926)
Test result: FAILED. 0 passed; 1 failed; finished in 2.63ms

Failing tests:
Encountered 1 failing test in contracts/contracts/ContractTest.sol:CounterTest
[FAIL. Reason: ERC20: burn amount exceeds balance] testRoundIssue() (gas: 77926)

In contrast, if you adjust by 1+amount/3 instead, then it does not revert.

So, as you can see, a very innocuous call to adjust renders the user unable to claim anything. This issue is valid.

KuTuGu

Sorry I confused the hard-coded parameter fractionDenominator for ContinuousVesting and BasicDistributor. You are correct, each adjust may produce 1wei error, resulting in failure to withdraw money.

hrishibhat

@jkoppel @dot-pengun Firstly thank you for the points around admin input error. I can see how the rule can be ambiguous at times, and an improvement on the same is pending.

About this issue, to summarize this seems to be creating temporary dos for user claims which can correct by the owner using adjust?

jkoppel

No, that's not an accurate summary.

The summary is that a very innocuous call to adjust creates a DOS for user claims, period.

The admin can fix this problem by sweeping the tokens back and distributing them manually, or by a very unintuitive sequence of admin calls which amounts to using another exploit to undo this bug.

Note that all other DOS vulnerabilities can be worked around in a similar manner: #55, #141, and #14. #141 in particular has a very easy workaround: instead of calling setTotal(newTotal), call setTotal(claimed); setTotal(newTotal)

Admins are also able to work around the issue for #188, #143, #130, and #41.

SilentYuki

In contrast, if you adjust by 1+amount/3 instead, then it does not revert.

As mentioned the rounding error can be prevented and depends mainly on the inputted value by the admin.

So, as you can see, a very innocuous call to adjust renders the user unable to claim anything. This issue is valid.

Even if admin makes false call to adjust and rounding error occurs, the DoS is only temporarily as admin can re-adjust to fix the issue.

jkoppel

Even if admin makes false call to adjust and rounding error occurs, the DoS is only temporarily as admin can re-adjust to fix the issue.

Yes, and similar is true of #55, #141, #14, #188, #143, #130, and #41. I don't see a way to mark this invalid without also marking all 7 of those other issues as invalid. Further, in this case, the proposed workaround using adjust() only works by exploiting buggy logic in the code.

hrishibhat

@jkoppel thanks for the context. So the way I see it, there is an error this would be an issue if voteFactor was set too low or not a multiple of fractionDenominator, and this value is not something that can be changed to fix this issue. correct? also there is no way to know what the best voteFactor would be as it could vary from case to case.

jkoppel

Correct, this is an issue if voteFactor is not an exact multiple of fractionDenominator. The protocol clearly intends to allow many different values for voteFactor. The docs suggest a value of 15000 for voteFactor and 10000 for fractionDenominator, which does enable the vulnerability.

hrishibhat

Result: Medium Unique Considering this issue a valid medium based on the comments above: https://github.com/sherlock-audit/2023-06-tokensoft-judging/issues/56#issuecomment-1684238186

sherlock-admin2

Escalations have been resolved successfully!

Escalation status:

cr-walker

@sherlock-admin - here's the fix: https://github.com/SoftDAO/contracts/pull/11

maarcweiss

Fixed by wrapping the logic of the fix in #41 in the _reconcileVotingPower function and preventing rounding issues to fix that the user's were not be able to withdraw

The original report as published on Sherlock, by jkoppel. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

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 integer division in tokensToVotes truncates, so minting and burning voting tokens can round differently when a claim is adjusted upwards, leading to insufficient voting tokens to burn on withdrawal.

What the attacker needed

VoteFactor not a multiple of fractionDenominator; claim adjusted upwards by owner

The fix

The fix was to burn the minimum of the expected voting token quantity and the current balance to avoid rounding issues.

How it was found

  1. Owner creates an airdrop and grants a user a claim of 1000 tokens with voteFactor 5 and fractionDenominator 10000.
  2. User initializes their distribution record and is minted 0 voting tokens due to rounding.
  3. Owner adjusts the user's claim upwards by another 1000 tokens, minting another 0 voting tokens.
  4. User fully vests and attempts to withdraw, but the contract tries to burn 1 voting token, which the user does not have, causing a 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.

This is a smart contract bug where the code calculates voting power by multiplying a token amount by a factor and then dividing. Because division in programming often drops remainders, small rounding errors can occur. If the numbers don't divide evenly, a user might end up with slightly less voting power than needed to withdraw their tokens, causing the withdrawal to fail.

What is DoS?

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.

More by jkoppel

View all

4 more disclosed reports, best first.

More from Tokensoft

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.