Skip to content
Business logic Audit finding Advanced

The formula used in ````SafeCall.callWithMinGas()```` is wrong

The gas calculation in SafeCall.callWithMinGas() did not account for all dynamic gas costs of the CALL opcode, so the sub-contract could receive less than the specified minimum gas. This could cause withdrawal transactions to fail unexpectedly due to out-of-gas, potentially leading to loss of funds.

KingNFT Follow with ShadowForce

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-03-optimism-judging/issues/40

Found by

KingNFT, ShadowForce

Summary

The formula used in SafeCall.callWithMinGas() is not fully complying with EIP-150 and EIP-2929, the actual gas received by the sub-contract can be less than the required _minGas. Withdrawal transactions can be finalized with less than specified gas limit, may lead to loss of funds.

Vulnerability Detail

Solidity
File: contracts\libraries\SafeCall.sol
048:     function callWithMinGas(
049:         address _target,
050:         uint256 _minGas,
051:         uint256 _value,
052:         bytes memory _calldata
053:     ) internal returns (bool) {
054:         bool _success;
055:         assembly {
056:             // Assertion: gasleft() >= ((_minGas + 200) * 64) / 63
057:             //
058:             // Because EIP-150 ensures that, a maximum of 63/64ths of the remaining gas in the call
059:             // frame may be passed to a subcontext, we need to ensure that the gas will not be
060:             // truncated to hold this function's invariant: "If a call is performed by
061:             // `callWithMinGas`, it must receive at least the specified minimum gas limit." In
062:             // addition, exactly 51 gas is consumed between the below `GAS` opcode and the `CALL`
063:             // opcode, so it is factored in with some extra room for error.
064:             if lt(gas(), div(mul(64, add(_minGas, 200)), 63)) {
065:                 // Store the "Error(string)" selector in scratch space.
066:                 mstore(0, 0x08c379a0)
067:                 // Store the pointer to the string length in scratch space.
068:                 mstore(32, 32)
069:                 // Store the string.
070:                 //
071:                 // SAFETY:
072:                 // - We pad the beginning of the string with two zero bytes as well as the
073:                 // length (24) to ensure that we override the free memory pointer at offset
074:                 // 0x40. This is necessary because the free memory pointer is likely to
075:                 // be greater than 1 byte when this function is called, but it is incredibly
076:                 // unlikely that it will be greater than 3 bytes. As for the data within
077:                 // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset.
078:                 // - It's fine to clobber the free memory pointer, we're reverting.
079:                 mstore(88, 0x0000185361666543616c6c3a204e6f7420656e6f75676820676173)
080: 
081:                 // Revert with 'Error("SafeCall: Not enough gas")'
082:                 revert(28, 100)
083:             }
084: 
085:             // The call will be supplied at least (((_minGas + 200) * 64) / 63) - 49 gas due to the
086:             // above assertion. This ensures that, in all circumstances, the call will
087:             // receive at least the minimum amount of gas specified.
088:             // We can prove this property by solving the inequalities:
089:             // ((((_minGas + 200) * 64) / 63) - 49) >= _minGas
090:             // ((((_minGas + 200) * 64) / 63) - 51) * (63 / 64) >= _minGas
091:             // Both inequalities hold true for all possible values of `_minGas`.
092:             _success := call(
093:                 gas(), // gas
094:                 _target, // recipient
095:                 _value, // ether value
096:                 add(_calldata, 32), // inloc
097:                 mload(_calldata), // inlen
098:                 0x00, // outloc
099:                 0x00 // outlen
100:             )
101:         }
102:         return _success;
103:     }

The current formula used in SafeCall.callWithMinGas() involves two issues.

Firstly, the 63/64 rule is not the whole story of EIP-150 for the CALL opcode, let's take a look at the implementation of EIP-150, a base gas is subtracted before applying 63/64 rule.

https://github.com/ethereum/go-ethereum/blob/2adce0b06640aa665706d014a92cd06f0720dcab/core/vm/gas.go#L37

