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