clear_pending_tx_test.go 9.97 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package drivers_test

import (
	"context"
	"crypto/ecdsa"
	"errors"
	"math/big"
	"testing"
	"time"

11 12 13
	"github.com/ethereum-optimism/optimism/bss-core/drivers"
	"github.com/ethereum-optimism/optimism/bss-core/mock"
	"github.com/ethereum-optimism/optimism/bss-core/txmgr"
14
	"github.com/ethereum/go-ethereum"
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/stretchr/testify/require"
)

func init() {
	privKey, err := crypto.GenerateKey()
	if err != nil {
		panic(err)
	}
	testPrivKey = privKey
	testWalletAddr = crypto.PubkeyToAddress(privKey.PublicKey)
}

var (
32 33 34 35
	testPrivKey     *ecdsa.PrivateKey
	testWalletAddr  common.Address
	testChainID     = big.NewInt(1)
	testNonce       = uint64(2)
36 37
	testGasFeeCap   = big.NewInt(3)
	testGasTipCap   = big.NewInt(4)
38
	testBlockNumber = uint64(5)
39
	testBaseFee     = big.NewInt(6)
40
	testGasLimit    = uint64(7)
41 42 43 44 45 46
)

// TestCraftClearingTx asserts that CraftClearingTx produces the expected
// unsigned clearing transaction.
func TestCraftClearingTx(t *testing.T) {
	tx := drivers.CraftClearingTx(
47
		testWalletAddr, testNonce, testGasFeeCap, testGasTipCap, testGasLimit,
48 49 50
	)
	require.Equal(t, &testWalletAddr, tx.To())
	require.Equal(t, testNonce, tx.Nonce())
51
	require.Equal(t, testGasLimit, tx.Gas())
52 53
	require.Equal(t, testGasFeeCap, tx.GasFeeCap())
	require.Equal(t, testGasTipCap, tx.GasTipCap())
54 55 56 57 58 59 60 61
	require.Equal(t, new(big.Int), tx.Value())
	require.Nil(t, tx.Data())
}

// TestSignClearingTxSuccess asserts that we will sign a properly formed
// clearing transaction when the call to EstimateGas succeeds.
func TestSignClearingTxEstimateGasSuccess(t *testing.T) {
	l1Client := mock.NewL1Client(mock.L1ClientConfig{
62 63 64 65 66 67 68
		HeaderByNumber: func(_ context.Context, _ *big.Int) (*types.Header, error) {
			return &types.Header{
				BaseFee: testBaseFee,
			}, nil
		},
		SuggestGasTipCap: func(_ context.Context) (*big.Int, error) {
			return testGasTipCap, nil
69
		},
70 71 72
		EstimateGas: func(_ context.Context, _ ethereum.CallMsg) (uint64, error) {
			return testGasLimit, nil
		},
73 74
	})

75 76 77 78 79
	expGasFeeCap := new(big.Int).Add(
		testGasTipCap,
		new(big.Int).Mul(testBaseFee, big.NewInt(2)),
	)

80
	tx, err := drivers.SignClearingTx(
81 82
		"TEST", context.Background(), testWalletAddr, testNonce, l1Client,
		testPrivKey, testChainID,
83 84 85 86 87
	)
	require.Nil(t, err)
	require.NotNil(t, tx)
	require.Equal(t, &testWalletAddr, tx.To())
	require.Equal(t, testNonce, tx.Nonce())
88 89
	require.Equal(t, expGasFeeCap, tx.GasFeeCap())
	require.Equal(t, testGasTipCap, tx.GasTipCap())
90 91 92 93 94 95 96 97 98
	require.Equal(t, new(big.Int), tx.Value())
	require.Nil(t, tx.Data())

	// Finally, ensure the sender is correct.
	sender, err := types.Sender(types.LatestSignerForChainID(testChainID), tx)
	require.Nil(t, err)
	require.Equal(t, testWalletAddr, sender)
}

99 100 101 102
// TestSignClearingTxSuggestGasTipCapFail asserts that signing a clearing
// transaction will fail if the underlying call to SuggestGasTipCap fails.
func TestSignClearingTxSuggestGasTipCapFail(t *testing.T) {
	errSuggestGasTipCap := errors.New("suggest gas tip cap")
103 104

	l1Client := mock.NewL1Client(mock.L1ClientConfig{
105 106
		SuggestGasTipCap: func(_ context.Context) (*big.Int, error) {
			return nil, errSuggestGasTipCap
107 108 109 110
		},
	})

	tx, err := drivers.SignClearingTx(
111 112
		"TEST", context.Background(), testWalletAddr, testNonce, l1Client,
		testPrivKey, testChainID,
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
	)
	require.Equal(t, errSuggestGasTipCap, err)
	require.Nil(t, tx)
}