Go
func callGas(isEip150 bool, availableGas, base uint64, callCost *uint256.Int) (uint64, error) {
	if isEip150 {
		availableGas = availableGas - base
		gas := availableGas - availableGas/64
		// If the bit length exceeds 64 bit we know that the newly calculated "gas" for EIP150
		// is smaller than the requested amount. Therefore we return the new gas instead
		// of returning an error.
		if !callCost.IsUint64() || gas < callCost.Uint64() {
			return gas, nil
		}
	}
	if !callCost.IsUint64() {
		return 0, ErrGasUintOverflow
	}

	return callCost.Uint64(), nil
}

The base gas is calculated in gasCall() of gas_table.go, which is subject to

Solidity
(1) L370~L376: call to a new account
(2) L377~L379: call with non zero value
(3) L380~L383: memory expansion

The (1) and (3) are irrelevant in this case, but (2) should be taken into account.

https://github.com/ethereum/go-ethereum/blob/2adce0b06640aa665706d014a92cd06f0720dcab/core/vm/gas_table.go#L364

Go
File: core\vm\gas_table.go
364: func gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
365: 	var (
366: 		gas            uint64
367: 		transfersValue = !stack.Back(2).IsZero()
368: 		address        = common.Address(stack.Back(1).Bytes20())
369: 	)
370: 	if evm.chainRules.IsEIP158 {
371: 		if transfersValue && evm.StateDB.Empty(address) {
372: 			gas += params.CallNewAccountGas
373: 		}
374: 	} else if !evm.StateDB.Exist(address) {
375: 		gas += params.CallNewAccountGas
376: 	}
377: 	if transfersValue {
378: 		gas += params.CallValueTransferGas
379: 	}
380: 	memoryGas, err := memoryGasCost(mem, memorySize)
381: 	if err != nil {
382: 		return 0, err
383: 	}
384: 	var overflow bool
385: 	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
386: 		return 0, ErrGasUintOverflow
387: 	}
388: 
389: 	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
390: 	if err != nil {
391: 		return 0, err
392: 	}
393: 	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
394: 		return 0, ErrGasUintOverflow
395: 	}
396: 	return gas, nil
397: }

The raw extra gas for transferring value is

Solidity
params.CallValueTransferGas - params.CallStipend * 64 / 63 = 9000 - 2300 * 64 / 63 = 6664

releated LOCs: https://github.com/ethereum/go-ethereum/blob/2adce0b06640aa665706d014a92cd06f0720dcab/params/protocol_params.go#L30 https://github.com/ethereum/go-ethereum/blob/2adce0b06640aa665706d014a92cd06f0720dcab/params/protocol_params.go#L37 https://github.com/ethereum/go-ethereum/blob/2adce0b06640aa665706d014a92cd06f0720dcab/core/vm/instructions.go#L681-L684

Secondly, EIP-2929 also affects the gas cost of CALL opcode.

Let's look at the implementation of EIP-2929 on CALL opcode, the ColdAccountAccessCostEIP2929 is 2600 and the WarmStorageReadCostEIP2929 is 100, they are subtracted before applying 63/64 rule too. https://github.com/ethereum/go-ethereum/blob/2adce0b06640aa665706d014a92cd06f0720dcab/core/vm/operations_acl.go#L160

Go
File: core\vm\operations_acl.go
195: 	gasCallEIP2929         = makeCallVariantGasCallEIP2929(gasCall)

