Skip to content
Business logic Audit finding Intermediate

Pool’s gulped emissions could be lost if a reserve has no supply

The emission distribution logic does not skip reserves with zero supply, so emissions allocated to such reserves are permanently lost and cannot be claimed. An attacker could not directly exploit this, but the protocol loses funds that should have gone to other reserves or future suppliers.

0xAlix2 Follow with aldarion and alexxander

Originally disclosed on Code4rena

Submitted by 0xAlix2, also found by aldarion and alexxander

When a pool is added to the reward zone, some emissions get distributed to it, these emissions could be “claimed” by calling gulp_emissions on that pool, which calls gulp_emissions on the backstop module. The gulped emissions are distributed to different reserves (borrow or debt reserves), according to the reserves set by the pool admin in pool_emissions, by calling set_emissions_config.

On the other hand, after gulping these emissions, users who deposited into these reserves can claim their part by calling claim -> claim_emissions, which ultimately calls update_emission_data and update_user_emissions:

    pub(super) fn update_emission_data(
        e: &Env,
        res_token_id: u32,
        supply: i128,
        supply_scalar: i128,
    ) -> Option<ReserveEmissionData> {
        match storage::get_res_emis_data(e, &res_token_id) {
            Some(mut res_emission_data) => {
                if res_emission_data.last_time >= res_emission_data.expiration
                    || e.ledger().timestamp() == res_emission_data.last_time
                    || res_emission_data.eps == 0
@>                  || supply == 0
                {
                    return Some(res_emission_data);
                }

                // ... snip ...
            }
            None => return None, // no emission exist, no update is required
        }
    }

    fn update_user_emissions(
        e: &Env,
        res_emis_data: &ReserveEmissionData,
        res_token_id: u32,
        supply_scalar: i128,
        user: &Address,
        balance: i128,
        claim: bool,
    ) -> i128 {
        if let Some(user_data) = storage::get_user_emissions(e, user, &res_token_id) {
            if user_data.index != res_emis_data.index || claim {
                let mut accrual = user_data.accrued;
@>              if balance != 0 {
                    // ... snip ...
                }
                return set_user_emissions(e, user, res_token_id, res_emis_data.index, accrual, claim);
            }
            0
        } else if balance == 0 {
            // first time the user registered an action with the asset since emissions were added
            return set_user_emissions(e, user, res_token_id, res_emis_data.index, 0, claim);
        } else {
            // user had tokens before emissions began, they are due any historical emissions
            let to_accrue =
                balance.fixed_mul_floor(e, &res_emis_data.index, &(supply_scalar * SCALAR_7));
            return set_user_emissions(e, user, res_token_id, res_emis_data.index, to_accrue, claim);
        }
    }

As shown, both check if the balance/supply is >0 to go ahead with the claiming, in other words, if no balance/supply nothing happens.

However, this check is not available when gulping and distributing the emissions between reserves, in do_gulp_emissions.

As a result, if a reserve has 0 supply, but it is already added in the pool emissions (and maybe not removed yet), any emissions incoming, that reserve’s part will be lost forever, as it can never be claimed.

Proof of Concept

Add the following test in blend-contracts-v2/pool/src/emissions/manager.rs:

#[test]
fn test_lost_emissions() {
    let e = Env::default();
    e.mock_all_auths();
    e.ledger().set(LedgerInfo {
        timestamp: 1500000000,
        protocol_version: 22,
        sequence_number: 20100,
        network_id: Default::default(),
        base_reserve: 10,
        min_temp_entry_ttl: 10,
        min_persistent_entry_ttl: 10,
        max_entry_ttl: 3110400,
    });

    let pool = testutils::create_pool(&e);
    let bombadil = Address::generate(&e);

    let new_emissions: i128 = 100_0000000;

    let (reserve_config, reserve_data) = testutils::default_reserve_meta();
    let (underlying_0, _) = testutils::create_token_contract(&e, &bombadil);
    testutils::create_reserve(&e, &pool, &underlying_0, &reserve_config, &reserve_data);
    let (underlying_1, _) = testutils::create_token_contract(&e, &bombadil);
    testutils::create_reserve(&e, &pool, &underlying_1, &reserve_config, &reserve_data);

    e.as_contract(&pool, || {
        // only b_supply received emissions
        storage::set_pool_emissions(&e, &map![&e, (0, 0_5000000), (2, 0_5000000)]);

        do_gulp_emissions(&e, new_emissions);

        let mut res_emis_data_0 = storage::get_res_emis_data(&e, &0).unwrap_optimized();
        let mut res_emis_data_2 = storage::get_res_emis_data(&e, &2).unwrap_optimized();

        // R0 and R2 have 0 emission indexes
        assert!(res_emis_data_0.index == res_emis_data_2.index && res_emis_data_0.index == 0);

        // R0 and R2 have the same last_time as now
        assert!(
            res_emis_data_0.last_time == res_emis_data_2.last_time
                && res_emis_data_0.last_time == 1500000000
        );

        // R0 and R2 have the same eps
        assert!(
            res_emis_data_0.eps == res_emis_data_2.eps && res_emis_data_0.eps == 8267195767
        );

        e.ledger()
            .set_timestamp(e.ledger().timestamp() + (24 * 60 * 60));

        // R0 has no more d_supply
        let mut reserve_data_0 = storage::get_res_data(&e, &underlying_0);
        reserve_data_0.d_supply = 0;
        storage::set_res_data(&e, &underlying_0, &reserve_data_0);

        // New emissions are gulped
        do_gulp_emissions(&e, new_emissions);

        res_emis_data_0 = storage::get_res_emis_data(&e, &0).unwrap_optimized();
        res_emis_data_2 = storage::get_res_emis_data(&e, &2).unwrap_optimized();

        // R0 index remains the same, 0
        assert_eq!(res_emis_data_0.index, 0);
        // R2 index is updated
        assert_eq!(res_emis_data_2.index, 9523809523584);

        // Both R0 and R2 last times are updated
        assert!(
            res_emis_data_0.last_time == res_emis_data_2.last_time
                && res_emis_data_0.last_time == 1500086400
        );

        // Both R0 and R2 eps are updated
        //  -> R0 should have its eps updated as it has some d_supply
        //  -> R2 shouldn't have its eps updated as it has no d_supply (all emissions for R2 are lost, as they can't be claimed)
        assert!(
            res_emis_data_0.eps == res_emis_data_2.eps && res_emis_data_0.eps == 15353363558
        );
    });
}

Recommended mitigation steps