// TestSignClearingTxHeaderByNumberFail asserts that signing a clearing
// transaction will fail if the underlying call to HeaderByNumber fails.
func TestSignClearingTxHeaderByNumberFail(t *testing.T) {
	errHeaderByNumber := errors.New("header by number")

	l1Client := mock.NewL1Client(mock.L1ClientConfig{
		HeaderByNumber: func(_ context.Context, _ *big.Int) (*types.Header, error) {
			return nil, errHeaderByNumber
		},
		SuggestGasTipCap: func(_ context.Context) (*big.Int, error) {
			return testGasTipCap, nil
		},
	})

	tx, err := drivers.SignClearingTx(
133 134
		"TEST", context.Background(), testWalletAddr, testNonce, l1Client,
		testPrivKey, testChainID,
135
	)
136
	require.Equal(t, errHeaderByNumber, err)
137 138 139
	require.Nil(t, tx)
}

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
// TestSignClearingTxEstimateGasFail asserts that signing a clearing
// transaction will fail if the underlying call to EstimateGas fails.
func TestSignClearingTxEstimateGasFail(t *testing.T) {
	errEstimateGas := errors.New("estimate gas")

	l1Client := mock.NewL1Client(mock.L1ClientConfig{
		EstimateGas: func(_ context.Context, _ ethereum.CallMsg) (uint64, error) {
			return 0, errEstimateGas
		},
		HeaderByNumber: func(_ context.Context, _ *big.Int) (*types.Header, error) {
			return &types.Header{
				BaseFee: testBaseFee,
			}, nil
		},
		SuggestGasTipCap: func(_ context.Context) (*big.Int, error) {
			return testGasTipCap, nil
		},
	})

	tx, err := drivers.SignClearingTx(
		"TEST", context.Background(), testWalletAddr, testNonce, l1Client,
		testPrivKey, testChainID,
	)
	require.Equal(t, errEstimateGas, err)
	require.Nil(t, tx)
}

167
type clearPendingTxHarness struct {
168
	l1Client *mock.L1Client
169 170 171
	txMgr    txmgr.TxManager
}

172 173 174 175
func newClearPendingTxHarnessWithNumConfs(
	l1ClientConfig mock.L1ClientConfig,
	numConfirmations uint64,
) *clearPendingTxHarness {
176 177 178 179 180 181

	if l1ClientConfig.BlockNumber == nil {
		l1ClientConfig.BlockNumber = func(_ context.Context) (uint64, error) {
			return testBlockNumber, nil
		}
	}
182 183 184 185 186 187 188
	if l1ClientConfig.HeaderByNumber == nil {
		l1ClientConfig.HeaderByNumber = func(_ context.Context, _ *big.Int) (*types.Header, error) {
			return &types.Header{
				BaseFee: testBaseFee,
			}, nil
		}
	}
189 190 191 192 193
	if l1ClientConfig.NonceAt == nil {
		l1ClientConfig.NonceAt = func(_ context.Context, _ common.Address, _ *big.Int) (uint64, error) {
			return testNonce, nil
		}
	}
194 195 196
	if l1ClientConfig.SuggestGasTipCap == nil {
		l1ClientConfig.SuggestGasTipCap = func(_ context.Context) (*big.Int, error) {
			return testGasTipCap, nil
197 198
		}
	}
199 200 201 202 203
	if l1ClientConfig.EstimateGas == nil {
		l1ClientConfig.EstimateGas = func(_ context.Context, _ ethereum.CallMsg) (uint64, error) {
			return testGasLimit, nil
		}
	}
204 205 206

	l1Client := mock.NewL1Client(l1ClientConfig)
	txMgr := txmgr.NewSimpleTxManager("test", txmgr.Config{
207 208 209 210
		ResubmissionTimeout:       time.Second,
		ReceiptQueryInterval:      50 * time.Millisecond,
		NumConfirmations:          numConfirmations,
		SafeAbortNonceTooLowCount: 3,
211 212 213 214 215 216 217 218
	}, l1Client)

	return &clearPendingTxHarness{
		l1Client: l1Client,
		txMgr:    txMgr,
	}
}