File: core\vm\operations_acl.go
160: func makeCallVariantGasCallEIP2929(oldCalculator gasFunc) gasFunc {
161: 	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
162: 		addr := common.Address(stack.Back(1).Bytes20())
163: 		// Check slot presence in the access list
164: 		warmAccess := evm.StateDB.AddressInAccessList(addr)
165: 		// The WarmStorageReadCostEIP2929 (100) is already deducted in the form of a constant cost, so
166: 		// the cost to charge for cold access, if any, is Cold - Warm
167: 		coldCost := params.ColdAccountAccessCostEIP2929 - params.WarmStorageReadCostEIP2929
168: 		if !warmAccess {
169: 			evm.StateDB.AddAddressToAccessList(addr)
170: 			// Charge the remaining difference here already, to correctly calculate available
171: 			// gas for call
172: 			if !contract.UseGas(coldCost) {
173: 				return 0, ErrOutOfGas
174: 			}
175: 		}
176: 		// Now call the old calculator, which takes into account
177: 		// - create new account
178: 		// - transfer value
179: 		// - memory expansion
180: 		// - 63/64ths rule
181: 		gas, err := oldCalculator(evm, contract, stack, mem, memorySize)
182: 		if warmAccess || err != nil {
183: 			return gas, err
184: 		}
185: 		// In case of a cold access, we temporarily add the cold charge back, and also
186: 		// add it to the returned gas. By adding it to the return, it will be charged
187: 		// outside of this function, as part of the dynamic gas, and that will make it
188: 		// also become correctly reported to tracers.
189: 		contract.Gas += coldCost
190: 		return gas + coldCost, nil
191: 	}
192: }

Here is a test script to show the impact of the two aspects mentioned above

Solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;

import "forge-std/Test.sol";
import "forge-std/console.sol";

library SafeCall {
    function callWithMinGas(
        address _target,
        uint256 _minGas,
        uint256 _value,
        bytes memory _calldata
    ) internal returns (bool) {
        bool _success;
        uint256 gasSent;
        assembly {
            // Assertion: gasleft() >= ((_minGas + 200) * 64) / 63
            //
            // Because EIP-150 ensures that, a maximum of 63/64ths of the remaining gas in the call
            // frame may be passed to a subcontext, we need to ensure that the gas will not be
            // truncated to hold this function's invariant: "If a call is performed by
            // `callWithMinGas`, it must receive at least the specified minimum gas limit." In
            // addition, exactly 51 gas is consumed between the below `GAS` opcode and the `CALL`
            // opcode, so it is factored in with some extra room for error.
            if lt(gas(), div(mul(64, add(_minGas, 200)), 63)) {
                // Store the "Error(string)" selector in scratch space.
                mstore(0, 0x08c379a0)
                // Store the pointer to the string length in scratch space.
                mstore(32, 32)
                // Store the string.
                //
                // SAFETY:
                // - We pad the beginning of the string with two zero bytes as well as the
                // length (24) to ensure that we override the free memory pointer at offset
                // 0x40. This is necessary because the free memory pointer is likely to
                // be greater than 1 byte when this function is called, but it is incredibly
                // unlikely that it will be greater than 3 bytes. As for the data within
                // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset.
                // - It's fine to clobber the free memory pointer, we're reverting.
                mstore(
                    88,
                    0x0000185361666543616c6c3a204e6f7420656e6f75676820676173
                )

                // Revert with 'Error("SafeCall: Not enough gas")'
                revert(28, 100)
            }

            // The call will be supplied at least (((_minGas + 200) * 64) / 63) - 49 gas due to the
            // above assertion. This ensures that, in all circumstances, the call will
            // receive at least the minimum amount of gas specified.
            // We can prove this property by solving the inequalities:
            // ((((_minGas + 200) * 64) / 63) - 49) >= _minGas
            // ((((_minGas + 200) * 64) / 63) - 51) * (63 / 64) >= _minGas
            // Both inequalities hold true for all possible values of `_minGas`.
            gasSent := gas() // @audit this operation costs 2 gas
            _success := call(
                gas(), // gas
                _target, // recipient
                _value, // ether value
                add(_calldata, 32), // inloc
                mload(_calldata), // inlen
                0x00, // outloc
                0x00 // outlen
            )
        }
        console.log("gasSent =", gasSent);
        return _success;
    }
}