If a reserve doesn’t have a supply, skip its distribution, and if no reserves have a supply, block gulping emissions to avoid edge cases.

    fn do_gulp_emissions(e: &Env, new_emissions: i128) {
        // ... snip..

        let mut total_share: i128 = 0;
        for (res_token_id, res_eps_share) in pool_emissions.iter() {
            let reserve_index = res_token_id / 2;
            let res_asset_address = reserve_list.get_unchecked(reserve_index);
            let res_config = storage::get_res_config(e, &res_asset_address);

+           let reserve_data = storage::get_res_data(e, &res_asset_address);
+           let supply = match res_token_id % 2 {
+               0 => reserve_data.d_supply,
+               1 => reserve_data.b_supply,
+               _ => panic_with_error!(e, PoolError::BadRequest),
+           };

-           if res_config.enabled {
+           if res_config.enabled && supply > 0 {
                pool_emis_enabled.push_back((
                    res_config,
                    res_asset_address,
                    res_token_id,
                    res_eps_share,
                ));
                total_share += i128(res_eps_share);
            }
        }
+       if pool_emis_enabled.len() == 0 {
+           panic_with_error!(e, PoolError::BadRequest);
+       }

        // ... snip..
    }

markus_pl10 (Script3) disputed

mootz12 (Script3) commented:

This is not an issue, and the suggested fix would cause more missed emissions than the current situation, in my opinion.

When a reserve has 0 supply, it’s emissions data does not get updated. Once someone adds supply, they will receive all the emissions during the time it had zero supply.

If the reserve has zero supply for long enough where we need to re-write the EPS / expiration, there is nothing we can do at that point to prevent lost emissions, from the time the reserve was set to 0 supply up to the pool gulp_emissions time period.

Either:

  1. The previous emissions are lost where 0 supply existed
  2. The reserve does not receive new emissions

Given there is incentive to keep 1 as short as possible, it makes the most sense to keep the implementation as is, rather than have the reserve miss all new incoming emissions.

LSDan (judge) decreased severity to Low and commented:

This seems highly unlikely, albeit possible. Downgrading to low.

a_kalout (warden) commented:

The sponsor presented a couple of points that I believe aren’t accurate, and I’d like to refute them.

This is not an issue, and the suggested fix would cause more missed emissions than the current situation, in my opinion.

I’m afraid that’s not accurate. If the fix is implemented, any rewards that were for the 0 supply reserve would go to the other >0 reserves. Why? Because total_share won’t account for the 0 supply, resulting in higher new_reserve_emissions, for all non-zero reserves:

let new_reserve_emissions = i128(res_eps_share)
    .fixed_div_floor(e, &total_share, &SCALAR_7)
    .fixed_mul_floor(e, &new_emissions, &SCALAR_7);

When a reserve has 0 supply, it’s emissions data does not get updated. Once someone adds supply, they will receive all the emissions during the time it had zero supply.

This is also not accurate. When emissions come in for 0 supply reserves, the emission data is indeed not updated (emission data index is not updated); however, the EPS is updated, and this is shown in the above PoC. When someone adds some supply to a reserve that has “lost” emissions, his emission index would be set to the current supply’s emission index, in update_user_emissions. Later, when he tries to claim the “lost” emissions, it’ll be calculated as follows:

if user_data.index != res_emis_data.index || claim {
    let mut accrual = user_data.accrued;
    if balance != 0 {
        let delta_index = res_emis_data.index - user_data.index;
        require_nonnegative(e, &delta_index);
        let to_accrue = balance.fixed_mul_floor(
            e,
            &(res_emis_data.index - user_data.index),
            &(supply_scalar * SCALAR_7),
        );
        accrual += to_accrue;
    }
    return set_user_emissions(e, user, res_token_id, res_emis_data.index, accrual, claim);
}

Will user_data.index be != res_emis_data.index? No. So, no, all “lost” emissions are lost forever and can’t be claimed. Well.. if new emissions come in with supply > 0 (after the deposit), only the new ones are claimable.

If the reserve has zero supply for long enough where we need to re-write the EPS / expiration, there is nothing we can do at that point to prevent lost emissions, from the time the reserve was set to 0 supply up to the pool gulp_emissions time period.

I am not sure about the added value of re-writing the EPS/expiration. The recommended mitigation handles this perfectly, even if the reserve doesn’t receive emissions for ages, without any losses.

Regarding the likelihood, first, I’d like to point out that for a specific asset, we have 2 reserves, b (supply) and d (debt). Having a 0 b supply is very unlikely, I agree; however, having a 0 d supply isn’t that rare. It’s pretty normal in lending protocols to have no loans issued for a specific asset.

As a result, I respectfully believe this easily guarantees at least a medium severity. I would appreciate it if the judge could take another look at this.

LSDan (judge) commented:

Thank you for the clarifications. On balance, I agree that the 0 d supply may not be super rare, but this still requires the admin to configure the protocol to send emissions to a pool with no activity, does it not?

a_kalout (warden) commented:

Hmm, not really. The emissions could be set to different reserves, for example, reserve X, which corresponds to a d supply (d or b depends on the key, whether even or odd), and the supply would go down to 0 (repay, withdraw, …), all emissions after that are lost, until the admin removes that from the emissions array.

LSDan (judge) increased severity to Medium and commented:

Ok. I see the point. Reconstituting this as a medium.


The original report as published on Code4rena, by 0xAlix2. 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 emission distribution function does not check whether a reserve has zero supply before allocating emissions to it, unlike the claim functions which skip zero balances.

Impact

Emissions allocated to a reserve with zero supply are permanently lost and cannot be claimed, reducing rewards for other reserves or future suppliers.

What the attacker needed

Reserve with zero supply; emissions configured for that reserve; admin does not remove reserve from emissions

The fix

The code should be fixed to skip distribution to reserves with zero supply and to block gulping if no reserves have supply.

How it was found

  1. Set up a pool with two reserves and configure emissions for both.
  2. Call do_gulp_emissions to distribute initial emissions.
  3. Set the debt supply of one reserve to zero.
  4. Call do_gulp_emissions again with new emissions.
  5. Observe that the zero-supply reserve's emission index remains unchanged while its EPS is updated, meaning its allocated emissions are lost.

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.

In a lending protocol, rewards are shared among reserves based on how much is supplied or borrowed. If a reserve has no supply, the code still gives it a share of rewards, but those rewards can never be claimed because there are no users to claim them. This means those rewards are lost forever instead of being redistributed.

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.

More by 0xAlix2

View all

39 more disclosed reports, best first.

More from Blend V2 Audit + Certora Formal Verification

View all

The newest disclosed reports for this program.

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.