Skip to content
Business logic Audit finding Intermediate

Balance check during MagicSpend validation cannot ensure that MagicSpend has enough balance to cover the requested fund

The balance check during MagicSpend validation only compares the contract's current balance to each withdrawal amount individually, so when multiple user operations are batched, the total withdrawals can exceed the balance. An attacker could cause the second withdrawal to fail, grieving the paymaster's reputation.

doublespending Follow with imare

Originally disclosed on Code4rena

Submitted by doublespending, also found by imare

Balance check during MagicSpend validation cannot ensure that MagicSpend has enough balance to cover the requested fund.

        // Ensure at validation that the contract has enough balance to cover the requested funds.
        // NOTE: This check is necessary to enforce that the contract will be able to transfer the remaining funds
        //       when `postOp()` is called back after the `UserOperation` has been executed.
        if (address(this).balance < withdrawAmount) {
            revert InsufficientBalance(withdrawAmount, address(this).balance);
        }

Proof of Concept

  1. EntryPoint executes userOps by two loops: validation loop and execution loop.

  2. Suppose we have two userOps using MagicSpend:

    • userOp1 with withdrawAmount 100
    • userOp2 with withdrawAmount 150
  3. userOp1 and userOp2 are packed together as UserOperation[] ops and ops will be executed by entryPoint through the handleOps method

  4. Suppose the balance of MagicSpend is 200.

  5. During the validation loop:

    • validatePaymasterUserOp will be called during userOp1 validation and pass for address(this).balance (=200) is larger than withdrawAmount (=100)
    • validatePaymasterUserOp will be called during userOp1 validation and pass for address(this).balance (=200) is larger than withdrawAmount (=150)
        // https://github.com/eth-infinitism/account-abstraction/blob/abff2aca61a8f0934e533d0d352978055fddbd96/contracts/core/EntryPoint.sol#L98C1-L102C10
        for (uint256 i = 0; i < opslen; i++) {
            UserOpInfo memory opInfo = opInfos[i];
            (uint256 validationData, uint256 pmValidationData) = _validatePrepayment(i, ops[i], opInfo);
            _validateAccountAndPaymasterValidationData(i, validationData, pmValidationData, address(0));
        }
  1. During the execution loop:

    • The balance of MagicSpend is 200
    • The request fund of userOp1 and userOp2 is 100+150=250 > 200

        for (uint256 i = 0; i < opslen; i++) {
            collected += _executeUserOp(i, ops[i], opInfos[i]);
        }
  • After executing postOp of userOp1, the balance of MagicSpend is 100.
        // https://github.com/code-423n4/2024-03-coinbase/blob/e0573369b865d47fed778de00a7b6df65ab1744e/src/MagicSpend/MagicSpend.sol#L160C1-L162C10
        if (withdrawable > 0) {
            SafeTransferLib.forceSafeTransferETH(account, withdrawable, SafeTransferLib.GAS_STIPEND_NO_STORAGE_WRITES);
        }
  • When executing postOp of userOp2, MagicSpend does not have enough balance to cover the requested fund (=150) of userOp2 and the execution will fail.
        // https://github.com/code-423n4/2024-03-coinbase/blob/e0573369b865d47fed778de00a7b6df65ab1744e/src/MagicSpend/MagicSpend.sol#L160C1-L162C10
        if (withdrawable > 0) {
            SafeTransferLib.forceSafeTransferETH(account, withdrawable, SafeTransferLib.GAS_STIPEND_NO_STORAGE_WRITES);
        }
  • So, a balance check during MagicSpend validation cannot ensure that MagicSpend has enough balance to cover the requested fund.

        // Ensure at validation that the contract has enough balance to cover the requested funds.
        // NOTE: This check is necessary to enforce that the contract will be able to transfer the remaining funds
        //       when `postOp()` is called back after the `UserOperation` has been executed.
        if (address(this).balance < withdrawAmount) {
            revert InsufficientBalance(withdrawAmount, address(this).balance);
        }

Recommended Mitigation Steps

Use a state instead of address(this).balance to record the remaining balance.

        if (remain < withdrawAmount) {
            revert InsufficientBalance(withdrawAmount, address(this).balance);
        }
        remain -= withdrawAmount;

raymondfam (lookout) commented:

This would happen only when the entrypoint batches the transactions. Additionally, this is kind of related to the known issue from the readme: When acting as a paymaster, EntryPoint will debit MagicSpend slightly more than actualGasCost, meaning what is withheld on a gas-paying withdrawal will not cover 100% of MagicSpend’s balance decrease in the EntryPoint.

wilsoncusack (Coinbase) confirmed and commented:

Ah right I feel like we discussed this @xenoliss and then perhaps forgot in a later conversation. The only way to avoid this would be to have validation keep some tally of all the expected coming withdraws.

3docSec (judge) commented:

To be fair, one could argue that the bundlers should simulate the execution of their bundles before submission to avoid reverts; however, this is a valid way of grieving the reputation of the MagicSpend contract.

wilsoncusack (Coinbase) commented:

@3docSec - it is correct that the bundler would be expected to see this and revert the whole bundle. However, the point is valid that the guard is not fully satisfactory as it is written. It should probably be removed or fixed.

Coinbase mitigated:

This issue is complex to address. The warden suggested adding a variable to track in flight withdraws, and we pursued this. However, we realized that bundlers penalize paymasters when the UserOp behaves differently when simulated in isolation vs. in the bundle, and this would not fix this. Instead, we give the owner a tool to address this probabilistically: the owner can set a maxWithdrawDenominator and we enforce that native asset withdraws must be <= address(this).balance / maxWithdrawDenominator. For example, if maxWithdrawDenominator is set to 20, it would take 20 native asset withdraws (each withdrawing max allowed) + 1 native asset withdraw in the same transaction to cause a revert. It is of course known that this doesn’t entirely solve the issue, and the efficacy depends the value chosen and usage. (PR here)

Status: Mitigation confirmed. Full details in reports from imare and McToady.


The original report as published on Code4rena, by doublespending. 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

The validation check uses the contract's current balance without accounting for other withdrawals in the same batch, so it does not reserve funds for pending withdrawals.

Impact

The second withdrawal fails, which could grief the reputation of the MagicSpend contract; bundlers are expected to simulate and revert the whole bundle, but the guard is not fully satisfactory.

What the attacker needed

EntryPoint batches multiple userOps; Multiple userOps use MagicSpend; Total withdrawals exceed MagicSpend balance

The fix

The issue was mitigated by adding a maxWithdrawDenominator set by the owner, enforcing that native asset withdrawals are at most address(this).balance divided by that denominator, though this does not entirely solve the issue.

How it was found

  1. EntryPoint executes userOps in two loops: validation loop and execution loop.
  2. Two userOps use MagicSpend with withdrawAmounts 100 and 150, and MagicSpend balance is 200.
  3. During validation, both userOps pass because balance (200) is greater than each individual withdrawAmount.
  4. During execution, after userOp1's postOp, balance becomes 100, which is less than userOp2's withdrawAmount (150).
  5. userOp2's postOp fails because MagicSpend lacks sufficient balance.

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.

MagicSpend is a paymaster that pays gas for users. It checks it has enough balance before approving each request, but if two requests are processed together, it approves both based on the same starting balance, then runs out of money when paying the second one. This makes the second payment fail.

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 from Smart Wallet

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.