contract Callee {
    fallback() external payable {
        uint256 gas = gasleft();
        console.log("gasReceived =", gas);
    }
}

contract Caller {
    function execute(
        address _target,
        uint256 _minGas,
        bytes memory _calldata
    ) external payable {
        SafeCall.callWithMinGas(_target, _minGas, msg.value, _calldata);
    }
}

contract TestCallWithMinGas is Test {
    address callee;
    Caller caller;

    function setUp() public {
        callee = address(new Callee());
        caller = new Caller();
    }

    function testCallWithMinGas() public {
        console.log("-------1st call------");
        caller.execute{gas: 64_855}(callee, 63_000, "");

        console.log("\n  -------2nd call------");
        caller.execute{gas: 64_855}(callee, 63_000, "");

        console.log("\n  -------3rd call------");
        caller.execute{gas: 62_555, value: 1}(callee, 63_000, "");
    }
}

And the log would be

Solidity
Running 1 test for test/TestCallWithMinGas.sol:TestCallWithMinGas
[PASS] testCallWithMinGas() (gas: 36065)
Logs:
  -------1st call------
  gasReceived = 60582
  gasSent = 64200

  -------2nd call------
  gasReceived = 63042
  gasSent = 64200

  -------3rd call------
  gasReceived = 56483
  gasSent = 64200

The difference between 1st call and 2nd call is caused by EIP-2929, and the difference between 2nd call and 3rd call is caused by transferring value. We can see the actual received gas in the sub-contract is less than the 63,000 _minGas limit in both 1st and 3rd call.

Impact

SafeCall.callWithMinGas() is a key design to ensure withdrawal transactions will be executed with more gas than the limit specified by users. This issue breaks the specification. Finalizing withdrawal transactions with less than specified gas limit may fail unexpectedly due to out of gas, lead to loss of funds.

Code Snippet

https://github.com/sherlock-audit/2023-03-optimism/blob/main/optimism/packages/contracts-bedrock/contracts/libraries/SafeCall.sol#L48

Tool used

Manual Review

Recommendation

The migration logic may look like

Solidity
if (_value == 0) {
     gasleft() >= ((_minGas + 200) * 64) / 63 + 2600
} else {
     gasleft() >= ((_minGas + 200) * 64) / 63 + 2600 + 6700
}

Discussion

GalloDaSballo

The math checks out, the base-gas is ignoring CALL + Cold Address meaning that there are scenarios in which base gas is not sufficient

hrishibhat

Sponsor comment: This report is valid. The formula used in SafeCall.callWithMinGas() does not account for all of the dynamic gas costs of the CALL opcode.

GalloDaSballo

The finding shows the full impact, agree with High Severity

The original report as published on Sherlock, by KingNFT. 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 formula only applied the 63/64 rule without subtracting the base gas costs for cold account access and value transfer, so the actual gas forwarded was lower than intended.

Impact

Withdrawal transactions could be finalized with less gas than the user specified, potentially causing them to fail due to out-of-gas and leading to loss of funds.

What the attacker needed

Withdrawal transaction using callWithMinGas; gas provided close to the minimum threshold

The fix

The formula should be updated to add the cold account access cost and, when value is transferred, the value transfer cost to the required gas check.

How it was found

  1. Deploy a caller contract that uses SafeCall.callWithMinGas() and a callee contract that logs the gas it receives.
  2. Call the caller with a gas amount just above the formula's threshold and a minimum gas value.
  3. Observe that the callee receives less gas than the specified minimum, especially on the first call or when value is transferred.

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.

When one smart contract calls another, it must reserve enough gas for the call to succeed. The code tried to guarantee a minimum amount of gas would reach the called contract, but its formula missed some costs that the Ethereum virtual machine charges before passing gas along. As a result, the called contract sometimes got less gas than promised, which could make important transactions 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 by KingNFT

View all

25 more disclosed reports, best first.

More from Optimism Update

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.