219 220 221 222
func newClearPendingTxHarness(l1ClientConfig mock.L1ClientConfig) *clearPendingTxHarness {
	return newClearPendingTxHarnessWithNumConfs(l1ClientConfig, 1)
}

223 224 225 226 227 228 229 230 231
// TestClearPendingTxClearingTxÇonfirms asserts the happy path where our
// clearing transactions confirms unobstructed.
func TestClearPendingTxClearingTxConfirms(t *testing.T) {
	h := newClearPendingTxHarness(mock.L1ClientConfig{
		SendTransaction: func(_ context.Context, _ *types.Transaction) error {
			return nil
		},
		TransactionReceipt: func(_ context.Context, txHash common.Hash) (*types.Receipt, error) {
			return &types.Receipt{
232 233
				TxHash:      txHash,
				BlockNumber: big.NewInt(int64(testBlockNumber)),
234
				Status:      types.ReceiptStatusSuccessful,
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
			}, nil
		},
	})

	err := drivers.ClearPendingTx(
		"test", context.Background(), h.txMgr, h.l1Client, testWalletAddr,
		testPrivKey, testChainID,
	)
	require.Nil(t, err)
}

// TestClearPendingTx∏reviousTxConfirms asserts that if the mempool starts
// rejecting our transactions because the nonce is too low that ClearPendingTx
// will abort continuing to publish a clearing transaction.
func TestClearPendingTxPreviousTxConfirms(t *testing.T) {
	h := newClearPendingTxHarness(mock.L1ClientConfig{
		SendTransaction: func(_ context.Context, _ *types.Transaction) error {
			return core.ErrNonceTooLow
		},
	})

	err := drivers.ClearPendingTx(
		"test", context.Background(), h.txMgr, h.l1Client, testWalletAddr,
		testPrivKey, testChainID,
	)
	require.Equal(t, drivers.ErrClearPendingRetry, err)
}

// TestClearPendingTxTimeout asserts that ClearPendingTx returns an
// ErrPublishTimeout if the clearing transaction fails to confirm in a timely
// manner and no prior transaction confirms.
func TestClearPendingTxTimeout(t *testing.T) {
	h := newClearPendingTxHarness(mock.L1ClientConfig{
		SendTransaction: func(_ context.Context, _ *types.Transaction) error {
			return nil
		},
		TransactionReceipt: func(_ context.Context, txHash common.Hash) (*types.Receipt, error) {
			return nil, nil
		},
	})

276 277 278
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

279
	err := drivers.ClearPendingTx(
280 281
		"test", ctx, h.txMgr, h.l1Client, testWalletAddr, testPrivKey,
		testChainID,
282
	)
283
	require.Equal(t, context.DeadlineExceeded, err)
284
}
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

// TestClearPendingTxMultipleConfs tests we wait the appropriate number of
// confirmations for the clearing transaction to confirm.
func TestClearPendingTxMultipleConfs(t *testing.T) {
	const numConfs = 2

	// Instantly confirm transaction.
	h := newClearPendingTxHarnessWithNumConfs(mock.L1ClientConfig{
		SendTransaction: func(_ context.Context, _ *types.Transaction) error {
			return nil
		},
		TransactionReceipt: func(_ context.Context, txHash common.Hash) (*types.Receipt, error) {
			return &types.Receipt{
				TxHash:      txHash,
				BlockNumber: big.NewInt(int64(testBlockNumber)),
300
				Status:      types.ReceiptStatusSuccessful,
301 302 303 304
			}, nil
		},
	}, numConfs)

305 306 307
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

308 309
	// The txmgr should timeout waiting for the txn to confirm.
	err := drivers.ClearPendingTx(
310 311
		"test", ctx, h.txMgr, h.l1Client, testWalletAddr, testPrivKey,
		testChainID,
312
	)
313
	require.Equal(t, context.DeadlineExceeded, err)
314 315 316 317 318 319 320 321 322 323 324 325 326 327

	// Now set the chain height to the earliest the transaction will be
	// considered sufficiently confirmed.
	h.l1Client.SetBlockNumberFunc(func(_ context.Context) (uint64, error) {
		return testBlockNumber + numConfs - 1, nil
	})

	// Publishing should succeed.
	err = drivers.ClearPendingTx(
		"test", context.Background(), h.txMgr, h.l1Client, testWalletAddr,
		testPrivKey, testChainID,
	)
	require.Nil(t, err)
}