Skip to content

Commit 3608f90

Browse files
authored
Return already known for a resent EVM transaction (#4553)
`eth_sendRawTransaction` passed the mempool's `tx already exists in cache` error straight through when a transaction was resent. Ethereum clients expect geth's `already known` for a tx that is already pending. ethers 6.15 doesn't recognise the Sei message, and the nightly `TestNightlyGigaMixedRelease` run failed on it on 10-12 with a NaN underflow in the step after the resend. The mempool also returns the same error for txs that will never be mined, so mapping all of it to `already known` would leave a client waiting for a receipt that never comes. Part of SEI-10413. `txStore.ShouldReject` becomes `txStore.Rejection`, which returns why the tx is rejected. The reasons are new sentinels in `sei-tendermint/types`: `ErrTxInMempool` (in the pool, or being checked in parallel), `ErrTxNonceTooLow`, `ErrTxReplacementUnderpriced` and `ErrTxInsufficientFunds` (a tx with the same nonce wins). Each wraps `ErrTxInCache`, which also moves to `types` so that `evmrpc` can import it. `SendRawTransaction` maps them to `txpool.ErrAlreadyKnown`, `core.ErrNonceTooLow`, `txpool.ErrReplaceUnderpriced` and `core.ErrInsufficientFunds` on both the sync and commit broadcast paths. A tx cached as executed or invalid has no metadata to tell those cases apart, so it keeps the plain `ErrTxInCache` message. Every new error still matches `errors.Is(err, ErrTxInCache)` and still contains `tx already exists in cache`. The mempool reactor's gossip check and the Cosmos client's `ErrTxInMempoolCache` mapping therefore behave as before. The mempool only changes which error it returns, never which txs it admits.
1 parent 69861ea commit 3608f90

7 files changed

Lines changed: 156 additions & 31 deletions

File tree

‎evmrpc/send.go‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import (
1010

1111
"github.com/ethereum/go-ethereum/common"
1212
"github.com/ethereum/go-ethereum/common/hexutil"
13+
"github.com/ethereum/go-ethereum/core"
14+
"github.com/ethereum/go-ethereum/core/txpool"
1315
ethtypes "github.com/ethereum/go-ethereum/core/types"
1416
"github.com/ethereum/go-ethereum/export"
1517
"github.com/ethereum/go-ethereum/rpc"
@@ -22,6 +24,7 @@ import (
2224
sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
2325
sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors"
2426
"github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils"
27+
tmtypes "github.com/sei-protocol/sei-chain/sei-tendermint/types"
2528
"github.com/sei-protocol/sei-chain/x/evm/keeper"
2629
"github.com/sei-protocol/sei-chain/x/evm/types"
2730
"github.com/sei-protocol/sei-chain/x/evm/types/ethtx"
@@ -140,7 +143,7 @@ func (s *SendAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (
140143
if s.sendConfig.slow && !s.sendConfig.autobahn {
141144
res, broadcastError := s.tmClient.BroadcastTxCommit(ctx, txbz)
142145
if broadcastError != nil {
143-
err = broadcastError
146+
err = toEthBroadcastError(broadcastError)
144147
} else if res == nil {
145148
err = errors.New("missing broadcast response")
146149
} else if res.CheckTx.Code != 0 {
@@ -149,7 +152,7 @@ func (s *SendAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (
149152
} else {
150153
res, broadcastError := s.tmClient.BroadcastTx(ctx, txbz)
151154
if broadcastError != nil {
152-
err = broadcastError
155+
err = toEthBroadcastError(broadcastError)
153156
} else if res == nil {
154157
err = errors.New("missing broadcast response")
155158
} else if res.Code != 0 {
@@ -159,6 +162,22 @@ func (s *SendAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (
159162
return
160163
}
161164

165+
// toEthBroadcastError maps a mempool rejection to its Ethereum equivalent, if it has one.
166+
func toEthBroadcastError(err error) error {
167+
switch {
168+
case errors.Is(err, tmtypes.ErrTxInMempool):
169+
return txpool.ErrAlreadyKnown
170+
case errors.Is(err, tmtypes.ErrTxNonceTooLow):
171+
return core.ErrNonceTooLow
172+
case errors.Is(err, tmtypes.ErrTxReplacementUnderpriced):
173+
return txpool.ErrReplaceUnderpriced
174+
case errors.Is(err, tmtypes.ErrTxInsufficientFunds):
175+
return core.ErrInsufficientFunds
176+
default:
177+
return err
178+
}
179+
}
180+
162181
func getSender(tx *ethtypes.Transaction, chainID *big.Int) (common.Address, error) {
163182
return ethtypes.LatestSignerForChainID(chainID).Sender(tx)
164183
}

‎evmrpc/send_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"encoding/hex"
66
"encoding/json"
7+
"fmt"
78
"math/big"
89
"net/http"
910
"net/http/httptest"
@@ -12,6 +13,8 @@ import (
1213

1314
"github.com/ethereum/go-ethereum/common"
1415
"github.com/ethereum/go-ethereum/common/hexutil"
16+
"github.com/ethereum/go-ethereum/core"
17+
"github.com/ethereum/go-ethereum/core/txpool"
1518
ethtypes "github.com/ethereum/go-ethereum/core/types"
1619
"github.com/ethereum/go-ethereum/crypto"
1720
"github.com/ethereum/go-ethereum/rpc"
@@ -249,6 +252,43 @@ func TestSendRawTransactionSlowOnCometUsesBroadcastTxCommit(t *testing.T) {
249252
require.Equal(t, 1, tmClient.commitCount)
250253
}
251254

255+
// rejectingClient fails every broadcast with err.
256+
type rejectingClient struct {
257+
*MockClient
258+
err error
259+
}
260+
261+
func (c *rejectingClient) BroadcastTx(context.Context, tmtypes.Tx) (*coretypes.ResultBroadcastTx, error) {
262+
return nil, c.err
263+
}
264+
265+
func (c *rejectingClient) BroadcastTxCommit(context.Context, tmtypes.Tx) (*coretypes.ResultBroadcastTxCommit, error) {
266+
return nil, c.err
267+
}
268+
269+
func TestSendRawTransactionMapsMempoolRejections(t *testing.T) {
270+
ethTxBytes, _ := mustSignTestTx(t)
271+
for _, tc := range []struct {
272+
mempoolErr error
273+
want error
274+
}{
275+
{tmtypes.ErrTxInMempool, txpool.ErrAlreadyKnown},
276+
{tmtypes.ErrTxNonceTooLow, core.ErrNonceTooLow},
277+
{tmtypes.ErrTxReplacementUnderpriced, txpool.ErrReplaceUnderpriced},
278+
{tmtypes.ErrTxInsufficientFunds, core.ErrInsufficientFunds},
279+
{tmtypes.ErrTxInCache, tmtypes.ErrTxInCache},
280+
} {
281+
for _, slow := range []bool{false, true} {
282+
t.Run(fmt.Sprintf("%v/slow=%v", tc.mempoolErr, slow), func(t *testing.T) {
283+
client := &rejectingClient{MockClient: &MockClient{}, err: tc.mempoolErr}
284+
sendAPI := newTestSendAPI(client, evmrpc.NewSendConfig(slow, false, false))
285+
_, err := sendAPI.SendRawTransaction(t.Context(), hexutil.Bytes(ethTxBytes))
286+
require.ErrorIs(t, err, tc.want)
287+
})
288+
}
289+
}
290+
}
291+
252292
func mustSignTestTx(t *testing.T) ([]byte, *ethtypes.Transaction) {
253293
t.Helper()
254294
to := common.HexToAddress("010203")

‎sei-tendermint/internal/mempool/mempool.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import (
2121
var logger = seilog.NewLogger("tendermint", "internal", "mempool")
2222

2323
// ErrTxInCache is returned to the client if we saw tx earlier.
24-
var ErrTxInCache = errors.New("tx already exists in cache")
24+
var ErrTxInCache = types.ErrTxInCache
2525

2626
// ErrTxTooLarge defines an error when a transaction is too big to be sent to peers.
2727
var ErrTxTooLarge = errors.New("tx too large")
@@ -303,8 +303,8 @@ func (txmp *TxMempool) CheckTx(ctx context.Context, tx types.Tx) (*abci.Response
303303

304304
// Avoid processing same transaction in parallel.
305305
if !txmp.txLocks.Lock(hTx.Hash()) {
306-
// ErrTxInCache is returned for backward compatibility.
307-
return nil, ErrTxInCache
306+
// ErrTxInMempool wraps ErrTxInCache for backward compatibility.
307+
return nil, types.ErrTxInMempool
308308
}
309309
defer txmp.txLocks.Unlock(hTx.Hash())
310310

@@ -337,8 +337,8 @@ func (txmp *TxMempool) CheckTx(ctx context.Context, tx types.Tx) (*abci.Response
337337
}
338338

339339
// Check if the tx is known to be bad.
340-
if txmp.txStore.ShouldReject(hTx.Hash()) {
341-
return nil, ErrTxInCache
340+
if err := txmp.txStore.Rejection(hTx.Hash()); err != nil {
341+
return nil, err
342342
}
343343

344344
if c, ok := txmp.duplicateTxsCache.Get(); ok {

‎sei-tendermint/internal/mempool/mempool_test.go‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -975,7 +975,7 @@ func TestTxMempool_EvmMetadataCacheShortCircuitsAndReadmitsAfterFailedExecution(
975975
require.Equal(t, 1, txmp.Size())
976976

977977
_, err = txmp.CheckTx(ctx, tc.worseTx)
978-
require.Equal(t, ErrTxInCache, err)
978+
require.ErrorIs(t, err, ErrTxInCache)
979979
require.Equal(t, 1, txmp.Size())
980980

981981
txmp.Lock()
@@ -993,6 +993,55 @@ func TestTxMempool_EvmMetadataCacheShortCircuitsAndReadmitsAfterFailedExecution(
993993
}
994994
}
995995

996+
func TestTxMempool_CheckTxRejectionReasons(t *testing.T) {
997+
ctx := t.Context()
998+
sender := common.HexToAddress("0x00000000000000000000000000000000000000aa")
999+
betterTx := types.Tx(fmt.Sprintf("evm=%s=%d=%d=%d", sender.Hex(), 7, 10, 0))
1000+
1001+
for _, tc := range []struct {
1002+
name string
1003+
resent types.Tx
1004+
wantErr error
1005+
}{
1006+
{
1007+
name: "same tx",
1008+
resent: betterTx,
1009+
wantErr: types.ErrTxInMempool,
1010+
},
1011+
{
1012+
name: "same nonce lower priority",
1013+
resent: types.Tx(fmt.Sprintf("evm=%s=%d=%d=%d", sender.Hex(), 7, 9, 0)),
1014+
wantErr: types.ErrTxReplacementUnderpriced,
1015+
},
1016+
{
1017+
name: "same nonce higher priority but too high required balance",
1018+
resent: types.Tx(fmt.Sprintf("evm=%s=%d=%d=%d", sender.Hex(), 7, 20, 101)),
1019+
wantErr: types.ErrTxInsufficientFunds,
1020+
},
1021+
} {
1022+
t.Run(tc.name, func(t *testing.T) {
1023+
app := newEVMNonceApp()
1024+
app.setNonce(sender, 7)
1025+
app.setBalance(sender, 100)
1026+
1027+
cfg := TestConfig()
1028+
cfg.CacheSize = 100
1029+
txmp := setup(cfg, proxy.New(app), NopTxConstraintsFetcher)
1030+
1031+
_, err := txmp.CheckTx(ctx, betterTx)
1032+
require.NoError(t, err)
1033+
if !bytes.Equal(tc.resent, betterTx) {
1034+
_, err = txmp.CheckTx(ctx, tc.resent)
1035+
require.ErrorIs(t, err, errSameNonce)
1036+
}
1037+
1038+
_, err = txmp.CheckTx(ctx, tc.resent)
1039+
require.ErrorIs(t, err, tc.wantErr)
1040+
require.Equal(t, 1, txmp.Size())
1041+
})
1042+
}
1043+
}
1044+
9961045
func TestBlockFailedTxTrackerClearedOnSuccess(t *testing.T) {
9971046
ctx := t.Context()
9981047

‎sei-tendermint/internal/mempool/tx.go‎

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,10 @@ func (s *txStore) Clear() {
211211
}
212212

213213
// Checks if tx should be immediately rejected.
214-
func (s *txStore) ShouldReject(txHash types.TxHash) bool {
214+
// Rejection returns why a tx with this hash must be rejected, or nil if it may be admitted.
215+
func (s *txStore) Rejection(txHash types.TxHash) error {
215216
for inner := range s.inner.RLock() {
216-
return inner.shouldReject(txHash)
217+
return inner.rejection(txHash)
217218
}
218219
panic("unreachable")
219220
}
@@ -320,48 +321,48 @@ func (s *txStore) SafeGetTxsForHashes(txHashes []types.TxHash) (types.Txs, []typ
320321
return got, missing
321322
}
322323

323-
func (inner *txStoreInner) shouldReject(txHash types.TxHash) bool {
324-
// Already in mempool => true
324+
func (inner *txStoreInner) rejection(txHash types.TxHash) error {
325+
// Already in mempool => reject
325326
if _, ok := inner.byHash[txHash]; ok {
326-
return true
327+
return types.ErrTxInMempool
327328
}
328-
// Not cached => false
329+
// Not cached => admit
329330
e, ok := inner.cache.Get(txHash)
330331
if !ok {
331-
return false
332+
return nil
332333
}
333334
// empty entry means that tx is known to be invalid.
334335
evm, ok := e.Get()
335336
if !ok {
336-
return true
337+
return types.ErrTxInCache
337338
}
338-
// evm account not tracked => false
339+
// evm account not tracked => admit
339340
account, ok := inner.accounts[evm.address]
340341
if !ok {
341-
return false
342+
return nil
342343
}
343-
// too old nonce => true
344+
// too old nonce => reject
344345
if evm.nonce < account.firstNonce {
345-
return true
346+
return types.ErrTxNonceTooLow
346347
}
347-
// no conflicting nonce => false
348+
// no conflicting nonce => admit
348349
old, ok := inner.byNonce[evmAddrNonce{evm.address, evm.nonce}]
349350
if !ok {
350-
return false
351+
return nil
351352
}
352-
// better tx for this nonce in mempool => false
353+
// better tx for this nonce in mempool => reject
353354
oldEvm := old.evm.OrPanic("non-evm tx")
354355
oldReady := oldEvm.nonce < account.nextNonce
355356
// If the old tx is ready but the new tx is not, then reject the new tx.
356357
if oldReady && account.balance.Cmp(&evm.requiredBalance) < 0 {
357-
return true
358+
return types.ErrTxInsufficientFunds
358359
}
359360
// If the old tx has >= priority, then reject new tx.
360361
if old.priority >= evm.priority {
361-
return true
362+
return types.ErrTxReplacementUnderpriced
362363
}
363-
// otherwise => false
364-
return false
364+
// otherwise => admit
365+
return nil
365366
}
366367

367368
// account returns the tracked state of the evm account, fetching it from the app on first use.

‎sei-tendermint/internal/mempool/tx_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -576,8 +576,8 @@ func TestTxStore_ExpiredTxCacheBehavior(t *testing.T) {
576576
_, pendingPresent := txStore.ByHash(pending.Hash())
577577
require.Equal(t, tc.wantReadyPresent, readyPresent)
578578
require.Equal(t, tc.wantPendingPresent, pendingPresent)
579-
require.Equal(t, tc.wantReadyRejected, txStore.ShouldReject(ready.Hash()))
580-
require.Equal(t, tc.wantPendingRejected, txStore.ShouldReject(pending.Hash()))
579+
require.Equal(t, tc.wantReadyRejected, txStore.Rejection(ready.Hash()) != nil)
580+
require.Equal(t, tc.wantPendingRejected, txStore.Rejection(pending.Hash()) != nil)
581581
})
582582
}
583583
}
@@ -612,8 +612,8 @@ func TestTxStore_NoncePrunedTxsRejectedAsOldNonce(t *testing.T) {
612612
_, pendingPresent := txStore.ByHash(prunedPending.Hash())
613613
require.False(t, readyPresent)
614614
require.False(t, pendingPresent)
615-
require.True(t, txStore.ShouldReject(prunedReady.Hash()))
616-
require.True(t, txStore.ShouldReject(prunedPending.Hash()))
615+
require.ErrorIs(t, txStore.Rejection(prunedReady.Hash()), types.ErrTxInCache)
616+
require.ErrorIs(t, txStore.Rejection(prunedPending.Hash()), types.ErrTxInCache)
617617
}
618618

619619
func TestTxStore_ReplacesReadyTxByHigherPriority(t *testing.T) {

‎sei-tendermint/types/mempool.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,22 @@ import (
1010
tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types"
1111
)
1212

13+
var (
14+
// ErrTxInCache is returned when the mempool rejects a tx it has already seen. The errors below
15+
// wrap it to say why the tx was rejected.
16+
ErrTxInCache = errors.New("tx already exists in cache")
17+
// ErrTxInMempool is returned when the tx is already in the mempool or is being checked.
18+
ErrTxInMempool = fmt.Errorf("%w: tx is pending", ErrTxInCache)
19+
// ErrTxNonceTooLow is returned when the tx's nonce is below the sender's lowest pending nonce.
20+
ErrTxNonceTooLow = fmt.Errorf("%w: nonce too low", ErrTxInCache)
21+
// ErrTxReplacementUnderpriced is returned when the mempool holds a tx with the same nonce
22+
// and at least the same priority.
23+
ErrTxReplacementUnderpriced = fmt.Errorf("%w: replacement transaction underpriced", ErrTxInCache)
24+
// ErrTxInsufficientFunds is returned when the tx would replace a ready tx with the same nonce
25+
// but the sender cannot afford it.
26+
ErrTxInsufficientFunds = fmt.Errorf("%w: insufficient funds", ErrTxInCache)
27+
)
28+
1329
// TxHash is the fixed length array hash used as an index.
1430
type TxHash crypto.Hash
1531

0 commit comments

Comments
 (0)