git.pirl.io/community/pirl@v0.0.0-20201111064343-9d3d31ff74be/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  	"git.pirl.io/community/pirl/common"
    30  	"git.pirl.io/community/pirl/core/rawdb"
    31  	"git.pirl.io/community/pirl/core/state"
    32  	"git.pirl.io/community/pirl/core/types"
    33  	"git.pirl.io/community/pirl/crypto"
    34  	"git.pirl.io/community/pirl/event"
    35  	"git.pirl.io/community/pirl/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()))
    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()))
   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()))
   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()))
   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()))
   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()))
   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()))
   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)         { testTransactionQueueTimeLimiting(t, false) }
   861  func TestTransactionQueueTimeLimitingNoLocals(t *testing.T) { testTransactionQueueTimeLimiting(t, true) }
   862  
   863  func testTransactionQueueTimeLimiting(t *testing.T, nolocals bool) {
   864  	// Reduce the eviction interval to a testable amount
   865  	defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
   866  	evictionInterval = time.Second
   867  
   868  	// Create the pool to test the non-expiration enforcement
   869  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
   870  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
   871  
   872  	config := testTxPoolConfig
   873  	config.Lifetime = time.Second
   874  	config.NoLocals = nolocals
   875  
   876  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
   877  	defer pool.Stop()
   878  
   879  	// Create two test accounts to ensure remotes expire but locals do not
   880  	local, _ := crypto.GenerateKey()
   881  	remote, _ := crypto.GenerateKey()
   882  
   883  	pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
   884  	pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))
   885  
   886  	// Add the two transactions and ensure they both are queued up
   887  	if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
   888  		t.Fatalf("failed to add local transaction: %v", err)
   889  	}
   890  	if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), remote)); err != nil {
   891  		t.Fatalf("failed to add remote transaction: %v", err)
   892  	}
   893  	pending, queued := pool.Stats()
   894  	if pending != 0 {
   895  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
   896  	}
   897  	if queued != 2 {
   898  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
   899  	}
   900  	if err := validateTxPoolInternals(pool); err != nil {
   901  		t.Fatalf("pool internal state corrupted: %v", err)
   902  	}
   903  	// Wait a bit for eviction to run and clean up any leftovers, and ensure only the local remains
   904  	time.Sleep(2 * config.Lifetime)
   905  
   906  	pending, queued = pool.Stats()
   907  	if pending != 0 {
   908  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
   909  	}
   910  	if nolocals {
   911  		if queued != 0 {
   912  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
   913  		}
   914  	} else {
   915  		if queued != 1 {
   916  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
   917  		}
   918  	}
   919  	if err := validateTxPoolInternals(pool); err != nil {
   920  		t.Fatalf("pool internal state corrupted: %v", err)
   921  	}
   922  }
   923  
   924  // Tests that even if the transaction count belonging to a single account goes
   925  // above some threshold, as long as the transactions are executable, they are
   926  // accepted.
   927  func TestTransactionPendingLimiting(t *testing.T) {
   928  	t.Parallel()
   929  
   930  	// Create a test account and fund it
   931  	pool, key := setupTxPool()
   932  	defer pool.Stop()
   933  
   934  	account := crypto.PubkeyToAddress(key.PublicKey)
   935  	pool.currentState.AddBalance(account, big.NewInt(1000000))
   936  
   937  	// Keep track of transaction events to ensure all executables get announced
   938  	events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
   939  	sub := pool.txFeed.Subscribe(events)
   940  	defer sub.Unsubscribe()
   941  
   942  	// Keep queuing up transactions and make sure all above a limit are dropped
   943  	for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ {
   944  		if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil {
   945  			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
   946  		}
   947  		if pool.pending[account].Len() != int(i)+1 {
   948  			t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1)
   949  		}
   950  		if len(pool.queue) != 0 {
   951  			t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
   952  		}
   953  	}
   954  	if pool.all.Count() != int(testTxPoolConfig.AccountQueue+5) {
   955  		t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue+5)
   956  	}
   957  	if err := validateEvents(events, int(testTxPoolConfig.AccountQueue+5)); err != nil {
   958  		t.Fatalf("event firing failed: %v", err)
   959  	}
   960  	if err := validateTxPoolInternals(pool); err != nil {
   961  		t.Fatalf("pool internal state corrupted: %v", err)
   962  	}
   963  }
   964  
   965  // Tests that if the transaction count belonging to multiple accounts go above
   966  // some hard threshold, the higher transactions are dropped to prevent DOS
   967  // attacks.
   968  func TestTransactionPendingGlobalLimiting(t *testing.T) {
   969  	t.Parallel()
   970  
   971  	// Create the pool to test the limit enforcement with
   972  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
   973  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
   974  
   975  	config := testTxPoolConfig
   976  	config.GlobalSlots = config.AccountSlots * 10
   977  
   978  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
   979  	defer pool.Stop()
   980  
   981  	// Create a number of test accounts and fund them
   982  	keys := make([]*ecdsa.PrivateKey, 5)
   983  	for i := 0; i < len(keys); i++ {
   984  		keys[i], _ = crypto.GenerateKey()
   985  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
   986  	}
   987  	// Generate and queue a batch of transactions
   988  	nonces := make(map[common.Address]uint64)
   989  
   990  	txs := types.Transactions{}
   991  	for _, key := range keys {
   992  		addr := crypto.PubkeyToAddress(key.PublicKey)
   993  		for j := 0; j < int(config.GlobalSlots)/len(keys)*2; j++ {
   994  			txs = append(txs, transaction(nonces[addr], 100000, key))
   995  			nonces[addr]++
   996  		}
   997  	}
   998  	// Import the batch and verify that limits have been enforced
   999  	pool.AddRemotesSync(txs)
  1000  
  1001  	pending := 0
  1002  	for _, list := range pool.pending {
  1003  		pending += list.Len()
  1004  	}
  1005  	if pending > int(config.GlobalSlots) {
  1006  		t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, config.GlobalSlots)
  1007  	}
  1008  	if err := validateTxPoolInternals(pool); err != nil {
  1009  		t.Fatalf("pool internal state corrupted: %v", err)
  1010  	}
  1011  }
  1012  
  1013  // Test the limit on transaction size is enforced correctly.
  1014  // This test verifies every transaction having allowed size
  1015  // is added to the pool, and longer transactions are rejected.
  1016  func TestTransactionAllowedTxSize(t *testing.T) {
  1017  	t.Parallel()
  1018  
  1019  	// Create a test account and fund it
  1020  	pool, key := setupTxPool()
  1021  	defer pool.Stop()
  1022  
  1023  	account := crypto.PubkeyToAddress(key.PublicKey)
  1024  	pool.currentState.AddBalance(account, big.NewInt(1000000000))
  1025  
  1026  	// Compute maximal data size for transactions (lower bound).
  1027  	//
  1028  	// It is assumed the fields in the transaction (except of the data) are:
  1029  	//   - nonce     <= 32 bytes
  1030  	//   - gasPrice  <= 32 bytes
  1031  	//   - gasLimit  <= 32 bytes
  1032  	//   - recipient == 20 bytes
  1033  	//   - value     <= 32 bytes
  1034  	//   - signature == 65 bytes
  1035  	// All those fields are summed up to at most 213 bytes.
  1036  	baseSize := uint64(213)
  1037  	dataSize := txMaxSize - baseSize
  1038  
  1039  	// Try adding a transaction with maximal allowed size
  1040  	tx := pricedDataTransaction(0, pool.currentMaxGas, big.NewInt(1), key, dataSize)
  1041  	if err := pool.addRemoteSync(tx); err != nil {
  1042  		t.Fatalf("failed to add transaction of size %d, close to maximal: %v", int(tx.Size()), err)
  1043  	}
  1044  	// Try adding a transaction with random allowed size
  1045  	if err := pool.addRemoteSync(pricedDataTransaction(1, pool.currentMaxGas, big.NewInt(1), key, uint64(rand.Intn(int(dataSize))))); err != nil {
  1046  		t.Fatalf("failed to add transaction of random allowed size: %v", err)
  1047  	}
  1048  	// Try adding a transaction of minimal not allowed size
  1049  	if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, txMaxSize)); err == nil {
  1050  		t.Fatalf("expected rejection on slightly oversize transaction")
  1051  	}
  1052  	// Try adding a transaction of random not allowed size
  1053  	if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, dataSize+1+uint64(rand.Intn(int(10*txMaxSize))))); err == nil {
  1054  		t.Fatalf("expected rejection on oversize transaction")
  1055  	}
  1056  	// Run some sanity checks on the pool internals
  1057  	pending, queued := pool.Stats()
  1058  	if pending != 2 {
  1059  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1060  	}
  1061  	if queued != 0 {
  1062  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1063  	}
  1064  	if err := validateTxPoolInternals(pool); err != nil {
  1065  		t.Fatalf("pool internal state corrupted: %v", err)
  1066  	}
  1067  }
  1068  
  1069  // Tests that if transactions start being capped, transactions are also removed from 'all'
  1070  func TestTransactionCapClearsFromAll(t *testing.T) {
  1071  	t.Parallel()
  1072  
  1073  	// Create the pool to test the limit enforcement with
  1074  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1075  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1076  
  1077  	config := testTxPoolConfig
  1078  	config.AccountSlots = 2
  1079  	config.AccountQueue = 2
  1080  	config.GlobalSlots = 8
  1081  
  1082  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1083  	defer pool.Stop()
  1084  
  1085  	// Create a number of test accounts and fund them
  1086  	key, _ := crypto.GenerateKey()
  1087  	addr := crypto.PubkeyToAddress(key.PublicKey)
  1088  	pool.currentState.AddBalance(addr, big.NewInt(1000000))
  1089  
  1090  	txs := types.Transactions{}
  1091  	for j := 0; j < int(config.GlobalSlots)*2; j++ {
  1092  		txs = append(txs, transaction(uint64(j), 100000, key))
  1093  	}
  1094  	// Import the batch and verify that limits have been enforced
  1095  	pool.AddRemotes(txs)
  1096  	if err := validateTxPoolInternals(pool); err != nil {
  1097  		t.Fatalf("pool internal state corrupted: %v", err)
  1098  	}
  1099  }
  1100  
  1101  // Tests that if the transaction count belonging to multiple accounts go above
  1102  // some hard threshold, if they are under the minimum guaranteed slot count then
  1103  // the transactions are still kept.
  1104  func TestTransactionPendingMinimumAllowance(t *testing.T) {
  1105  	t.Parallel()
  1106  
  1107  	// Create the pool to test the limit enforcement with
  1108  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1109  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1110  
  1111  	config := testTxPoolConfig
  1112  	config.GlobalSlots = 1
  1113  
  1114  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1115  	defer pool.Stop()
  1116  
  1117  	// Create a number of test accounts and fund them
  1118  	keys := make([]*ecdsa.PrivateKey, 5)
  1119  	for i := 0; i < len(keys); i++ {
  1120  		keys[i], _ = crypto.GenerateKey()
  1121  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1122  	}
  1123  	// Generate and queue a batch of transactions
  1124  	nonces := make(map[common.Address]uint64)
  1125  
  1126  	txs := types.Transactions{}
  1127  	for _, key := range keys {
  1128  		addr := crypto.PubkeyToAddress(key.PublicKey)
  1129  		for j := 0; j < int(config.AccountSlots)*2; j++ {
  1130  			txs = append(txs, transaction(nonces[addr], 100000, key))
  1131  			nonces[addr]++
  1132  		}
  1133  	}
  1134  	// Import the batch and verify that limits have been enforced
  1135  	pool.AddRemotesSync(txs)
  1136  
  1137  	for addr, list := range pool.pending {
  1138  		if list.Len() != int(config.AccountSlots) {
  1139  			t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), config.AccountSlots)
  1140  		}
  1141  	}
  1142  	if err := validateTxPoolInternals(pool); err != nil {
  1143  		t.Fatalf("pool internal state corrupted: %v", err)
  1144  	}
  1145  }
  1146  
  1147  // Tests that setting the transaction pool gas price to a higher value correctly
  1148  // discards everything cheaper than that and moves any gapped transactions back
  1149  // from the pending pool to the queue.
  1150  //
  1151  // Note, local transactions are never allowed to be dropped.
  1152  func TestTransactionPoolRepricing(t *testing.T) {
  1153  	t.Parallel()
  1154  
  1155  	// Create the pool to test the pricing enforcement with
  1156  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1157  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1158  
  1159  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1160  	defer pool.Stop()
  1161  
  1162  	// Keep track of transaction events to ensure all executables get announced
  1163  	events := make(chan NewTxsEvent, 32)
  1164  	sub := pool.txFeed.Subscribe(events)
  1165  	defer sub.Unsubscribe()
  1166  
  1167  	// Create a number of test accounts and fund them
  1168  	keys := make([]*ecdsa.PrivateKey, 4)
  1169  	for i := 0; i < len(keys); i++ {
  1170  		keys[i], _ = crypto.GenerateKey()
  1171  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1172  	}
  1173  	// Generate and queue a batch of transactions, both pending and queued
  1174  	txs := types.Transactions{}
  1175  
  1176  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(2), keys[0]))
  1177  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[0]))
  1178  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[0]))
  1179  
  1180  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1]))
  1181  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[1]))
  1182  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[1]))
  1183  
  1184  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[2]))
  1185  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2]))
  1186  	txs = append(txs, pricedTransaction(3, 100000, big.NewInt(2), keys[2]))
  1187  
  1188  	ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[3])
  1189  
  1190  	// Import the batch and that both pending and queued transactions match up
  1191  	pool.AddRemotesSync(txs)
  1192  	pool.AddLocal(ltx)
  1193  
  1194  	pending, queued := pool.Stats()
  1195  	if pending != 7 {
  1196  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 7)
  1197  	}
  1198  	if queued != 3 {
  1199  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
  1200  	}
  1201  	if err := validateEvents(events, 7); err != nil {
  1202  		t.Fatalf("original event firing failed: %v", err)
  1203  	}
  1204  	if err := validateTxPoolInternals(pool); err != nil {
  1205  		t.Fatalf("pool internal state corrupted: %v", err)
  1206  	}
  1207  	// Reprice the pool and check that underpriced transactions get dropped
  1208  	pool.SetGasPrice(big.NewInt(2))
  1209  
  1210  	pending, queued = pool.Stats()
  1211  	if pending != 2 {
  1212  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1213  	}
  1214  	if queued != 5 {
  1215  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 5)
  1216  	}
  1217  	if err := validateEvents(events, 0); err != nil {
  1218  		t.Fatalf("reprice event firing failed: %v", err)
  1219  	}
  1220  	if err := validateTxPoolInternals(pool); err != nil {
  1221  		t.Fatalf("pool internal state corrupted: %v", err)
  1222  	}
  1223  	// Check that we can't add the old transactions back
  1224  	if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), keys[0])); err != ErrUnderpriced {
  1225  		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1226  	}
  1227  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
  1228  		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1229  	}
  1230  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), keys[2])); err != ErrUnderpriced {
  1231  		t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1232  	}
  1233  	if err := validateEvents(events, 0); err != nil {
  1234  		t.Fatalf("post-reprice event firing failed: %v", err)
  1235  	}
  1236  	if err := validateTxPoolInternals(pool); err != nil {
  1237  		t.Fatalf("pool internal state corrupted: %v", err)
  1238  	}
  1239  	// However we can add local underpriced transactions
  1240  	tx := pricedTransaction(1, 100000, big.NewInt(1), keys[3])
  1241  	if err := pool.AddLocal(tx); err != nil {
  1242  		t.Fatalf("failed to add underpriced local transaction: %v", err)
  1243  	}
  1244  	if pending, _ = pool.Stats(); pending != 3 {
  1245  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  1246  	}
  1247  	if err := validateEvents(events, 1); err != nil {
  1248  		t.Fatalf("post-reprice local event firing failed: %v", err)
  1249  	}
  1250  	if err := validateTxPoolInternals(pool); err != nil {
  1251  		t.Fatalf("pool internal state corrupted: %v", err)
  1252  	}
  1253  	// And we can fill gaps with properly priced transactions
  1254  	if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(2), keys[0])); err != nil {
  1255  		t.Fatalf("failed to add pending transaction: %v", err)
  1256  	}
  1257  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), keys[1])); err != nil {
  1258  		t.Fatalf("failed to add pending transaction: %v", err)
  1259  	}
  1260  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), keys[2])); err != nil {
  1261  		t.Fatalf("failed to add queued transaction: %v", err)
  1262  	}
  1263  	if err := validateEvents(events, 5); err != nil {
  1264  		t.Fatalf("post-reprice event firing failed: %v", err)
  1265  	}
  1266  	if err := validateTxPoolInternals(pool); err != nil {
  1267  		t.Fatalf("pool internal state corrupted: %v", err)
  1268  	}
  1269  }
  1270  
  1271  // Tests that setting the transaction pool gas price to a higher value does not
  1272  // remove local transactions.
  1273  func TestTransactionPoolRepricingKeepsLocals(t *testing.T) {
  1274  	t.Parallel()
  1275  
  1276  	// Create the pool to test the pricing enforcement with
  1277  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1278  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1279  
  1280  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1281  	defer pool.Stop()
  1282  
  1283  	// Create a number of test accounts and fund them
  1284  	keys := make([]*ecdsa.PrivateKey, 3)
  1285  	for i := 0; i < len(keys); i++ {
  1286  		keys[i], _ = crypto.GenerateKey()
  1287  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000*1000000))
  1288  	}
  1289  	// Create transaction (both pending and queued) with a linearly growing gasprice
  1290  	for i := uint64(0); i < 500; i++ {
  1291  		// Add pending transaction.
  1292  		pendingTx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2])
  1293  		if err := pool.AddLocal(pendingTx); err != nil {
  1294  			t.Fatal(err)
  1295  		}
  1296  		// Add queued transaction.
  1297  		queuedTx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2])
  1298  		if err := pool.AddLocal(queuedTx); err != nil {
  1299  			t.Fatal(err)
  1300  		}
  1301  	}
  1302  	pending, queued := pool.Stats()
  1303  	expPending, expQueued := 500, 500
  1304  	validate := func() {
  1305  		pending, queued = pool.Stats()
  1306  		if pending != expPending {
  1307  			t.Fatalf("pending transactions mismatched: have %d, want %d", pending, expPending)
  1308  		}
  1309  		if queued != expQueued {
  1310  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, expQueued)
  1311  		}
  1312  
  1313  		if err := validateTxPoolInternals(pool); err != nil {
  1314  			t.Fatalf("pool internal state corrupted: %v", err)
  1315  		}
  1316  	}
  1317  	validate()
  1318  
  1319  	// Reprice the pool and check that nothing is dropped
  1320  	pool.SetGasPrice(big.NewInt(2))
  1321  	validate()
  1322  
  1323  	pool.SetGasPrice(big.NewInt(2))
  1324  	pool.SetGasPrice(big.NewInt(4))
  1325  	pool.SetGasPrice(big.NewInt(8))
  1326  	pool.SetGasPrice(big.NewInt(100))
  1327  	validate()
  1328  }
  1329  
  1330  // Tests that when the pool reaches its global transaction limit, underpriced
  1331  // transactions are gradually shifted out for more expensive ones and any gapped
  1332  // pending transactions are moved into the queue.
  1333  //
  1334  // Note, local transactions are never allowed to be dropped.
  1335  func TestTransactionPoolUnderpricing(t *testing.T) {
  1336  	t.Parallel()
  1337  
  1338  	// Create the pool to test the pricing enforcement with
  1339  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1340  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1341  
  1342  	config := testTxPoolConfig
  1343  	config.GlobalSlots = 2
  1344  	config.GlobalQueue = 2
  1345  
  1346  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1347  	defer pool.Stop()
  1348  
  1349  	// Keep track of transaction events to ensure all executables get announced
  1350  	events := make(chan NewTxsEvent, 32)
  1351  	sub := pool.txFeed.Subscribe(events)
  1352  	defer sub.Unsubscribe()
  1353  
  1354  	// Create a number of test accounts and fund them
  1355  	keys := make([]*ecdsa.PrivateKey, 4)
  1356  	for i := 0; i < len(keys); i++ {
  1357  		keys[i], _ = crypto.GenerateKey()
  1358  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1359  	}
  1360  	// Generate and queue a batch of transactions, both pending and queued
  1361  	txs := types.Transactions{}
  1362  
  1363  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0]))
  1364  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[0]))
  1365  
  1366  	txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[1]))
  1367  
  1368  	ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[2])
  1369  
  1370  	// Import the batch and that both pending and queued transactions match up
  1371  	pool.AddRemotes(txs)
  1372  	pool.AddLocal(ltx)
  1373  
  1374  	pending, queued := pool.Stats()
  1375  	if pending != 3 {
  1376  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  1377  	}
  1378  	if queued != 1 {
  1379  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  1380  	}
  1381  	if err := validateEvents(events, 3); err != nil {
  1382  		t.Fatalf("original event firing failed: %v", err)
  1383  	}
  1384  	if err := validateTxPoolInternals(pool); err != nil {
  1385  		t.Fatalf("pool internal state corrupted: %v", err)
  1386  	}
  1387  	// Ensure that adding an underpriced transaction on block limit fails
  1388  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
  1389  		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  1390  	}
  1391  	// Ensure that adding high priced transactions drops cheap ones, but not own
  1392  	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 -
  1393  		t.Fatalf("failed to add well priced transaction: %v", err)
  1394  	}
  1395  	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
  1396  		t.Fatalf("failed to add well priced transaction: %v", err)
  1397  	}
  1398  	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
  1399  		t.Fatalf("failed to add well priced transaction: %v", err)
  1400  	}
  1401  	pending, queued = pool.Stats()
  1402  	if pending != 2 {
  1403  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1404  	}
  1405  	if queued != 2 {
  1406  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
  1407  	}
  1408  	if err := validateEvents(events, 1); err != nil {
  1409  		t.Fatalf("additional event firing failed: %v", err)
  1410  	}
  1411  	if err := validateTxPoolInternals(pool); err != nil {
  1412  		t.Fatalf("pool internal state corrupted: %v", err)
  1413  	}
  1414  	// Ensure that adding local transactions can push out even higher priced ones
  1415  	ltx = pricedTransaction(1, 100000, big.NewInt(0), keys[2])
  1416  	if err := pool.AddLocal(ltx); err != nil {
  1417  		t.Fatalf("failed to append underpriced local transaction: %v", err)
  1418  	}
  1419  	ltx = pricedTransaction(0, 100000, big.NewInt(0), keys[3])
  1420  	if err := pool.AddLocal(ltx); err != nil {
  1421  		t.Fatalf("failed to add new underpriced local transaction: %v", err)
  1422  	}
  1423  	pending, queued = pool.Stats()
  1424  	if pending != 3 {
  1425  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  1426  	}
  1427  	if queued != 1 {
  1428  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  1429  	}
  1430  	if err := validateEvents(events, 2); err != nil {
  1431  		t.Fatalf("local event firing failed: %v", err)
  1432  	}
  1433  	if err := validateTxPoolInternals(pool); err != nil {
  1434  		t.Fatalf("pool internal state corrupted: %v", err)
  1435  	}
  1436  }
  1437  
  1438  // Tests that more expensive transactions push out cheap ones from the pool, but
  1439  // without producing instability by creating gaps that start jumping transactions
  1440  // back and forth between queued/pending.
  1441  func TestTransactionPoolStableUnderpricing(t *testing.T) {
  1442  	t.Parallel()
  1443  
  1444  	// Create the pool to test the pricing enforcement with
  1445  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1446  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1447  
  1448  	config := testTxPoolConfig
  1449  	config.GlobalSlots = 128
  1450  	config.GlobalQueue = 0
  1451  
  1452  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1453  	defer pool.Stop()
  1454  
  1455  	// Keep track of transaction events to ensure all executables get announced
  1456  	events := make(chan NewTxsEvent, 32)
  1457  	sub := pool.txFeed.Subscribe(events)
  1458  	defer sub.Unsubscribe()
  1459  
  1460  	// Create a number of test accounts and fund them
  1461  	keys := make([]*ecdsa.PrivateKey, 2)
  1462  	for i := 0; i < len(keys); i++ {
  1463  		keys[i], _ = crypto.GenerateKey()
  1464  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1465  	}
  1466  	// Fill up the entire queue with the same transaction price points
  1467  	txs := types.Transactions{}
  1468  	for i := uint64(0); i < config.GlobalSlots; i++ {
  1469  		txs = append(txs, pricedTransaction(i, 100000, big.NewInt(1), keys[0]))
  1470  	}
  1471  	pool.AddRemotesSync(txs)
  1472  
  1473  	pending, queued := pool.Stats()
  1474  	if pending != int(config.GlobalSlots) {
  1475  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
  1476  	}
  1477  	if queued != 0 {
  1478  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1479  	}
  1480  	if err := validateEvents(events, int(config.GlobalSlots)); err != nil {
  1481  		t.Fatalf("original event firing failed: %v", err)
  1482  	}
  1483  	if err := validateTxPoolInternals(pool); err != nil {
  1484  		t.Fatalf("pool internal state corrupted: %v", err)
  1485  	}
  1486  	// Ensure that adding high priced transactions drops a cheap, but doesn't produce a gap
  1487  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil {
  1488  		t.Fatalf("failed to add well priced transaction: %v", err)
  1489  	}
  1490  	pending, queued = pool.Stats()
  1491  	if pending != int(config.GlobalSlots) {
  1492  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
  1493  	}
  1494  	if queued != 0 {
  1495  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1496  	}
  1497  	if err := validateEvents(events, 1); err != nil {
  1498  		t.Fatalf("additional event firing failed: %v", err)
  1499  	}
  1500  	if err := validateTxPoolInternals(pool); err != nil {
  1501  		t.Fatalf("pool internal state corrupted: %v", err)
  1502  	}
  1503  }
  1504  
  1505  // Tests that the pool rejects duplicate transactions.
  1506  func TestTransactionDeduplication(t *testing.T) {
  1507  	t.Parallel()
  1508  
  1509  	// Create the pool to test the pricing enforcement with
  1510  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1511  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1512  
  1513  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1514  	defer pool.Stop()
  1515  
  1516  	// Create a test account to add transactions with
  1517  	key, _ := crypto.GenerateKey()
  1518  	pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
  1519  
  1520  	// Create a batch of transactions and add a few of them
  1521  	txs := make([]*types.Transaction, 16)
  1522  	for i := 0; i < len(txs); i++ {
  1523  		txs[i] = pricedTransaction(uint64(i), 100000, big.NewInt(1), key)
  1524  	}
  1525  	var firsts []*types.Transaction
  1526  	for i := 0; i < len(txs); i += 2 {
  1527  		firsts = append(firsts, txs[i])
  1528  	}
  1529  	errs := pool.AddRemotesSync(firsts)
  1530  	if len(errs) != len(firsts) {
  1531  		t.Fatalf("first add mismatching result count: have %d, want %d", len(errs), len(firsts))
  1532  	}
  1533  	for i, err := range errs {
  1534  		if err != nil {
  1535  			t.Errorf("add %d failed: %v", i, err)
  1536  		}
  1537  	}
  1538  	pending, queued := pool.Stats()
  1539  	if pending != 1 {
  1540  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1)
  1541  	}
  1542  	if queued != len(txs)/2-1 {
  1543  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, len(txs)/2-1)
  1544  	}
  1545  	// Try to add all of them now and ensure previous ones error out as knowns
  1546  	errs = pool.AddRemotesSync(txs)
  1547  	if len(errs) != len(txs) {
  1548  		t.Fatalf("all add mismatching result count: have %d, want %d", len(errs), len(txs))
  1549  	}
  1550  	for i, err := range errs {
  1551  		if i%2 == 0 && err == nil {
  1552  			t.Errorf("add %d succeeded, should have failed as known", i)
  1553  		}
  1554  		if i%2 == 1 && err != nil {
  1555  			t.Errorf("add %d failed: %v", i, err)
  1556  		}
  1557  	}
  1558  	pending, queued = pool.Stats()
  1559  	if pending != len(txs) {
  1560  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, len(txs))
  1561  	}
  1562  	if queued != 0 {
  1563  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1564  	}
  1565  	if err := validateTxPoolInternals(pool); err != nil {
  1566  		t.Fatalf("pool internal state corrupted: %v", err)
  1567  	}
  1568  }
  1569  
  1570  // Tests that the pool rejects replacement transactions that don't meet the minimum
  1571  // price bump required.
  1572  func TestTransactionReplacement(t *testing.T) {
  1573  	t.Parallel()
  1574  
  1575  	// Create the pool to test the pricing enforcement with
  1576  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1577  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1578  
  1579  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1580  	defer pool.Stop()
  1581  
  1582  	// Keep track of transaction events to ensure all executables get announced
  1583  	events := make(chan NewTxsEvent, 32)
  1584  	sub := pool.txFeed.Subscribe(events)
  1585  	defer sub.Unsubscribe()
  1586  
  1587  	// Create a test account to add transactions with
  1588  	key, _ := crypto.GenerateKey()
  1589  	pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
  1590  
  1591  	// Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
  1592  	price := int64(100)
  1593  	threshold := (price * (100 + int64(testTxPoolConfig.PriceBump))) / 100
  1594  
  1595  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), key)); err != nil {
  1596  		t.Fatalf("failed to add original cheap pending transaction: %v", err)
  1597  	}
  1598  	if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced {
  1599  		t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1600  	}
  1601  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), key)); err != nil {
  1602  		t.Fatalf("failed to replace original cheap pending transaction: %v", err)
  1603  	}
  1604  	if err := validateEvents(events, 2); err != nil {
  1605  		t.Fatalf("cheap replacement event firing failed: %v", err)
  1606  	}
  1607  
  1608  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(price), key)); err != nil {
  1609  		t.Fatalf("failed to add original proper pending transaction: %v", err)
  1610  	}
  1611  	if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced {
  1612  		t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1613  	}
  1614  	if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(threshold), key)); err != nil {
  1615  		t.Fatalf("failed to replace original proper pending transaction: %v", err)
  1616  	}
  1617  	if err := validateEvents(events, 2); err != nil {
  1618  		t.Fatalf("proper replacement event firing failed: %v", err)
  1619  	}
  1620  
  1621  	// Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
  1622  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), key)); err != nil {
  1623  		t.Fatalf("failed to add original cheap queued transaction: %v", err)
  1624  	}
  1625  	if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced {
  1626  		t.Fatalf("original cheap queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1627  	}
  1628  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), key)); err != nil {
  1629  		t.Fatalf("failed to replace original cheap queued transaction: %v", err)
  1630  	}
  1631  
  1632  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(price), key)); err != nil {
  1633  		t.Fatalf("failed to add original proper queued transaction: %v", err)
  1634  	}
  1635  	if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced {
  1636  		t.Fatalf("original proper queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  1637  	}
  1638  	if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(threshold), key)); err != nil {
  1639  		t.Fatalf("failed to replace original proper queued transaction: %v", err)
  1640  	}
  1641  
  1642  	if err := validateEvents(events, 0); err != nil {
  1643  		t.Fatalf("queued replacement event firing failed: %v", err)
  1644  	}
  1645  	if err := validateTxPoolInternals(pool); err != nil {
  1646  		t.Fatalf("pool internal state corrupted: %v", err)
  1647  	}
  1648  }
  1649  
  1650  // Tests that local transactions are journaled to disk, but remote transactions
  1651  // get discarded between restarts.
  1652  func TestTransactionJournaling(t *testing.T)         { testTransactionJournaling(t, false) }
  1653  func TestTransactionJournalingNoLocals(t *testing.T) { testTransactionJournaling(t, true) }
  1654  
  1655  func testTransactionJournaling(t *testing.T, nolocals bool) {
  1656  	t.Parallel()
  1657  
  1658  	// Create a temporary file for the journal
  1659  	file, err := ioutil.TempFile("", "")
  1660  	if err != nil {
  1661  		t.Fatalf("failed to create temporary journal: %v", err)
  1662  	}
  1663  	journal := file.Name()
  1664  	defer os.Remove(journal)
  1665  
  1666  	// Clean up the temporary file, we only need the path for now
  1667  	file.Close()
  1668  	os.Remove(journal)
  1669  
  1670  	// Create the original pool to inject transaction into the journal
  1671  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1672  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1673  
  1674  	config := testTxPoolConfig
  1675  	config.NoLocals = nolocals
  1676  	config.Journal = journal
  1677  	config.Rejournal = time.Second
  1678  
  1679  	pool := NewTxPool(config, params.TestChainConfig, blockchain)
  1680  
  1681  	// Create two test accounts to ensure remotes expire but locals do not
  1682  	local, _ := crypto.GenerateKey()
  1683  	remote, _ := crypto.GenerateKey()
  1684  
  1685  	pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
  1686  	pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))
  1687  
  1688  	// Add three local and a remote transactions and ensure they are queued up
  1689  	if err := pool.AddLocal(pricedTransaction(0, 100000, big.NewInt(1), local)); err != nil {
  1690  		t.Fatalf("failed to add local transaction: %v", err)
  1691  	}
  1692  	if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
  1693  		t.Fatalf("failed to add local transaction: %v", err)
  1694  	}
  1695  	if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil {
  1696  		t.Fatalf("failed to add local transaction: %v", err)
  1697  	}
  1698  	if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), remote)); err != nil {
  1699  		t.Fatalf("failed to add remote transaction: %v", err)
  1700  	}
  1701  	pending, queued := pool.Stats()
  1702  	if pending != 4 {
  1703  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4)
  1704  	}
  1705  	if queued != 0 {
  1706  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1707  	}
  1708  	if err := validateTxPoolInternals(pool); err != nil {
  1709  		t.Fatalf("pool internal state corrupted: %v", err)
  1710  	}
  1711  	// Terminate the old pool, bump the local nonce, create a new pool and ensure relevant transaction survive
  1712  	pool.Stop()
  1713  	statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
  1714  	blockchain = &testBlockChain{statedb, 1000000, new(event.Feed)}
  1715  
  1716  	pool = NewTxPool(config, params.TestChainConfig, blockchain)
  1717  
  1718  	pending, queued = pool.Stats()
  1719  	if queued != 0 {
  1720  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1721  	}
  1722  	if nolocals {
  1723  		if pending != 0 {
  1724  			t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
  1725  		}
  1726  	} else {
  1727  		if pending != 2 {
  1728  			t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1729  		}
  1730  	}
  1731  	if err := validateTxPoolInternals(pool); err != nil {
  1732  		t.Fatalf("pool internal state corrupted: %v", err)
  1733  	}
  1734  	// Bump the nonce temporarily and ensure the newly invalidated transaction is removed
  1735  	statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2)
  1736  	<-pool.requestReset(nil, nil)
  1737  	time.Sleep(2 * config.Rejournal)
  1738  	pool.Stop()
  1739  
  1740  	statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
  1741  	blockchain = &testBlockChain{statedb, 1000000, new(event.Feed)}
  1742  	pool = NewTxPool(config, params.TestChainConfig, blockchain)
  1743  
  1744  	pending, queued = pool.Stats()
  1745  	if pending != 0 {
  1746  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
  1747  	}
  1748  	if nolocals {
  1749  		if queued != 0 {
  1750  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
  1751  		}
  1752  	} else {
  1753  		if queued != 1 {
  1754  			t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  1755  		}
  1756  	}
  1757  	if err := validateTxPoolInternals(pool); err != nil {
  1758  		t.Fatalf("pool internal state corrupted: %v", err)
  1759  	}
  1760  	pool.Stop()
  1761  }
  1762  
  1763  // TestTransactionStatusCheck tests that the pool can correctly retrieve the
  1764  // pending status of individual transactions.
  1765  func TestTransactionStatusCheck(t *testing.T) {
  1766  	t.Parallel()
  1767  
  1768  	// Create the pool to test the status retrievals with
  1769  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()))
  1770  	blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)}
  1771  
  1772  	pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
  1773  	defer pool.Stop()
  1774  
  1775  	// Create the test accounts to check various transaction statuses with
  1776  	keys := make([]*ecdsa.PrivateKey, 3)
  1777  	for i := 0; i < len(keys); i++ {
  1778  		keys[i], _ = crypto.GenerateKey()
  1779  		pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  1780  	}
  1781  	// Generate and queue a batch of transactions, both pending and queued
  1782  	txs := types.Transactions{}
  1783  
  1784  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) // Pending only
  1785  	txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) // Pending and queued
  1786  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[1]))
  1787  	txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) // Queued only
  1788  
  1789  	// Import the transaction and ensure they are correctly added
  1790  	pool.AddRemotesSync(txs)
  1791  
  1792  	pending, queued := pool.Stats()
  1793  	if pending != 2 {
  1794  		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  1795  	}
  1796  	if queued != 2 {
  1797  		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
  1798  	}
  1799  	if err := validateTxPoolInternals(pool); err != nil {
  1800  		t.Fatalf("pool internal state corrupted: %v", err)
  1801  	}
  1802  	// Retrieve the status of each transaction and validate them
  1803  	hashes := make([]common.Hash, len(txs))
  1804  	for i, tx := range txs {
  1805  		hashes[i] = tx.Hash()
  1806  	}
  1807  	hashes = append(hashes, common.Hash{})
  1808  
  1809  	statuses := pool.Status(hashes)
  1810  	expect := []TxStatus{TxStatusPending, TxStatusPending, TxStatusQueued, TxStatusQueued, TxStatusUnknown}
  1811  
  1812  	for i := 0; i < len(statuses); i++ {
  1813  		if statuses[i] != expect[i] {
  1814  			t.Errorf("transaction %d: status mismatch: have %v, want %v", i, statuses[i], expect[i])
  1815  		}
  1816  	}
  1817  }
  1818  
  1819  // Test the transaction slots consumption is computed correctly
  1820  func TestTransactionSlotCount(t *testing.T) {
  1821  	t.Parallel()
  1822  
  1823  	key, _ := crypto.GenerateKey()
  1824  
  1825  	// Check that an empty transaction consumes a single slot
  1826  	smallTx := pricedDataTransaction(0, 0, big.NewInt(0), key, 0)
  1827  	if slots := numSlots(smallTx); slots != 1 {
  1828  		t.Fatalf("small transactions slot count mismatch: have %d want %d", slots, 1)
  1829  	}
  1830  	// Check that a large transaction consumes the correct number of slots
  1831  	bigTx := pricedDataTransaction(0, 0, big.NewInt(0), key, uint64(10*txSlotSize))
  1832  	if slots := numSlots(bigTx); slots != 11 {
  1833  		t.Fatalf("big transactions slot count mismatch: have %d want %d", slots, 11)
  1834  	}
  1835  }
  1836  
  1837  // Benchmarks the speed of validating the contents of the pending queue of the
  1838  // transaction pool.
  1839  func BenchmarkPendingDemotion100(b *testing.B)   { benchmarkPendingDemotion(b, 100) }
  1840  func BenchmarkPendingDemotion1000(b *testing.B)  { benchmarkPendingDemotion(b, 1000) }
  1841  func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) }
  1842  
  1843  func benchmarkPendingDemotion(b *testing.B, size int) {
  1844  	// Add a batch of transactions to a pool one by one
  1845  	pool, key := setupTxPool()
  1846  	defer pool.Stop()
  1847  
  1848  	account := crypto.PubkeyToAddress(key.PublicKey)
  1849  	pool.currentState.AddBalance(account, big.NewInt(1000000))
  1850  
  1851  	for i := 0; i < size; i++ {
  1852  		tx := transaction(uint64(i), 100000, key)
  1853  		pool.promoteTx(account, tx.Hash(), tx)
  1854  	}
  1855  	// Benchmark the speed of pool validation
  1856  	b.ResetTimer()
  1857  	for i := 0; i < b.N; i++ {
  1858  		pool.demoteUnexecutables()
  1859  	}
  1860  }
  1861  
  1862  // Benchmarks the speed of scheduling the contents of the future queue of the
  1863  // transaction pool.
  1864  func BenchmarkFuturePromotion100(b *testing.B)   { benchmarkFuturePromotion(b, 100) }
  1865  func BenchmarkFuturePromotion1000(b *testing.B)  { benchmarkFuturePromotion(b, 1000) }
  1866  func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) }
  1867  
  1868  func benchmarkFuturePromotion(b *testing.B, size int) {
  1869  	// Add a batch of transactions to a pool one by one
  1870  	pool, key := setupTxPool()
  1871  	defer pool.Stop()
  1872  
  1873  	account := crypto.PubkeyToAddress(key.PublicKey)
  1874  	pool.currentState.AddBalance(account, big.NewInt(1000000))
  1875  
  1876  	for i := 0; i < size; i++ {
  1877  		tx := transaction(uint64(1+i), 100000, key)
  1878  		pool.enqueueTx(tx.Hash(), tx)
  1879  	}
  1880  	// Benchmark the speed of pool validation
  1881  	b.ResetTimer()
  1882  	for i := 0; i < b.N; i++ {
  1883  		pool.promoteExecutables(nil)
  1884  	}
  1885  }
  1886  
  1887  // Benchmarks the speed of batched transaction insertion.
  1888  func BenchmarkPoolBatchInsert100(b *testing.B)   { benchmarkPoolBatchInsert(b, 100) }
  1889  func BenchmarkPoolBatchInsert1000(b *testing.B)  { benchmarkPoolBatchInsert(b, 1000) }
  1890  func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000) }
  1891  
  1892  func benchmarkPoolBatchInsert(b *testing.B, size int) {
  1893  	// Generate a batch of transactions to enqueue into the pool
  1894  	pool, key := setupTxPool()
  1895  	defer pool.Stop()
  1896  
  1897  	account := crypto.PubkeyToAddress(key.PublicKey)
  1898  	pool.currentState.AddBalance(account, big.NewInt(1000000))
  1899  
  1900  	batches := make([]types.Transactions, b.N)
  1901  	for i := 0; i < b.N; i++ {
  1902  		batches[i] = make(types.Transactions, size)
  1903  		for j := 0; j < size; j++ {
  1904  			batches[i][j] = transaction(uint64(size*i+j), 100000, key)
  1905  		}
  1906  	}
  1907  	// Benchmark importing the transactions into the queue
  1908  	b.ResetTimer()
  1909  	for _, batch := range batches {
  1910  		pool.AddRemotes(batch)
  1911  	}
  1912  }