gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/core/tx_pool_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"math/big"
    24  	"math/rand"
    25  	"os"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/core/rawdb"
    31  	"github.com/ethereum/go-ethereum/core/state"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/crypto"
    34  	"github.com/ethereum/go-ethereum/event"
    35  	"github.com/ethereum/go-ethereum/params"
    36  )
    37  
    38  // testTxPoolConfig is a transaction pool configuration without stateful disk
    39  // sideeffects used during testing.
    40  var testTxPoolConfig TxPoolConfig
    41  
    42  func init() {
    43  	testTxPoolConfig = DefaultTxPoolConfig
    44  	testTxPoolConfig.Journal = ""
    45  }
    46  
    47  type testBlockChain struct {
    48  	statedb       *state.StateDB
    49  	gasLimit      uint64
    50  	chainHeadFeed *event.Feed
    51  }
    52  
    53  func (bc *testBlockChain) CurrentBlock() *types.Block {
    54  	return types.NewBlock(&types.Header{
    55  		GasLimit: bc.gasLimit,
    56  	}, nil, nil, nil)
    57  }
    58  
    59  func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
    60  	return bc.CurrentBlock()
    61  }
    62  
    63  func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) {
    64  	return bc.statedb, nil
    65  }
    66  
    67  func (bc *testBlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
    68  	return bc.chainHeadFeed.Subscribe(ch)
    69  }
    70  
    71  func transaction(nonce uint64, gaslimit uint64, key *ecdsa.PrivateKey) *types.Transaction {
    72  	return pricedTransaction(nonce, gaslimit, big.NewInt(1), key)
    73  }
    74  
    75  func pricedTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
    76  	tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, gasprice, nil), types.HomesteadSigner{}, key)
    77  	return tx
    78  }
    79  
    80  func pricedDataTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey, bytes uint64) *types.Transaction {
    81  	data := make([]byte, bytes)
    82  	rand.Read(data)
    83  
    84  	tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(0), gaslimit, gasprice, data), types.HomesteadSigner{}, key)
    85  	return tx
    86  }
    87  
    88  func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
    89  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
    90  	blockchain := &testBlockChain{statedb, 10000000, new(event.Feed)}
    91  
    92  	key, _ := crypto.GenerateKey()
    93  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    94  
    95  	return pool, key
    96  }
    97  
    98  // validateTxPoolInternals checks various consistency invariants within the pool.
    99  func validateTxPoolInternals(pool *TxPool) error {
   100  	pool.mu.RLock()
   101  	defer pool.mu.RUnlock()
   102  
   103  	// Ensure the total transaction set is consistent with pending + queued
   104  	pending, queued := pool.stats()
   105  	if total := pool.all.Count(); total != pending+queued {
   106  		return fmt.Errorf("total transaction count %d != %d pending + %d queued", total, pending, queued)
   107  	}
   108  	if priced := pool.priced.items.Len() - pool.priced.stales; priced != pending+queued {
   109  		return fmt.Errorf("total priced transaction count %d != %d pending + %d queued", priced, pending, queued)
   110  	}
   111  	// Ensure the next nonce to assign is the correct one
   112  	for addr, txs := range pool.pending {
   113  		// Find the last transaction
   114  		var last uint64
   115  		for nonce := range txs.txs.items {
   116  			if last < nonce {
   117  				last = nonce
   118  			}
   119  		}
   120  		if nonce := pool.Nonce(addr); nonce != last+1 {
   121  			return fmt.Errorf("pending nonce mismatch: have %v, want %v", nonce, last+1)
   122  		}
   123  	}
   124  	return nil
   125  }
   126  
   127  // validateEvents checks that the correct number of transaction addition events
   128  // were fired on the pool's event feed.
   129  func validateEvents(events chan NewTxsEvent, count int) error {
   130  	var received []*types.Transaction
   131  
   132  	for len(received) < count {
   133  		select {
   134  		case ev := <-events:
   135  			received = append(received, ev.Txs...)
   136  		case <-time.After(time.Second):
   137  			return fmt.Errorf("event #%d not fired", len(received))
   138  		}
   139  	}
   140  	if len(received) > count {
   141  		return fmt.Errorf("more than %d events fired: %v", count, received[count:])
   142  	}
   143  	select {
   144  	case ev := <-events:
   145  		return fmt.Errorf("more than %d events fired: %v", count, ev.Txs)
   146  
   147  	case <-time.After(50 * time.Millisecond):
   148  		// This branch should be "default", but it's a data race between goroutines,
   149  		// reading the event channel and pushing into it, so better wait a bit ensuring
   150  		// really nothing gets injected.
   151  	}
   152  	return nil
   153  }
   154  
   155  func deriveSender(tx *types.Transaction) (common.Address, error) {
   156  	return types.Sender(types.HomesteadSigner{}, tx)
   157  }
   158  
   159  type testChain struct {
   160  	*testBlockChain
   161  	address common.Address
   162  	trigger *bool
   163  }
   164  
   165  // testChain.State() is used multiple times to reset the pending state.
   166  // when simulate is true it will create a state that indicates
   167  // that tx0 and tx1 are included in the chain.
   168  func (c *testChain) State() (*state.StateDB, error) {
   169  	// delay "state change" by one. The tx pool fetches the
   170  	// state multiple times and by delaying it a bit we simulate
   171  	// a state change between those fetches.
   172  	stdb := c.statedb
   173  	if *c.trigger {
   174  		c.statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   175  		// simulate that the new head block included tx0 and tx1
   176  		c.statedb.SetNonce(c.address, 2)
   177  		c.statedb.SetBalance(c.address, new(big.Int).SetUint64(params.Ether))
   178  		*c.trigger = false
   179  	}
   180  	return stdb, nil
   181  }
   182  
   183  // This test simulates a scenario where a new block is imported during a
   184  // state reset and tests whether the pending state is in sync with the
   185  // block head event that initiated the resetState().
   186  func TestStateChangeDuringTransactionPoolReset(t *testing.T) {
   187  	t.Parallel()
   188  
   189  	var (
   190  		key, _     = crypto.GenerateKey()
   191  		address    = crypto.PubkeyToAddress(key.PublicKey)
   192  		statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   193  		trigger    = false
   194  	)
   195  
   196  	// setup pool with 2 transaction in it
   197  	statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
   198  	blockchain := &testChain{&testBlockChain{statedb, 1000000000, new(event.Feed)}, address, &trigger}
   199  
   200  	tx0 := transaction(0, 100000, key)
   201  	tx1 := transaction(1, 100000, key)
   202  
   203  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
   204  	defer pool.Stop()
   205  
   206  	nonce := pool.Nonce(address)
   207  	if nonce != 0 {
   208  		t.Fatalf("Invalid nonce, want 0, got %d", nonce)
   209  	}
   210  
   211  	pool.AddRemotesSync([]*types.Transaction{tx0, tx1})
   212  
   213  	nonce = pool.Nonce(address)
   214  	if nonce != 2 {
   215  		t.Fatalf("Invalid nonce, want 2, got %d", nonce)
   216  	}
   217  
   218  	// trigger state change in the background
   219  	trigger = true
   220  	<-pool.requestReset(nil, nil)
   221  
   222  	_, err := pool.Pending()
   223  	if err != nil {
   224  		t.Fatalf("Could not fetch pending transactions: %v", err)
   225  	}
   226  	nonce = pool.Nonce(address)
   227  	if nonce != 2 {
   228  		t.Fatalf("Invalid nonce, want 2, got %d", nonce)
   229  	}
   230  }
   231  
   232  func TestInvalidTransactions(t *testing.T) {
   233  	t.Parallel()
   234  
   235  	pool, key := setupTxPool()
   236  	defer pool.Stop()
   237  
   238  	tx := transaction(0, 100, key)
   239  	from, _ := deriveSender(tx)
   240  
   241  	pool.currentState.AddBalance(from, big.NewInt(1))
   242  	if err := pool.AddRemote(tx); err != ErrInsufficientFunds {
   243  		t.Error("expected", ErrInsufficientFunds)
   244  	}
   245  
   246  	balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(new(big.Int).SetUint64(tx.Gas()), tx.GasPrice()))
   247  	pool.currentState.AddBalance(from, balance)
   248  	if err := pool.AddRemote(tx); err != ErrIntrinsicGas {
   249  		t.Error("expected", ErrIntrinsicGas, "got", err)
   250  	}
   251  
   252  	pool.currentState.SetNonce(from, 1)
   253  	pool.currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
   254  	tx = transaction(0, 100000, key)
   255  	if err := pool.AddRemote(tx); err != ErrNonceTooLow {
   256  		t.Error("expected", ErrNonceTooLow)
   257  	}
   258  
   259  	tx = transaction(1, 100000, key)
   260  	pool.gasPrice = big.NewInt(1000)
   261  	if err := pool.AddRemote(tx); err != ErrUnderpriced {
   262  		t.Error("expected", ErrUnderpriced, "got", err)
   263  	}
   264  	if err := pool.AddLocal(tx); err != nil {
   265  		t.Error("expected", nil, "got", err)
   266  	}
   267  }
   268  
   269  func TestTransactionQueue(t *testing.T) {
   270  	t.Parallel()
   271  
   272  	pool, key := setupTxPool()
   273  	defer pool.Stop()
   274  
   275  	tx := transaction(0, 100, key)
   276  	from, _ := deriveSender(tx)
   277  	pool.currentState.AddBalance(from, big.NewInt(1000))
   278  	<-pool.requestReset(nil, nil)
   279  
   280  	pool.enqueueTx(tx.Hash(), tx)
   281  	<-pool.requestPromoteExecutables(newAccountSet(pool.signer, from))
   282  	if len(pool.pending) != 1 {
   283  		t.Error("expected valid txs to be 1 is", len(pool.pending))
   284  	}
   285  
   286  	tx = transaction(1, 100, key)
   287  	from, _ = deriveSender(tx)
   288  	pool.currentState.SetNonce(from, 2)
   289  	pool.enqueueTx(tx.Hash(), tx)
   290  
   291  	<-pool.requestPromoteExecutables(newAccountSet(pool.signer, from))
   292  	if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok {
   293  		t.Error("expected transaction to be in tx pool")
   294  	}
   295  	if len(pool.queue) > 0 {
   296  		t.Error("expected transaction queue to be empty. is", len(pool.queue))
   297  	}
   298  }
   299  
   300  func TestTransactionQueue2(t *testing.T) {
   301  	t.Parallel()
   302  
   303  	pool, key := setupTxPool()
   304  	defer pool.Stop()
   305  
   306  	tx1 := transaction(0, 100, key)
   307  	tx2 := transaction(10, 100, key)
   308  	tx3 := transaction(11, 100, key)
   309  	from, _ := deriveSender(tx1)
   310  	pool.currentState.AddBalance(from, big.NewInt(1000))
   311  	pool.reset(nil, nil)
   312  
   313  	pool.enqueueTx(tx1.Hash(), tx1)
   314  	pool.enqueueTx(tx2.Hash(), tx2)
   315  	pool.enqueueTx(tx3.Hash(), tx3)
   316  
   317  	pool.promoteExecutables([]common.Address{from})
   318  	if len(pool.pending) != 1 {
   319  		t.Error("expected pending length to be 1, got", len(pool.pending))
   320  	}
   321  	if pool.queue[from].Len() != 2 {
   322  		t.Error("expected len(queue) == 2, got", pool.queue[from].Len())
   323  	}
   324  }
   325  
   326  func TestTransactionNegativeValue(t *testing.T) {
   327  	t.Parallel()
   328  
   329  	pool, key := setupTxPool()
   330  	defer pool.Stop()
   331  
   332  	tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(-1), 100, big.NewInt(1), nil), types.HomesteadSigner{}, key)
   333  	from, _ := deriveSender(tx)
   334  	pool.currentState.AddBalance(from, big.NewInt(1))
   335  	if err := pool.AddRemote(tx); err != ErrNegativeValue {
   336  		t.Error("expected", ErrNegativeValue, "got", err)
   337  	}
   338  }
   339  
   340  func TestTransactionChainFork(t *testing.T) {
   341  	t.Parallel()
   342  
   343  	pool, key := setupTxPool()
   344  	defer pool.Stop()
   345  
   346  	addr := crypto.PubkeyToAddress(key.PublicKey)
   347  	resetState := func() {
   348  		statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   349  		statedb.AddBalance(addr, big.NewInt(100000000000000))
   350  
   351  		pool.chain = &testBlockChain{statedb, 1000000, new(event.Feed)}
   352  		<-pool.requestReset(nil, nil)
   353  	}
   354  	resetState()
   355  
   356  	tx := transaction(0, 100000, key)
   357  	if _, err := pool.add(tx, false); err != nil {
   358  		t.Error("didn't expect error", err)
   359  	}
   360  	pool.removeTx(tx.Hash(), true)
   361  
   362  	// reset the pool's internal state
   363  	resetState()
   364  	if _, err := pool.add(tx, false); err != nil {
   365  		t.Error("didn't expect error", err)
   366  	}
   367  }
   368  
   369  func TestTransactionDoubleNonce(t *testing.T) {
   370  	t.Parallel()
   371  
   372  	pool, key := setupTxPool()
   373  	defer pool.Stop()
   374  
   375  	addr := crypto.PubkeyToAddress(key.PublicKey)
   376  	resetState := func() {
   377  		statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   378  		statedb.AddBalance(addr, big.NewInt(100000000000000))
   379  
   380  		pool.chain = &testBlockChain{statedb, 1000000, new(event.Feed)}
   381  		<-pool.requestReset(nil, nil)
   382  	}
   383  	resetState()
   384  
   385  	signer := types.HomesteadSigner{}
   386  	tx1, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100000, big.NewInt(1), nil), signer, key)
   387  	tx2, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(2), nil), signer, key)
   388  	tx3, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(1), nil), signer, key)
   389  
   390  	// Add the first two transaction, ensure higher priced stays only
   391  	if replace, err := pool.add(tx1, false); err != nil || replace {
   392  		t.Errorf("first transaction insert failed (%v) or reported replacement (%v)", err, replace)
   393  	}
   394  	if replace, err := pool.add(tx2, false); err != nil || !replace {
   395  		t.Errorf("second transaction insert failed (%v) or not reported replacement (%v)", err, replace)
   396  	}
   397  	<-pool.requestPromoteExecutables(newAccountSet(signer, addr))
   398  	if pool.pending[addr].Len() != 1 {
   399  		t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
   400  	}
   401  	if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
   402  		t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
   403  	}
   404  
   405  	// Add the third transaction and ensure it's not saved (smaller price)
   406  	pool.add(tx3, false)
   407  	<-pool.requestPromoteExecutables(newAccountSet(signer, addr))
   408  	if pool.pending[addr].Len() != 1 {
   409  		t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
   410  	}
   411  	if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
   412  		t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
   413  	}
   414  	// Ensure the total transaction count is correct
   415  	if pool.all.Count() != 1 {
   416  		t.Error("expected 1 total transactions, got", pool.all.Count())
   417  	}
   418  }
   419  
   420  func TestTransactionMissingNonce(t *testing.T) {
   421  	t.Parallel()
   422  
   423  	pool, key := setupTxPool()
   424  	defer pool.Stop()
   425  
   426  	addr := crypto.PubkeyToAddress(key.PublicKey)
   427  	pool.currentState.AddBalance(addr, big.NewInt(100000000000000))
   428  	tx := transaction(1, 100000, key)
   429  	if _, err := pool.add(tx, false); err != nil {
   430  		t.Error("didn't expect error", err)
   431  	}
   432  	if len(pool.pending) != 0 {
   433  		t.Error("expected 0 pending transactions, got", len(pool.pending))
   434  	}
   435  	if pool.queue[addr].Len() != 1 {
   436  		t.Error("expected 1 queued transaction, got", pool.queue[addr].Len())
   437  	}
   438  	if pool.all.Count() != 1 {
   439  		t.Error("expected 1 total transactions, got", pool.all.Count())
   440  	}
   441  }
   442  
   443  func TestTransactionNonceRecovery(t *testing.T) {
   444  	t.Parallel()
   445  
   446  	const n = 10
   447  	pool, key := setupTxPool()
   448  	defer pool.Stop()
   449  
   450  	addr := crypto.PubkeyToAddress(key.PublicKey)
   451  	pool.currentState.SetNonce(addr, n)
   452  	pool.currentState.AddBalance(addr, big.NewInt(100000000000000))
   453  	<-pool.requestReset(nil, nil)
   454  
   455  	tx := transaction(n, 100000, key)
   456  	if err := pool.AddRemote(tx); err != nil {
   457  		t.Error(err)
   458  	}
   459  	// simulate some weird re-order of transactions and missing nonce(s)
   460  	pool.currentState.SetNonce(addr, n-1)
   461  	<-pool.requestReset(nil, nil)
   462  	if fn := pool.Nonce(addr); fn != n-1 {
   463  		t.Errorf("expected nonce to be %d, got %d", n-1, fn)
   464  	}
   465  }
   466  
   467  // Tests that if an account runs out of funds, any pending and queued transactions
   468  // are dropped.
   469  func TestTransactionDropping(t *testing.T) {
   470  	t.Parallel()
   471  
   472  	// Create a test account and fund it
   473  	pool, key := setupTxPool()
   474  	defer pool.Stop()
   475  
   476  	account := crypto.PubkeyToAddress(key.PublicKey)
   477  	pool.currentState.AddBalance(account, big.NewInt(1000))
   478  
   479  	// Add some pending and some queued transactions
   480  	var (
   481  		tx0  = transaction(0, 100, key)
   482  		tx1  = transaction(1, 200, key)
   483  		tx2  = transaction(2, 300, key)
   484  		tx10 = transaction(10, 100, key)
   485  		tx11 = transaction(11, 200, key)
   486  		tx12 = transaction(12, 300, key)
   487  	)
   488  	pool.promoteTx(account, tx0.Hash(), tx0)
   489  	pool.promoteTx(account, tx1.Hash(), tx1)
   490  	pool.promoteTx(account, tx2.Hash(), tx2)
   491  	pool.enqueueTx(tx10.Hash(), tx10)
   492  	pool.enqueueTx(tx11.Hash(), tx11)
   493  	pool.enqueueTx(tx12.Hash(), tx12)
   494  
   495  	// Check that pre and post validations leave the pool as is
   496  	if pool.pending[account].Len() != 3 {
   497  		t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3)
   498  	}
   499  	if pool.queue[account].Len() != 3 {
   500  		t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3)
   501  	}
   502  	if pool.all.Count() != 6 {
   503  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6)
   504  	}
   505  	<-pool.requestReset(nil, nil)
   506  	if pool.pending[account].Len() != 3 {
   507  		t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3)
   508  	}
   509  	if pool.queue[account].Len() != 3 {
   510  		t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3)
   511  	}
   512  	if pool.all.Count() != 6 {
   513  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6)
   514  	}
   515  	// Reduce the balance of the account, and check that invalidated transactions are dropped
   516  	pool.currentState.AddBalance(account, big.NewInt(-650))
   517  	<-pool.requestReset(nil, nil)
   518  
   519  	if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
   520  		t.Errorf("funded pending transaction missing: %v", tx0)
   521  	}
   522  	if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; !ok {
   523  		t.Errorf("funded pending transaction missing: %v", tx0)
   524  	}
   525  	if _, ok := pool.pending[account].txs.items[tx2.Nonce()]; ok {
   526  		t.Errorf("out-of-fund pending transaction present: %v", tx1)
   527  	}
   528  	if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
   529  		t.Errorf("funded queued transaction missing: %v", tx10)
   530  	}
   531  	if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; !ok {
   532  		t.Errorf("funded queued transaction missing: %v", tx10)
   533  	}
   534  	if _, ok := pool.queue[account].txs.items[tx12.Nonce()]; ok {
   535  		t.Errorf("out-of-fund queued transaction present: %v", tx11)
   536  	}
   537  	if pool.all.Count() != 4 {
   538  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 4)
   539  	}
   540  	// Reduce the block gas limit, check that invalidated transactions are dropped
   541  	pool.chain.(*testBlockChain).gasLimit = 100
   542  	<-pool.requestReset(nil, nil)
   543  
   544  	if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
   545  		t.Errorf("funded pending transaction missing: %v", tx0)
   546  	}
   547  	if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok {
   548  		t.Errorf("over-gased pending transaction present: %v", tx1)
   549  	}
   550  	if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
   551  		t.Errorf("funded queued transaction missing: %v", tx10)
   552  	}
   553  	if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok {
   554  		t.Errorf("over-gased queued transaction present: %v", tx11)
   555  	}
   556  	if pool.all.Count() != 2 {
   557  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 2)
   558  	}
   559  }
   560  
   561  // Tests that if a transaction is dropped from the current pending pool (e.g. out
   562  // of fund), all consecutive (still valid, but not executable) transactions are
   563  // postponed back into the future queue to prevent broadcasting them.
   564  func TestTransactionPostponing(t *testing.T) {
   565  	t.Parallel()
   566  
   567  	// Create the pool to test the postponing with
   568  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   569  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
   570  
   571  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
   572  	defer pool.Stop()
   573  
   574  	// Create two test accounts to produce different gap profiles with
   575  	keys := make([]*ecdsa.PrivateKey, 2)
   576  	accs := make([]common.Address, len(keys))
   577  
   578  	for i := 0; i < len(keys); i++ {
   579  		keys[i], _ = crypto.GenerateKey()
   580  		accs[i] = crypto.PubkeyToAddress(keys[i].PublicKey)
   581  
   582  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(50100))
   583  	}
   584  	// Add a batch consecutive pending transactions for validation
   585  	txs := []*types.Transaction{}
   586  	for i, key := range keys {
   587  
   588  		for j := 0; j < 100; j++ {
   589  			var tx *types.Transaction
   590  			if (i+j)%2 == 0 {
   591  				tx = transaction(uint64(j), 25000, key)
   592  			} else {
   593  				tx = transaction(uint64(j), 50000, key)
   594  			}
   595  			txs = append(txs, tx)
   596  		}
   597  	}
   598  	for i, err := range pool.AddRemotesSync(txs) {
   599  		if err != nil {
   600  			t.Fatalf("tx %d: failed to add transactions: %v", i, err)
   601  		}
   602  	}
   603  	// Check that pre and post validations leave the pool as is
   604  	if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) {
   605  		t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs))
   606  	}
   607  	if len(pool.queue) != 0 {
   608  		t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0)
   609  	}
   610  	if pool.all.Count() != len(txs) {
   611  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs))
   612  	}
   613  	<-pool.requestReset(nil, nil)
   614  	if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) {
   615  		t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs))
   616  	}
   617  	if len(pool.queue) != 0 {
   618  		t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0)
   619  	}
   620  	if pool.all.Count() != len(txs) {
   621  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs))
   622  	}
   623  	// Reduce the balance of the account, and check that transactions are reorganised
   624  	for _, addr := range accs {
   625  		pool.currentState.AddBalance(addr, big.NewInt(-1))
   626  	}
   627  	<-pool.requestReset(nil, nil)
   628  
   629  	// The first account's first transaction remains valid, check that subsequent
   630  	// ones are either filtered out, or queued up for later.
   631  	if _, ok := pool.pending[accs[0]].txs.items[txs[0].Nonce()]; !ok {
   632  		t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txs[0])
   633  	}
   634  	if _, ok := pool.queue[accs[0]].txs.items[txs[0].Nonce()]; ok {
   635  		t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txs[0])
   636  	}
   637  	for i, tx := range txs[1:100] {
   638  		if i%2 == 1 {
   639  			if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok {
   640  				t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx)
   641  			}
   642  			if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; !ok {
   643  				t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx)
   644  			}
   645  		} else {
   646  			if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok {
   647  				t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx)
   648  			}
   649  			if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; ok {
   650  				t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx)
   651  			}
   652  		}
   653  	}
   654  	// The second account's first transaction got invalid, check that all transactions
   655  	// are either filtered out, or queued up for later.
   656  	if pool.pending[accs[1]] != nil {
   657  		t.Errorf("invalidated account still has pending transactions")
   658  	}
   659  	for i, tx := range txs[100:] {
   660  		if i%2 == 1 {
   661  			if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; !ok {
   662  				t.Errorf("tx %d: valid but future transaction missing from future queue: %v", 100+i, tx)
   663  			}
   664  		} else {
   665  			if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; ok {
   666  				t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", 100+i, tx)
   667  			}
   668  		}
   669  	}
   670  	if pool.all.Count() != len(txs)/2 {
   671  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs)/2)
   672  	}
   673  }
   674  
   675  // Tests that if the transaction pool has both executable and non-executable
   676  // transactions from an origin account, filling the nonce gap moves all queued
   677  // ones into the pending pool.
   678  func TestTransactionGapFilling(t *testing.T) {
   679  	t.Parallel()
   680  
   681  	// Create a test account and fund it
   682  	pool, key := setupTxPool()
   683  	defer pool.Stop()
   684  
   685  	account := crypto.PubkeyToAddress(key.PublicKey)
   686  	pool.currentState.AddBalance(account, big.NewInt(1000000))
   687  
   688  	// Keep track of transaction events to ensure all executables get announced
   689  	events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
   690  	sub := pool.txFeed.Subscribe(events)
   691  	defer sub.Unsubscribe()
   692  
   693  	// Create a pending and a queued transaction with a nonce-gap in between
   694  	pool.AddRemotesSync([]*types.Transaction{
   695  		transaction(0, 100000, key),
   696  		transaction(2, 100000, key),
   697  	})
   698  	pending, queued := pool.Stats()
   699  	if pending != 1 {
   700  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1)
   701  	}
   702  	if queued != 1 {
   703  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
   704  	}
   705  	if err := validateEvents(events, 1); err != nil {
   706  		t.Fatalf("original event firing failed: %v", err)
   707  	}
   708  	if err := validateTxPoolInternals(pool); err != nil {
   709  		t.Fatalf("pool internal state corrupted: %v", err)
   710  	}
   711  	// Fill the nonce gap and ensure all transactions become pending
   712  	if err := pool.addRemoteSync(transaction(1, 100000, key)); err != nil {
   713  		t.Fatalf("failed to add gapped transaction: %v", err)
   714  	}
   715  	pending, queued = pool.Stats()
   716  	if pending != 3 {
   717  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
   718  	}
   719  	if queued != 0 {
   720  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
   721  	}
   722  	if err := validateEvents(events, 2); err != nil {
   723  		t.Fatalf("gap-filling event firing failed: %v", err)
   724  	}
   725  	if err := validateTxPoolInternals(pool); err != nil {
   726  		t.Fatalf("pool internal state corrupted: %v", err)
   727  	}
   728  }
   729  
   730  // Tests that if the transaction count belonging to a single account goes above
   731  // some threshold, the higher transactions are dropped to prevent DOS attacks.
   732  func TestTransactionQueueAccountLimiting(t *testing.T) {
   733  	t.Parallel()
   734  
   735  	// Create a test account and fund it
   736  	pool, key := setupTxPool()
   737  	defer pool.Stop()
   738  
   739  	account := crypto.PubkeyToAddress(key.PublicKey)
   740  	pool.currentState.AddBalance(account, big.NewInt(1000000))
   741  
   742  	// Keep queuing up transactions and make sure all above a limit are dropped
   743  	for i := uint64(1); i <= testTxPoolConfig.AccountQueue+5; i++ {
   744  		if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil {
   745  			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
   746  		}
   747  		if len(pool.pending) != 0 {
   748  			t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0)
   749  		}
   750  		if i <= testTxPoolConfig.AccountQueue {
   751  			if pool.queue[account].Len() != int(i) {
   752  				t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i)
   753  			}
   754  		} else {
   755  			if pool.queue[account].Len() != int(testTxPoolConfig.AccountQueue) {
   756  				t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), testTxPoolConfig.AccountQueue)
   757  			}
   758  		}
   759  	}
   760  	if pool.all.Count() != int(testTxPoolConfig.AccountQueue) {
   761  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue)
   762  	}
   763  }
   764  
   765  // Tests that if the transaction count belonging to multiple accounts go above
   766  // some threshold, the higher transactions are dropped to prevent DOS attacks.
   767  //
   768  // This logic should not hold for local transactions, unless the local tracking
   769  // mechanism is disabled.
   770  func TestTransactionQueueGlobalLimiting(t *testing.T) {
   771  	testTransactionQueueGlobalLimiting(t, false)
   772  }
   773  func TestTransactionQueueGlobalLimitingNoLocals(t *testing.T) {
   774  	testTransactionQueueGlobalLimiting(t, true)
   775  }
   776  
   777  func testTransactionQueueGlobalLimiting(t *testing.T, nolocals bool) {
   778  	t.Parallel()
   779  
   780  	// Create the pool to test the limit enforcement with
   781  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   782  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
   783  
   784  	config := testTxPoolConfig
   785  	config.NoLocals = nolocals
   786  	config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible)
   787  
   788  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
   789  	defer pool.Stop()
   790  
   791  	// Create a number of test accounts and fund them (last one will be the local)
   792  	keys := make([]*ecdsa.PrivateKey, 5)
   793  	for i := 0; i < len(keys); i++ {
   794  		keys[i], _ = crypto.GenerateKey()
   795  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
   796  	}
   797  	local := keys[len(keys)-1]
   798  
   799  	// Generate and queue a batch of transactions
   800  	nonces := make(map[common.Address]uint64)
   801  
   802  	txs := make(types.Transactions, 0, 3*config.GlobalQueue)
   803  	for len(txs) < cap(txs) {
   804  		key := keys[rand.Intn(len(keys)-1)] // skip adding transactions with the local account
   805  		addr := crypto.PubkeyToAddress(key.PublicKey)
   806  
   807  		txs = append(txs, transaction(nonces[addr]+1, 100000, key))
   808  		nonces[addr]++
   809  	}
   810  	// Import the batch and verify that limits have been enforced
   811  	pool.AddRemotesSync(txs)
   812  
   813  	queued := 0
   814  	for addr, list := range pool.queue {
   815  		if list.Len() > int(config.AccountQueue) {
   816  			t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue)
   817  		}
   818  		queued += list.Len()
   819  	}
   820  	if queued > int(config.GlobalQueue) {
   821  		t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue)
   822  	}
   823  	// Generate a batch of transactions from the local account and import them
   824  	txs = txs[:0]
   825  	for i := uint64(0); i < 3*config.GlobalQueue; i++ {
   826  		txs = append(txs, transaction(i+1, 100000, local))
   827  	}
   828  	pool.AddLocals(txs)
   829  
   830  	// If locals are disabled, the previous eviction algorithm should apply here too
   831  	if nolocals {
   832  		queued := 0
   833  		for addr, list := range pool.queue {
   834  			if list.Len() > int(config.AccountQueue) {
   835  				t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue)
   836  			}
   837  			queued += list.Len()
   838  		}
   839  		if queued > int(config.GlobalQueue) {
   840  			t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue)
   841  		}
   842  	} else {
   843  		// Local exemptions are enabled, make sure the local account owned the queue
   844  		if len(pool.queue) != 1 {
   845  			t.Errorf("multiple accounts in queue: have %v, want %v", len(pool.queue), 1)
   846  		}
   847  		// Also ensure no local transactions are ever dropped, even if above global limits
   848  		if queued := pool.queue[crypto.PubkeyToAddress(local.PublicKey)].Len(); uint64(queued) != 3*config.GlobalQueue {
   849  			t.Fatalf("local account queued transaction count mismatch: have %v, want %v", queued, 3*config.GlobalQueue)
   850  		}
   851  	}
   852  }
   853  
   854  // Tests that if an account remains idle for a prolonged amount of time, any
   855  // non-executable transactions queued up are dropped to prevent wasting resources
   856  // on shuffling them around.
   857  //
   858  // This logic should not hold for local transactions, unless the local tracking
   859  // mechanism is disabled.
   860  func TestTransactionQueueTimeLimiting(t *testing.T) {
   861  	testTransactionQueueTimeLimiting(t, false)
   862  }
   863  func TestTransactionQueueTimeLimitingNoLocals(t *testing.T) {
   864  	testTransactionQueueTimeLimiting(t, true)
   865  }
   866  
   867  func testTransactionQueueTimeLimiting(t *testing.T, nolocals bool) {
   868  	// Reduce the eviction interval to a testable amount
   869  	defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
   870  	evictionInterval = time.Second
   871  
   872  	// Create the pool to test the non-expiration enforcement
   873  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   874  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
   875  
   876  	config := testTxPoolConfig
   877  	config.Lifetime = time.Second
   878  	config.NoLocals = nolocals
   879  
   880  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
   881  	defer pool.Stop()
   882  
   883  	// Create two test accounts to ensure remotes expire but locals do not
   884  	local, _ := crypto.GenerateKey()
   885  	remote, _ := crypto.GenerateKey()
   886  
   887  	pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
   888  	pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))
   889  
   890  	// Add the two transactions and ensure they both are queued up
   891  	if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
   892  		t.Fatalf("failed to add local transaction: %v", err)
   893  	}
   894  	if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), remote)); err != nil {
   895  		t.Fatalf("failed to add remote transaction: %v", err)
   896  	}
   897  	pending, queued := pool.Stats()
   898  	if pending != 0 {
   899  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
   900  	}
   901  	if queued != 2 {
   902  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
   903  	}
   904  	if err := validateTxPoolInternals(pool); err != nil {
   905  		t.Fatalf("pool internal state corrupted: %v", err)
   906  	}
   907  	// Wait a bit for eviction to run and clean up any leftovers, and ensure only the local remains
   908  	time.Sleep(2 * config.Lifetime)
   909  
   910  	pending, queued = pool.Stats()
   911  	if pending != 0 {
   912  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
   913  	}
   914  	if nolocals {
   915  		if queued != 0 {
   916  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
   917  		}
   918  	} else {
   919  		if queued != 1 {
   920  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
   921  		}
   922  	}
   923  	if err := validateTxPoolInternals(pool); err != nil {
   924  		t.Fatalf("pool internal state corrupted: %v", err)
   925  	}
   926  }
   927  
   928  // Tests that even if the transaction count belonging to a single account goes
   929  // above some threshold, as long as the transactions are executable, they are
   930  // accepted.
   931  func TestTransactionPendingLimiting(t *testing.T) {
   932  	t.Parallel()
   933  
   934  	// Create a test account and fund it
   935  	pool, key := setupTxPool()
   936  	defer pool.Stop()
   937  
   938  	account := crypto.PubkeyToAddress(key.PublicKey)
   939  	pool.currentState.AddBalance(account, big.NewInt(1000000))
   940  
   941  	// Keep track of transaction events to ensure all executables get announced
   942  	events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
   943  	sub := pool.txFeed.Subscribe(events)
   944  	defer sub.Unsubscribe()
   945  
   946  	// Keep queuing up transactions and make sure all above a limit are dropped
   947  	for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ {
   948  		if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil {
   949  			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
   950  		}
   951  		if pool.pending[account].Len() != int(i)+1 {
   952  			t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1)
   953  		}
   954  		if len(pool.queue) != 0 {
   955  			t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
   956  		}
   957  	}
   958  	if pool.all.Count() != int(testTxPoolConfig.AccountQueue+5) {
   959  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue+5)
   960  	}
   961  	if err := validateEvents(events, int(testTxPoolConfig.AccountQueue+5)); err != nil {
   962  		t.Fatalf("event firing failed: %v", err)
   963  	}
   964  	if err := validateTxPoolInternals(pool); err != nil {
   965  		t.Fatalf("pool internal state corrupted: %v", err)
   966  	}
   967  }
   968  
   969  // Tests that if the transaction count belonging to multiple accounts go above
   970  // some hard threshold, the higher transactions are dropped to prevent DOS
   971  // attacks.
   972  func TestTransactionPendingGlobalLimiting(t *testing.T) {
   973  	t.Parallel()
   974  
   975  	// Create the pool to test the limit enforcement with
   976  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   977  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
   978  
   979  	config := testTxPoolConfig
   980  	config.GlobalSlots = config.AccountSlots * 10
   981  
   982  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
   983  	defer pool.Stop()
   984  
   985  	// Create a number of test accounts and fund them
   986  	keys := make([]*ecdsa.PrivateKey, 5)
   987  	for i := 0; i < len(keys); i++ {
   988  		keys[i], _ = crypto.GenerateKey()
   989  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
   990  	}
   991  	// Generate and queue a batch of transactions
   992  	nonces := make(map[common.Address]uint64)
   993  
   994  	txs := types.Transactions{}
   995  	for _, key := range keys {
   996  		addr := crypto.PubkeyToAddress(key.PublicKey)
   997  		for j := 0; j < int(config.GlobalSlots)/len(keys)*2; j++ {
   998  			txs = append(txs, transaction(nonces[addr], 100000, key))
   999  			nonces[addr]++
  1000  		}
  1001  	}
  1002  	// Import the batch and verify that limits have been enforced
  1003  	pool.AddRemotesSync(txs)
  1004  
  1005  	pending := 0
  1006  	for _, list := range pool.pending {
  1007  		pending += list.Len()
  1008  	}
  1009  	if pending > int(config.GlobalSlots) {
  1010  		t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, config.GlobalSlots)
  1011  	}
  1012  	if err := validateTxPoolInternals(pool); err != nil {
  1013  		t.Fatalf("pool internal state corrupted: %v", err)
  1014  	}
  1015  }
  1016  
  1017  // Test the limit on transaction size is enforced correctly.
  1018  // This test verifies every transaction having allowed size
  1019  // is added to the pool, and longer transactions are rejected.
  1020  func TestTransactionAllowedTxSize(t *testing.T) {
  1021  	t.Parallel()
  1022  
  1023  	// Create a test account and fund it
  1024  	pool, key := setupTxPool()
  1025  	defer pool.Stop()
  1026  
  1027  	account := crypto.PubkeyToAddress(key.PublicKey)
  1028  	pool.currentState.AddBalance(account, big.NewInt(1000000000))
  1029  
  1030  	// Compute maximal data size for transactions (lower bound).
  1031  	//
  1032  	// It is assumed the fields in the transaction (except of the data) are:
  1033  	//   - nonce     <= 32 bytes
  1034  	//   - gasPrice  <= 32 bytes
  1035  	//   - gasLimit  <= 32 bytes
  1036  	//   - recipient == 20 bytes
  1037  	//   - value     <= 32 bytes
  1038  	//   - signature == 65 bytes
  1039  	// All those fields are summed up to at most 213 bytes.
  1040  	baseSize := uint64(213)
  1041  	dataSize := txMaxSize - baseSize
  1042  
  1043  	// Try adding a transaction with maximal allowed size
  1044  	tx := pricedDataTransaction(0, pool.currentMaxGas, big.NewInt(1), key, dataSize)
  1045  	if err := pool.addRemoteSync(tx); err != nil {
  1046  		t.Fatalf("failed to add transaction of size %d, close to maximal: %v", int(tx.Size()), err)
  1047  	}
  1048  	// Try adding a transaction with random allowed size
  1049  	if err := pool.addRemoteSync(pricedDataTransaction(1, pool.currentMaxGas, big.NewInt(1), key, uint64(rand.Intn(int(dataSize))))); err != nil {
  1050  		t.Fatalf("failed to add transaction of random allowed size: %v", err)
  1051  	}
  1052  	// Try adding a transaction of minimal not allowed size
  1053  	if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, txMaxSize)); err == nil {
  1054  		t.Fatalf("expected rejection on slightly oversize transaction")
  1055  	}
  1056  	// Try adding a transaction of random not allowed size
  1057  	if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, dataSize+1+uint64(rand.Intn(int(10*txMaxSize))))); err == nil {
  1058  		t.Fatalf("expected rejection on oversize transaction")
  1059  	}
  1060  	// Run some sanity checks on the pool internals
  1061  	pending, queued := pool.Stats()
  1062  	if pending != 2 {
  1063  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1064  	}
  1065  	if queued != 0 {
  1066  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1067  	}
  1068  	if err := validateTxPoolInternals(pool); err != nil {
  1069  		t.Fatalf("pool internal state corrupted: %v", err)
  1070  	}
  1071  }
  1072  
  1073  // Tests that if transactions start being capped, transactions are also removed from 'all'
  1074  func TestTransactionCapClearsFromAll(t *testing.T) {
  1075  	t.Parallel()
  1076  
  1077  	// Create the pool to test the limit enforcement with
  1078  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1079  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1080  
  1081  	config := testTxPoolConfig
  1082  	config.AccountSlots = 2
  1083  	config.AccountQueue = 2
  1084  	config.GlobalSlots = 8
  1085  
  1086  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1087  	defer pool.Stop()
  1088  
  1089  	// Create a number of test accounts and fund them
  1090  	key, _ := crypto.GenerateKey()
  1091  	addr := crypto.PubkeyToAddress(key.PublicKey)
  1092  	pool.currentState.AddBalance(addr, big.NewInt(1000000))
  1093  
  1094  	txs := types.Transactions{}
  1095  	for j := 0; j < int(config.GlobalSlots)*2; j++ {
  1096  		txs = append(txs, transaction(uint64(j), 100000, key))
  1097  	}
  1098  	// Import the batch and verify that limits have been enforced
  1099  	pool.AddRemotes(txs)
  1100  	if err := validateTxPoolInternals(pool); err != nil {
  1101  		t.Fatalf("pool internal state corrupted: %v", err)
  1102  	}
  1103  }
  1104  
  1105  // Tests that if the transaction count belonging to multiple accounts go above
  1106  // some hard threshold, if they are under the minimum guaranteed slot count then
  1107  // the transactions are still kept.
  1108  func TestTransactionPendingMinimumAllowance(t *testing.T) {
  1109  	t.Parallel()
  1110  
  1111  	// Create the pool to test the limit enforcement with
  1112  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1113  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1114  
  1115  	config := testTxPoolConfig
  1116  	config.GlobalSlots = 1
  1117  
  1118  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1119  	defer pool.Stop()
  1120  
  1121  	// Create a number of test accounts and fund them
  1122  	keys := make([]*ecdsa.PrivateKey, 5)
  1123  	for i := 0; i < len(keys); i++ {
  1124  		keys[i], _ = crypto.GenerateKey()
  1125  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1126  	}
  1127  	// Generate and queue a batch of transactions
  1128  	nonces := make(map[common.Address]uint64)
  1129  
  1130  	txs := types.Transactions{}
  1131  	for _, key := range keys {
  1132  		addr := crypto.PubkeyToAddress(key.PublicKey)
  1133  		for j := 0; j < int(config.AccountSlots)*2; j++ {
  1134  			txs = append(txs, transaction(nonces[addr], 100000, key))
  1135  			nonces[addr]++
  1136  		}
  1137  	}
  1138  	// Import the batch and verify that limits have been enforced
  1139  	pool.AddRemotesSync(txs)
  1140  
  1141  	for addr, list := range pool.pending {
  1142  		if list.Len() != int(config.AccountSlots) {
  1143  			t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), config.AccountSlots)
  1144  		}
  1145  	}
  1146  	if err := validateTxPoolInternals(pool); err != nil {
  1147  		t.Fatalf("pool internal state corrupted: %v", err)
  1148  	}
  1149  }
  1150  
  1151  // Tests that setting the transaction pool gas price to a higher value correctly
  1152  // discards everything cheaper than that and moves any gapped transactions back
  1153  // from the pending pool to the queue.
  1154  //
  1155  // Note, local transactions are never allowed to be dropped.
  1156  func TestTransactionPoolRepricing(t *testing.T) {
  1157  	t.Parallel()
  1158  
  1159  	// Create the pool to test the pricing enforcement with
  1160  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1161  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1162  
  1163  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1164  	defer pool.Stop()
  1165  
  1166  	// Keep track of transaction events to ensure all executables get announced
  1167  	events := make(chan NewTxsEvent, 32)
  1168  	sub := pool.txFeed.Subscribe(events)
  1169  	defer sub.Unsubscribe()
  1170  
  1171  	// Create a number of test accounts and fund them
  1172  	keys := make([]*ecdsa.PrivateKey, 4)
  1173  	for i := 0; i < len(keys); i++ {
  1174  		keys[i], _ = crypto.GenerateKey()
  1175  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1176  	}
  1177  	// Generate and queue a batch of transactions, both pending and queued
  1178  	txs := types.Transactions{}
  1179  
  1180  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(2), keys[0]))
  1181  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[0]))
  1182  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[0]))
  1183  
  1184  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1]))
  1185  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[1]))
  1186  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[1]))
  1187  
  1188  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[2]))
  1189  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2]))
  1190  	txs = append(txs, pricedTransaction(3, 100000, big.NewInt(2), keys[2]))
  1191  
  1192  	ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[3])
  1193  
  1194  	// Import the batch and that both pending and queued transactions match up
  1195  	pool.AddRemotesSync(txs)
  1196  	pool.AddLocal(ltx)
  1197  
  1198  	pending, queued := pool.Stats()
  1199  	if pending != 7 {
  1200  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 7)
  1201  	}
  1202  	if queued != 3 {
  1203  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
  1204  	}
  1205  	if err := validateEvents(events, 7); err != nil {
  1206  		t.Fatalf("original event firing failed: %v", err)
  1207  	}
  1208  	if err := validateTxPoolInternals(pool); err != nil {
  1209  		t.Fatalf("pool internal state corrupted: %v", err)
  1210  	}
  1211  	// Reprice the pool and check that underpriced transactions get dropped
  1212  	pool.SetGasPrice(big.NewInt(2))
  1213  
  1214  	pending, queued = pool.Stats()
  1215  	if pending != 2 {
  1216  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1217  	}
  1218  	if queued != 5 {
  1219  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 5)
  1220  	}
  1221  	if err := validateEvents(events, 0); err != nil {
  1222  		t.Fatalf("reprice event firing failed: %v", err)
  1223  	}
  1224  	if err := validateTxPoolInternals(pool); err != nil {
  1225  		t.Fatalf("pool internal state corrupted: %v", err)
  1226  	}
  1227  	// Check that we can't add the old transactions back
  1228  	if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), keys[0])); err != ErrUnderpriced {
  1229  		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1230  	}
  1231  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
  1232  		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1233  	}
  1234  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), keys[2])); err != ErrUnderpriced {
  1235  		t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1236  	}
  1237  	if err := validateEvents(events, 0); err != nil {
  1238  		t.Fatalf("post-reprice event firing failed: %v", err)
  1239  	}
  1240  	if err := validateTxPoolInternals(pool); err != nil {
  1241  		t.Fatalf("pool internal state corrupted: %v", err)
  1242  	}
  1243  	// However we can add local underpriced transactions
  1244  	tx := pricedTransaction(1, 100000, big.NewInt(1), keys[3])
  1245  	if err := pool.AddLocal(tx); err != nil {
  1246  		t.Fatalf("failed to add underpriced local transaction: %v", err)
  1247  	}
  1248  	if pending, _ = pool.Stats(); pending != 3 {
  1249  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  1250  	}
  1251  	if err := validateEvents(events, 1); err != nil {
  1252  		t.Fatalf("post-reprice local event firing failed: %v", err)
  1253  	}
  1254  	if err := validateTxPoolInternals(pool); err != nil {
  1255  		t.Fatalf("pool internal state corrupted: %v", err)
  1256  	}
  1257  	// And we can fill gaps with properly priced transactions
  1258  	if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(2), keys[0])); err != nil {
  1259  		t.Fatalf("failed to add pending transaction: %v", err)
  1260  	}
  1261  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), keys[1])); err != nil {
  1262  		t.Fatalf("failed to add pending transaction: %v", err)
  1263  	}
  1264  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), keys[2])); err != nil {
  1265  		t.Fatalf("failed to add queued transaction: %v", err)
  1266  	}
  1267  	if err := validateEvents(events, 5); err != nil {
  1268  		t.Fatalf("post-reprice event firing failed: %v", err)
  1269  	}
  1270  	if err := validateTxPoolInternals(pool); err != nil {
  1271  		t.Fatalf("pool internal state corrupted: %v", err)
  1272  	}
  1273  }
  1274  
  1275  // Tests that setting the transaction pool gas price to a higher value does not
  1276  // remove local transactions.
  1277  func TestTransactionPoolRepricingKeepsLocals(t *testing.T) {
  1278  	t.Parallel()
  1279  
  1280  	// Create the pool to test the pricing enforcement with
  1281  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1282  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1283  
  1284  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1285  	defer pool.Stop()
  1286  
  1287  	// Create a number of test accounts and fund them
  1288  	keys := make([]*ecdsa.PrivateKey, 3)
  1289  	for i := 0; i < len(keys); i++ {
  1290  		keys[i], _ = crypto.GenerateKey()
  1291  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000*1000000))
  1292  	}
  1293  	// Create transaction (both pending and queued) with a linearly growing gasprice
  1294  	for i := uint64(0); i < 500; i++ {
  1295  		// Add pending transaction.
  1296  		pendingTx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2])
  1297  		if err := pool.AddLocal(pendingTx); err != nil {
  1298  			t.Fatal(err)
  1299  		}
  1300  		// Add queued transaction.
  1301  		queuedTx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2])
  1302  		if err := pool.AddLocal(queuedTx); err != nil {
  1303  			t.Fatal(err)
  1304  		}
  1305  	}
  1306  	pending, queued := pool.Stats()
  1307  	expPending, expQueued := 500, 500
  1308  	validate := func() {
  1309  		pending, queued = pool.Stats()
  1310  		if pending != expPending {
  1311  			t.Fatalf("pending transactions mismatched: have %d, want %d", pending, expPending)
  1312  		}
  1313  		if queued != expQueued {
  1314  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, expQueued)
  1315  		}
  1316  
  1317  		if err := validateTxPoolInternals(pool); err != nil {
  1318  			t.Fatalf("pool internal state corrupted: %v", err)
  1319  		}
  1320  	}
  1321  	validate()
  1322  
  1323  	// Reprice the pool and check that nothing is dropped
  1324  	pool.SetGasPrice(big.NewInt(2))
  1325  	validate()
  1326  
  1327  	pool.SetGasPrice(big.NewInt(2))
  1328  	pool.SetGasPrice(big.NewInt(4))
  1329  	pool.SetGasPrice(big.NewInt(8))
  1330  	pool.SetGasPrice(big.NewInt(100))
  1331  	validate()
  1332  }
  1333  
  1334  // Tests that when the pool reaches its global transaction limit, underpriced
  1335  // transactions are gradually shifted out for more expensive ones and any gapped
  1336  // pending transactions are moved into the queue.
  1337  //
  1338  // Note, local transactions are never allowed to be dropped.
  1339  func TestTransactionPoolUnderpricing(t *testing.T) {
  1340  	t.Parallel()
  1341  
  1342  	// Create the pool to test the pricing enforcement with
  1343  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1344  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1345  
  1346  	config := testTxPoolConfig
  1347  	config.GlobalSlots = 2
  1348  	config.GlobalQueue = 2
  1349  
  1350  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1351  	defer pool.Stop()
  1352  
  1353  	// Keep track of transaction events to ensure all executables get announced
  1354  	events := make(chan NewTxsEvent, 32)
  1355  	sub := pool.txFeed.Subscribe(events)
  1356  	defer sub.Unsubscribe()
  1357  
  1358  	// Create a number of test accounts and fund them
  1359  	keys := make([]*ecdsa.PrivateKey, 4)
  1360  	for i := 0; i < len(keys); i++ {
  1361  		keys[i], _ = crypto.GenerateKey()
  1362  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1363  	}
  1364  	// Generate and queue a batch of transactions, both pending and queued
  1365  	txs := types.Transactions{}
  1366  
  1367  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0]))
  1368  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[0]))
  1369  
  1370  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[1]))
  1371  
  1372  	ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[2])
  1373  
  1374  	// Import the batch and that both pending and queued transactions match up
  1375  	pool.AddRemotes(txs)
  1376  	pool.AddLocal(ltx)
  1377  
  1378  	pending, queued := pool.Stats()
  1379  	if pending != 3 {
  1380  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  1381  	}
  1382  	if queued != 1 {
  1383  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  1384  	}
  1385  	if err := validateEvents(events, 3); err != nil {
  1386  		t.Fatalf("original event firing failed: %v", err)
  1387  	}
  1388  	if err := validateTxPoolInternals(pool); err != nil {
  1389  		t.Fatalf("pool internal state corrupted: %v", err)
  1390  	}
  1391  	// Ensure that adding an underpriced transaction on block limit fails
  1392  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
  1393  		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1394  	}
  1395  	// Ensure that adding high priced transactions drops cheap ones, but not own
  1396  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil { // +K1:0 => -K1:1 => Pend K0:0, K0:1, K1:0, K2:0; Que -
  1397  		t.Fatalf("failed to add well priced transaction: %v", err)
  1398  	}
  1399  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(4), keys[1])); err != nil { // +K1:2 => -K0:0 => Pend K1:0, K2:0; Que K0:1 K1:2
  1400  		t.Fatalf("failed to add well priced transaction: %v", err)
  1401  	}
  1402  	if err := pool.AddRemote(pricedTransaction(3, 100000, big.NewInt(5), keys[1])); err != nil { // +K1:3 => -K0:1 => Pend K1:0, K2:0; Que K1:2 K1:3
  1403  		t.Fatalf("failed to add well priced transaction: %v", err)
  1404  	}
  1405  	pending, queued = pool.Stats()
  1406  	if pending != 2 {
  1407  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1408  	}
  1409  	if queued != 2 {
  1410  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
  1411  	}
  1412  	if err := validateEvents(events, 1); err != nil {
  1413  		t.Fatalf("additional event firing failed: %v", err)
  1414  	}
  1415  	if err := validateTxPoolInternals(pool); err != nil {
  1416  		t.Fatalf("pool internal state corrupted: %v", err)
  1417  	}
  1418  	// Ensure that adding local transactions can push out even higher priced ones
  1419  	ltx = pricedTransaction(1, 100000, big.NewInt(0), keys[2])
  1420  	if err := pool.AddLocal(ltx); err != nil {
  1421  		t.Fatalf("failed to append underpriced local transaction: %v", err)
  1422  	}
  1423  	ltx = pricedTransaction(0, 100000, big.NewInt(0), keys[3])
  1424  	if err := pool.AddLocal(ltx); err != nil {
  1425  		t.Fatalf("failed to add new underpriced local transaction: %v", err)
  1426  	}
  1427  	pending, queued = pool.Stats()
  1428  	if pending != 3 {
  1429  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  1430  	}
  1431  	if queued != 1 {
  1432  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  1433  	}
  1434  	if err := validateEvents(events, 2); err != nil {
  1435  		t.Fatalf("local event firing failed: %v", err)
  1436  	}
  1437  	if err := validateTxPoolInternals(pool); err != nil {
  1438  		t.Fatalf("pool internal state corrupted: %v", err)
  1439  	}
  1440  }
  1441  
  1442  // Tests that more expensive transactions push out cheap ones from the pool, but
  1443  // without producing instability by creating gaps that start jumping transactions
  1444  // back and forth between queued/pending.
  1445  func TestTransactionPoolStableUnderpricing(t *testing.T) {
  1446  	t.Parallel()
  1447  
  1448  	// Create the pool to test the pricing enforcement with
  1449  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1450  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1451  
  1452  	config := testTxPoolConfig
  1453  	config.GlobalSlots = 128
  1454  	config.GlobalQueue = 0
  1455  
  1456  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1457  	defer pool.Stop()
  1458  
  1459  	// Keep track of transaction events to ensure all executables get announced
  1460  	events := make(chan NewTxsEvent, 32)
  1461  	sub := pool.txFeed.Subscribe(events)
  1462  	defer sub.Unsubscribe()
  1463  
  1464  	// Create a number of test accounts and fund them
  1465  	keys := make([]*ecdsa.PrivateKey, 2)
  1466  	for i := 0; i < len(keys); i++ {
  1467  		keys[i], _ = crypto.GenerateKey()
  1468  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1469  	}
  1470  	// Fill up the entire queue with the same transaction price points
  1471  	txs := types.Transactions{}
  1472  	for i := uint64(0); i < config.GlobalSlots; i++ {
  1473  		txs = append(txs, pricedTransaction(i, 100000, big.NewInt(1), keys[0]))
  1474  	}
  1475  	pool.AddRemotesSync(txs)
  1476  
  1477  	pending, queued := pool.Stats()
  1478  	if pending != int(config.GlobalSlots) {
  1479  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
  1480  	}
  1481  	if queued != 0 {
  1482  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1483  	}
  1484  	if err := validateEvents(events, int(config.GlobalSlots)); err != nil {
  1485  		t.Fatalf("original event firing failed: %v", err)
  1486  	}
  1487  	if err := validateTxPoolInternals(pool); err != nil {
  1488  		t.Fatalf("pool internal state corrupted: %v", err)
  1489  	}
  1490  	// Ensure that adding high priced transactions drops a cheap, but doesn't produce a gap
  1491  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil {
  1492  		t.Fatalf("failed to add well priced transaction: %v", err)
  1493  	}
  1494  	pending, queued = pool.Stats()
  1495  	if pending != int(config.GlobalSlots) {
  1496  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
  1497  	}
  1498  	if queued != 0 {
  1499  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1500  	}
  1501  	if err := validateEvents(events, 1); err != nil {
  1502  		t.Fatalf("additional event firing failed: %v", err)
  1503  	}
  1504  	if err := validateTxPoolInternals(pool); err != nil {
  1505  		t.Fatalf("pool internal state corrupted: %v", err)
  1506  	}
  1507  }
  1508  
  1509  // Tests that the pool rejects duplicate transactions.
  1510  func TestTransactionDeduplication(t *testing.T) {
  1511  	t.Parallel()
  1512  
  1513  	// Create the pool to test the pricing enforcement with
  1514  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1515  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1516  
  1517  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1518  	defer pool.Stop()
  1519  
  1520  	// Create a test account to add transactions with
  1521  	key, _ := crypto.GenerateKey()
  1522  	pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
  1523  
  1524  	// Create a batch of transactions and add a few of them
  1525  	txs := make([]*types.Transaction, 16)
  1526  	for i := 0; i < len(txs); i++ {
  1527  		txs[i] = pricedTransaction(uint64(i), 100000, big.NewInt(1), key)
  1528  	}
  1529  	var firsts []*types.Transaction
  1530  	for i := 0; i < len(txs); i += 2 {
  1531  		firsts = append(firsts, txs[i])
  1532  	}
  1533  	errs := pool.AddRemotesSync(firsts)
  1534  	if len(errs) != len(firsts) {
  1535  		t.Fatalf("first add mismatching result count: have %d, want %d", len(errs), len(firsts))
  1536  	}
  1537  	for i, err := range errs {
  1538  		if err != nil {
  1539  			t.Errorf("add %d failed: %v", i, err)
  1540  		}
  1541  	}
  1542  	pending, queued := pool.Stats()
  1543  	if pending != 1 {
  1544  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1)
  1545  	}
  1546  	if queued != len(txs)/2-1 {
  1547  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, len(txs)/2-1)
  1548  	}
  1549  	// Try to add all of them now and ensure previous ones error out as knowns
  1550  	errs = pool.AddRemotesSync(txs)
  1551  	if len(errs) != len(txs) {
  1552  		t.Fatalf("all add mismatching result count: have %d, want %d", len(errs), len(txs))
  1553  	}
  1554  	for i, err := range errs {
  1555  		if i%2 == 0 && err == nil {
  1556  			t.Errorf("add %d succeeded, should have failed as known", i)
  1557  		}
  1558  		if i%2 == 1 && err != nil {
  1559  			t.Errorf("add %d failed: %v", i, err)
  1560  		}
  1561  	}
  1562  	pending, queued = pool.Stats()
  1563  	if pending != len(txs) {
  1564  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, len(txs))
  1565  	}
  1566  	if queued != 0 {
  1567  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1568  	}
  1569  	if err := validateTxPoolInternals(pool); err != nil {
  1570  		t.Fatalf("pool internal state corrupted: %v", err)
  1571  	}
  1572  }
  1573  
  1574  // Tests that the pool rejects replacement transactions that don't meet the minimum
  1575  // price bump required.
  1576  func TestTransactionReplacement(t *testing.T) {
  1577  	t.Parallel()
  1578  
  1579  	// Create the pool to test the pricing enforcement with
  1580  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1581  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1582  
  1583  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1584  	defer pool.Stop()
  1585  
  1586  	// Keep track of transaction events to ensure all executables get announced
  1587  	events := make(chan NewTxsEvent, 32)
  1588  	sub := pool.txFeed.Subscribe(events)
  1589  	defer sub.Unsubscribe()
  1590  
  1591  	// Create a test account to add transactions with
  1592  	key, _ := crypto.GenerateKey()
  1593  	pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
  1594  
  1595  	// Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
  1596  	price := int64(100)
  1597  	threshold := (price * (100 + int64(testTxPoolConfig.PriceBump))) / 100
  1598  
  1599  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), key)); err != nil {
  1600  		t.Fatalf("failed to add original cheap pending transaction: %v", err)
  1601  	}
  1602  	if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced {
  1603  		t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1604  	}
  1605  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), key)); err != nil {
  1606  		t.Fatalf("failed to replace original cheap pending transaction: %v", err)
  1607  	}
  1608  	if err := validateEvents(events, 2); err != nil {
  1609  		t.Fatalf("cheap replacement event firing failed: %v", err)
  1610  	}
  1611  
  1612  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(price), key)); err != nil {
  1613  		t.Fatalf("failed to add original proper pending transaction: %v", err)
  1614  	}
  1615  	if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced {
  1616  		t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1617  	}
  1618  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(threshold), key)); err != nil {
  1619  		t.Fatalf("failed to replace original proper pending transaction: %v", err)
  1620  	}
  1621  	if err := validateEvents(events, 2); err != nil {
  1622  		t.Fatalf("proper replacement event firing failed: %v", err)
  1623  	}
  1624  
  1625  	// Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
  1626  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), key)); err != nil {
  1627  		t.Fatalf("failed to add original cheap queued transaction: %v", err)
  1628  	}
  1629  	if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced {
  1630  		t.Fatalf("original cheap queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1631  	}
  1632  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), key)); err != nil {
  1633  		t.Fatalf("failed to replace original cheap queued transaction: %v", err)
  1634  	}
  1635  
  1636  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(price), key)); err != nil {
  1637  		t.Fatalf("failed to add original proper queued transaction: %v", err)
  1638  	}
  1639  	if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced {
  1640  		t.Fatalf("original proper queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1641  	}
  1642  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(threshold), key)); err != nil {
  1643  		t.Fatalf("failed to replace original proper queued transaction: %v", err)
  1644  	}
  1645  
  1646  	if err := validateEvents(events, 0); err != nil {
  1647  		t.Fatalf("queued replacement event firing failed: %v", err)
  1648  	}
  1649  	if err := validateTxPoolInternals(pool); err != nil {
  1650  		t.Fatalf("pool internal state corrupted: %v", err)
  1651  	}
  1652  }
  1653  
  1654  // Tests that local transactions are journaled to disk, but remote transactions
  1655  // get discarded between restarts.
  1656  func TestTransactionJournaling(t *testing.T)         { testTransactionJournaling(t, false) }
  1657  func TestTransactionJournalingNoLocals(t *testing.T) { testTransactionJournaling(t, true) }
  1658  
  1659  func testTransactionJournaling(t *testing.T, nolocals bool) {
  1660  	t.Parallel()
  1661  
  1662  	// Create a temporary file for the journal
  1663  	file, err := ioutil.TempFile("", "")
  1664  	if err != nil {
  1665  		t.Fatalf("failed to create temporary journal: %v", err)
  1666  	}
  1667  	journal := file.Name()
  1668  	defer os.Remove(journal)
  1669  
  1670  	// Clean up the temporary file, we only need the path for now
  1671  	file.Close()
  1672  	os.Remove(journal)
  1673  
  1674  	// Create the original pool to inject transaction into the journal
  1675  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1676  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1677  
  1678  	config := testTxPoolConfig
  1679  	config.NoLocals = nolocals
  1680  	config.Journal = journal
  1681  	config.Rejournal = time.Second
  1682  
  1683  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1684  
  1685  	// Create two test accounts to ensure remotes expire but locals do not
  1686  	local, _ := crypto.GenerateKey()
  1687  	remote, _ := crypto.GenerateKey()
  1688  
  1689  	pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
  1690  	pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))
  1691  
  1692  	// Add three local and a remote transactions and ensure they are queued up
  1693  	if err := pool.AddLocal(pricedTransaction(0, 100000, big.NewInt(1), local)); err != nil {
  1694  		t.Fatalf("failed to add local transaction: %v", err)
  1695  	}
  1696  	if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
  1697  		t.Fatalf("failed to add local transaction: %v", err)
  1698  	}
  1699  	if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil {
  1700  		t.Fatalf("failed to add local transaction: %v", err)
  1701  	}
  1702  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), remote)); err != nil {
  1703  		t.Fatalf("failed to add remote transaction: %v", err)
  1704  	}
  1705  	pending, queued := pool.Stats()
  1706  	if pending != 4 {
  1707  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4)
  1708  	}
  1709  	if queued != 0 {
  1710  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1711  	}
  1712  	if err := validateTxPoolInternals(pool); err != nil {
  1713  		t.Fatalf("pool internal state corrupted: %v", err)
  1714  	}
  1715  	// Terminate the old pool, bump the local nonce, create a new pool and ensure relevant transaction survive
  1716  	pool.Stop()
  1717  	statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
  1718  	blockchain = &testBlockChain{statedb, 1000000, new(event.Feed)}
  1719  
  1720  	pool = NewTxPool(config, params.TestChainConfig, blockchain)
  1721  
  1722  	pending, queued = pool.Stats()
  1723  	if queued != 0 {
  1724  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1725  	}
  1726  	if nolocals {
  1727  		if pending != 0 {
  1728  			t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
  1729  		}
  1730  	} else {
  1731  		if pending != 2 {
  1732  			t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1733  		}
  1734  	}
  1735  	if err := validateTxPoolInternals(pool); err != nil {
  1736  		t.Fatalf("pool internal state corrupted: %v", err)
  1737  	}
  1738  	// Bump the nonce temporarily and ensure the newly invalidated transaction is removed
  1739  	statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2)
  1740  	<-pool.requestReset(nil, nil)
  1741  	time.Sleep(2 * config.Rejournal)
  1742  	pool.Stop()
  1743  
  1744  	statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
  1745  	blockchain = &testBlockChain{statedb, 1000000, new(event.Feed)}
  1746  	pool = NewTxPool(config, params.TestChainConfig, blockchain)
  1747  
  1748  	pending, queued = pool.Stats()
  1749  	if pending != 0 {
  1750  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
  1751  	}
  1752  	if nolocals {
  1753  		if queued != 0 {
  1754  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1755  		}
  1756  	} else {
  1757  		if queued != 1 {
  1758  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  1759  		}
  1760  	}
  1761  	if err := validateTxPoolInternals(pool); err != nil {
  1762  		t.Fatalf("pool internal state corrupted: %v", err)
  1763  	}
  1764  	pool.Stop()
  1765  }
  1766  
  1767  // TestTransactionStatusCheck tests that the pool can correctly retrieve the
  1768  // pending status of individual transactions.
  1769  func TestTransactionStatusCheck(t *testing.T) {
  1770  	t.Parallel()
  1771  
  1772  	// Create the pool to test the status retrievals with
  1773  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  1774  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1775  
  1776  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1777  	defer pool.Stop()
  1778  
  1779  	// Create the test accounts to check various transaction statuses with
  1780  	keys := make([]*ecdsa.PrivateKey, 3)
  1781  	for i := 0; i < len(keys); i++ {
  1782  		keys[i], _ = crypto.GenerateKey()
  1783  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1784  	}
  1785  	// Generate and queue a batch of transactions, both pending and queued
  1786  	txs := types.Transactions{}
  1787  
  1788  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) // Pending only
  1789  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) // Pending and queued
  1790  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[1]))
  1791  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) // Queued only
  1792  
  1793  	// Import the transaction and ensure they are correctly added
  1794  	pool.AddRemotesSync(txs)
  1795  
  1796  	pending, queued := pool.Stats()
  1797  	if pending != 2 {
  1798  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1799  	}
  1800  	if queued != 2 {
  1801  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
  1802  	}
  1803  	if err := validateTxPoolInternals(pool); err != nil {
  1804  		t.Fatalf("pool internal state corrupted: %v", err)
  1805  	}
  1806  	// Retrieve the status of each transaction and validate them
  1807  	hashes := make([]common.Hash, len(txs))
  1808  	for i, tx := range txs {
  1809  		hashes[i] = tx.Hash()
  1810  	}
  1811  	hashes = append(hashes, common.Hash{})
  1812  
  1813  	statuses := pool.Status(hashes)
  1814  	expect := []TxStatus{TxStatusPending, TxStatusPending, TxStatusQueued, TxStatusQueued, TxStatusUnknown}
  1815  
  1816  	for i := 0; i < len(statuses); i++ {
  1817  		if statuses[i] != expect[i] {
  1818  			t.Errorf("transaction %d: status mismatch: have %v, want %v", i, statuses[i], expect[i])
  1819  		}
  1820  	}
  1821  }
  1822  
  1823  // Test the transaction slots consumption is computed correctly
  1824  func TestTransactionSlotCount(t *testing.T) {
  1825  	t.Parallel()
  1826  
  1827  	key, _ := crypto.GenerateKey()
  1828  
  1829  	// Check that an empty transaction consumes a single slot
  1830  	smallTx := pricedDataTransaction(0, 0, big.NewInt(0), key, 0)
  1831  	if slots := numSlots(smallTx); slots != 1 {
  1832  		t.Fatalf("small transactions slot count mismatch: have %d want %d", slots, 1)
  1833  	}
  1834  	// Check that a large transaction consumes the correct number of slots
  1835  	bigTx := pricedDataTransaction(0, 0, big.NewInt(0), key, uint64(10*txSlotSize))
  1836  	if slots := numSlots(bigTx); slots != 11 {
  1837  		t.Fatalf("big transactions slot count mismatch: have %d want %d", slots, 11)
  1838  	}
  1839  }
  1840  
  1841  // Benchmarks the speed of validating the contents of the pending queue of the
  1842  // transaction pool.
  1843  func BenchmarkPendingDemotion100(b *testing.B)   { benchmarkPendingDemotion(b, 100) }
  1844  func BenchmarkPendingDemotion1000(b *testing.B)  { benchmarkPendingDemotion(b, 1000) }
  1845  func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) }
  1846  
  1847  func benchmarkPendingDemotion(b *testing.B, size int) {
  1848  	// Add a batch of transactions to a pool one by one
  1849  	pool, key := setupTxPool()
  1850  	defer pool.Stop()
  1851  
  1852  	account := crypto.PubkeyToAddress(key.PublicKey)
  1853  	pool.currentState.AddBalance(account, big.NewInt(1000000))
  1854  
  1855  	for i := 0; i < size; i++ {
  1856  		tx := transaction(uint64(i), 100000, key)
  1857  		pool.promoteTx(account, tx.Hash(), tx)
  1858  	}
  1859  	// Benchmark the speed of pool validation
  1860  	b.ResetTimer()
  1861  	for i := 0; i < b.N; i++ {
  1862  		pool.demoteUnexecutables()
  1863  	}
  1864  }
  1865  
  1866  // Benchmarks the speed of scheduling the contents of the future queue of the
  1867  // transaction pool.
  1868  func BenchmarkFuturePromotion100(b *testing.B)   { benchmarkFuturePromotion(b, 100) }
  1869  func BenchmarkFuturePromotion1000(b *testing.B)  { benchmarkFuturePromotion(b, 1000) }
  1870  func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) }
  1871  
  1872  func benchmarkFuturePromotion(b *testing.B, size int) {
  1873  	// Add a batch of transactions to a pool one by one
  1874  	pool, key := setupTxPool()
  1875  	defer pool.Stop()
  1876  
  1877  	account := crypto.PubkeyToAddress(key.PublicKey)
  1878  	pool.currentState.AddBalance(account, big.NewInt(1000000))
  1879  
  1880  	for i := 0; i < size; i++ {
  1881  		tx := transaction(uint64(1+i), 100000, key)
  1882  		pool.enqueueTx(tx.Hash(), tx)
  1883  	}
  1884  	// Benchmark the speed of pool validation
  1885  	b.ResetTimer()
  1886  	for i := 0; i < b.N; i++ {
  1887  		pool.promoteExecutables(nil)
  1888  	}
  1889  }
  1890  
  1891  // Benchmarks the speed of batched transaction insertion.
  1892  func BenchmarkPoolBatchInsert100(b *testing.B)   { benchmarkPoolBatchInsert(b, 100) }
  1893  func BenchmarkPoolBatchInsert1000(b *testing.B)  { benchmarkPoolBatchInsert(b, 1000) }
  1894  func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000) }
  1895  
  1896  func benchmarkPoolBatchInsert(b *testing.B, size int) {
  1897  	// Generate a batch of transactions to enqueue into the pool
  1898  	pool, key := setupTxPool()
  1899  	defer pool.Stop()
  1900  
  1901  	account := crypto.PubkeyToAddress(key.PublicKey)
  1902  	pool.currentState.AddBalance(account, big.NewInt(1000000))
  1903  
  1904  	batches := make([]types.Transactions, b.N)
  1905  	for i := 0; i < b.N; i++ {
  1906  		batches[i] = make(types.Transactions, size)
  1907  		for j := 0; j < size; j++ {
  1908  			batches[i][j] = transaction(uint64(size*i+j), 100000, key)
  1909  		}
  1910  	}
  1911  	// Benchmark importing the transactions into the queue
  1912  	b.ResetTimer()
  1913  	for _, batch := range batches {
  1914  		pool.AddRemotes(batch)
  1915  	}
  1916  }