123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256 |
- // Copyright 2015 The go-ethereum Authors
- // This file is part of the go-ethereum library.
- //
- // The go-ethereum library is free software: you can redistribute it and/or modify
- // it under the terms of the GNU Lesser General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // The go-ethereum library is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU Lesser General Public License for more details.
- //
- // You should have received a copy of the GNU Lesser General Public License
- // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
- package core
- import (
- "crypto/ecdsa"
- "errors"
- "fmt"
- "io/ioutil"
- "math/big"
- "math/rand"
- "os"
- "reflect"
- "testing"
- "time"
- "github.com/ethereum/go-ethereum/common"
- "github.com/ethereum/go-ethereum/core/mps"
- "github.com/ethereum/go-ethereum/core/rawdb"
- "github.com/ethereum/go-ethereum/core/state"
- "github.com/ethereum/go-ethereum/core/types"
- "github.com/ethereum/go-ethereum/crypto"
- "github.com/ethereum/go-ethereum/event"
- "github.com/ethereum/go-ethereum/params"
- "github.com/ethereum/go-ethereum/trie"
- )
- // testTxPoolConfig is a transaction pool configuration without stateful disk
- // sideeffects used during testing.
- var testTxPoolConfig TxPoolConfig
- func init() {
- testTxPoolConfig = DefaultTxPoolConfig
- testTxPoolConfig.Journal = ""
- }
- type testBlockChain struct {
- statedb *state.StateDB
- psManager mps.PrivateStateRepository
- gasLimit uint64
- chainHeadFeed *event.Feed
- }
- func (bc *testBlockChain) CurrentBlock() *types.Block {
- return types.NewBlock(&types.Header{
- GasLimit: bc.gasLimit,
- }, nil, nil, nil, trie.NewStackTrie(nil))
- }
- func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
- return bc.CurrentBlock()
- }
- func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, mps.PrivateStateRepository, error) {
- return bc.statedb, bc.psManager, nil
- }
- func (bc *testBlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
- return bc.chainHeadFeed.Subscribe(ch)
- }
- func transaction(nonce uint64, gaslimit uint64, key *ecdsa.PrivateKey) *types.Transaction {
- return pricedTransaction(nonce, gaslimit, big.NewInt(1), key)
- }
- func pricedTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
- tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, gasprice, nil), types.HomesteadSigner{}, key)
- return tx
- }
- func pricedDataTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey, bytes uint64) *types.Transaction {
- data := make([]byte, bytes)
- rand.Read(data)
- tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(0), gaslimit, gasprice, data), types.HomesteadSigner{}, key)
- return tx
- }
- // Quorum - created setupTxPoolWithConfig(...) from original setupTxPool() to allow passing a ChainConfig as argument
- func setupTxPoolWithConfig(config *params.ChainConfig) (*TxPool, *ecdsa.PrivateKey) {
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 10000000, new(event.Feed)}
- key, _ := crypto.GenerateKey()
- pool := NewTxPool(testTxPoolConfig, config, blockchain)
- return pool, key
- }
- func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
- return setupTxPoolWithConfig(params.TestChainConfig)
- }
- func setupQuorumTxPool() (*TxPool, *ecdsa.PrivateKey) {
- return setupTxPoolWithConfig(params.QuorumTestChainConfig)
- }
- // validateTxPoolInternals checks various consistency invariants within the pool.
- func validateTxPoolInternals(pool *TxPool) error {
- pool.mu.RLock()
- defer pool.mu.RUnlock()
- // Ensure the total transaction set is consistent with pending + queued
- pending, queued := pool.stats()
- if total := pool.all.Count(); total != pending+queued {
- return fmt.Errorf("total transaction count %d != %d pending + %d queued", total, pending, queued)
- }
- pool.priced.Reheap()
- priced, remote := pool.priced.remotes.Len(), pool.all.RemoteCount()
- if priced != remote {
- return fmt.Errorf("total priced transaction count %d != %d", priced, remote)
- }
- // Ensure the next nonce to assign is the correct one
- for addr, txs := range pool.pending {
- // Find the last transaction
- var last uint64
- for nonce := range txs.txs.items {
- if last < nonce {
- last = nonce
- }
- }
- if nonce := pool.pendingNonces.get(addr); nonce != last+1 {
- return fmt.Errorf("pending nonce mismatch: have %v, want %v", nonce, last+1)
- }
- }
- return nil
- }
- // validateEvents checks that the correct number of transaction addition events
- // were fired on the pool's event feed.
- func validateEvents(events chan NewTxsEvent, count int) error {
- var received []*types.Transaction
- for len(received) < count {
- select {
- case ev := <-events:
- received = append(received, ev.Txs...)
- case <-time.After(time.Second):
- return fmt.Errorf("event #%d not fired", len(received))
- }
- }
- if len(received) > count {
- return fmt.Errorf("more than %d events fired: %v", count, received[count:])
- }
- select {
- case ev := <-events:
- return fmt.Errorf("more than %d events fired: %v", count, ev.Txs)
- case <-time.After(50 * time.Millisecond):
- // This branch should be "default", but it's a data race between goroutines,
- // reading the event channel and pushing into it, so better wait a bit ensuring
- // really nothing gets injected.
- }
- return nil
- }
- func deriveSender(tx *types.Transaction) (common.Address, error) {
- return types.Sender(types.HomesteadSigner{}, tx)
- }
- type testChain struct {
- *testBlockChain
- address common.Address
- trigger *bool
- }
- // testChain.State() is used multiple times to reset the pending state.
- // when simulate is true it will create a state that indicates
- // that tx0 and tx1 are included in the chain.
- func (c *testChain) State() (*state.StateDB, mps.PrivateStateRepository, error) {
- // delay "state change" by one. The tx pool fetches the
- // state multiple times and by delaying it a bit we simulate
- // a state change between those fetches.
- stdb := c.statedb
- if *c.trigger {
- c.statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- // simulate that the new head block included tx0 and tx1
- c.statedb.SetNonce(c.address, 2)
- c.statedb.SetBalance(c.address, new(big.Int).SetUint64(params.Ether))
- *c.trigger = false
- }
- return stdb, nil, nil
- }
- // This test simulates a scenario where a new block is imported during a
- // state reset and tests whether the pending state is in sync with the
- // block head event that initiated the resetState().
- func TestStateChangeDuringTransactionPoolReset(t *testing.T) {
- t.Parallel()
- var (
- key, _ = crypto.GenerateKey()
- address = crypto.PubkeyToAddress(key.PublicKey)
- statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- trigger = false
- )
- // setup pool with 2 transaction in it
- statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
- blockchain := &testChain{&testBlockChain{statedb, nil, 1000000000, new(event.Feed)}, address, &trigger}
- tx0 := transaction(0, 100000, key)
- tx1 := transaction(1, 100000, key)
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- nonce := pool.Nonce(address)
- if nonce != 0 {
- t.Fatalf("Invalid nonce, want 0, got %d", nonce)
- }
- pool.AddRemotesSync([]*types.Transaction{tx0, tx1})
- nonce = pool.Nonce(address)
- if nonce != 2 {
- t.Fatalf("Invalid nonce, want 2, got %d", nonce)
- }
- // trigger state change in the background
- trigger = true
- <-pool.requestReset(nil, nil)
- _, err := pool.Pending()
- if err != nil {
- t.Fatalf("Could not fetch pending transactions: %v", err)
- }
- nonce = pool.Nonce(address)
- if nonce != 2 {
- t.Fatalf("Invalid nonce, want 2, got %d", nonce)
- }
- }
- // Test for transactions that are invalid on Ethereum & Quorum
- func TestInvalidTransactions(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- tx := transaction(0, 100, key)
- from, _ := deriveSender(tx)
- pool.currentState.AddBalance(from, big.NewInt(1))
- if err := pool.AddRemote(tx); !errors.Is(err, ErrInsufficientFunds) {
- t.Error("expected", ErrInsufficientFunds, "; got", err)
- }
- balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(new(big.Int).SetUint64(tx.Gas()), tx.GasPrice()))
- pool.currentState.AddBalance(from, balance)
- if err := pool.AddRemote(tx); !errors.Is(err, ErrIntrinsicGas) {
- t.Error("expected", ErrIntrinsicGas, "; got", err)
- }
- pool.currentState.SetNonce(from, 1)
- pool.currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
- tx = transaction(0, 100000, key)
- if err := pool.AddRemote(tx); !errors.Is(err, ErrNonceTooLow) {
- t.Error("expected", ErrNonceTooLow, "; got", err)
- }
- tx = transaction(1, 100000, key)
- pool.gasPrice = big.NewInt(1000)
- if err := pool.AddRemote(tx); err != ErrUnderpriced {
- t.Error("expected", ErrUnderpriced, "; got", err)
- }
- if err := pool.AddLocal(tx); err != nil {
- t.Error("expected", nil, "; got", err)
- }
- tooMuchGas := pool.currentMaxGas + 1
- tx1 := transaction(2, tooMuchGas, key)
- if err := pool.AddRemote(tx1); err != ErrGasLimit {
- t.Error("expected", ErrGasLimit, "; got", err)
- }
- data := make([]byte, (64*1024)+1)
- tx2, _ := types.SignTx(types.NewTransaction(2, common.Address{}, big.NewInt(100), 100000, big.NewInt(1), data), types.HomesteadSigner{}, key)
- if err := pool.AddRemote(tx2); err != ErrOversizedData {
- t.Error("expected", ErrOversizedData, "; got", err)
- }
- // Quorum
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- params.QuorumTestChainConfig.TransactionSizeLimit = 128
- pool2 := NewTxPool(testTxPoolConfig, params.QuorumTestChainConfig, blockchain)
- pool2.currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
- data2 := make([]byte, (127 * 1024))
- tx3, _ := types.SignTx(types.NewTransaction(2, common.Address{}, big.NewInt(100), 100000, big.NewInt(0), data2), types.HomesteadSigner{}, key)
- if err := pool2.AddRemote(tx3); err != ErrIntrinsicGas {
- t.Error("expected", ErrIntrinsicGas, "; got", err)
- }
- data3 := make([]byte, (128*1024)+1)
- tx4, _ := types.SignTx(types.NewTransaction(2, common.Address{}, big.NewInt(100), 100000, big.NewInt(0), data3), types.HomesteadSigner{}, key)
- if err := pool2.AddRemote(tx4); err != ErrOversizedData {
- t.Error("expected", ErrOversizedData, "; got", err)
- }
- tx5, _ := types.SignTx(types.NewTransaction(1, common.Address{}, big.NewInt(100), 0, big.NewInt(0), nil), types.HomesteadSigner{}, key)
- balance = new(big.Int).Add(tx5.Value(), new(big.Int).Mul(new(big.Int).SetUint64(tx5.Gas()), tx5.GasPrice()))
- from, _ = deriveSender(tx5)
- pool2.currentState.AddBalance(from, balance)
- tx5.SetPrivate()
- if err := pool2.AddRemote(tx5); err != ErrEtherValueUnsupported {
- t.Error("expected", ErrEtherValueUnsupported, "; got", err)
- }
- }
- //Test for transactions that are only invalid on Quorum
- func TestQuorumInvalidTransactions(t *testing.T) {
- pool, key := setupQuorumTxPool()
- defer pool.Stop()
- tx := transaction(0, 0, key)
- if err := pool.AddRemote(tx); err != ErrInvalidGasPrice {
- t.Error("expected", ErrInvalidGasPrice, "; got", err)
- }
- }
- //Test for transactions that are only invalid on Quorum
- func TestQuorumTransactionSizeLimitTransition(t *testing.T) {
- pool, key := setupQuorumTxPool()
- defer pool.Stop()
- data := make([]byte, (64*1024)+1)
- tx, _ := types.SignTx(types.NewTransaction(2, common.Address{}, big.NewInt(0), 283148, big.NewInt(0), data), types.HomesteadSigner{}, key)
- if err := pool.AddRemote(tx); err != ErrOversizedData {
- t.Error("expected", ErrOversizedData, "; got", err)
- }
- pool.chainconfig.Transitions = []params.Transition{{
- Block: big.NewInt(0),
- TransactionSizeLimit: 128,
- }}
- if err := pool.AddRemote(tx); err != nil {
- t.Error("expected no error; got", err)
- }
- }
- func TestValidateTx_whenValueZeroTransferForPrivateTransaction(t *testing.T) {
- pool, key := setupQuorumTxPool()
- defer pool.Stop()
- zeroValue := common.Big0
- zeroGasPrice := common.Big0
- defaultTxPoolGasLimit := uint64(1000000)
- arbitraryTx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, zeroValue, defaultTxPoolGasLimit, zeroGasPrice, nil), types.HomesteadSigner{}, key)
- arbitraryTx.SetPrivate()
- if err := pool.AddRemote(arbitraryTx); err != ErrEtherValueUnsupported {
- t.Error("expected:", ErrEtherValueUnsupported, "; got:", err)
- }
- }
- func TestValidateTx_whenValueNonZeroTransferForPrivateTransaction(t *testing.T) {
- pool, key := setupQuorumTxPool()
- defer pool.Stop()
- arbitraryValue := common.Big3
- arbitraryTx, balance, from := newPrivateTransaction(arbitraryValue, nil, key)
- pool.currentState.AddBalance(from, balance)
- if err := pool.AddRemote(arbitraryTx); err != ErrEtherValueUnsupported {
- t.Error("expected: ", ErrEtherValueUnsupported, "; got:", err)
- }
- }
- func newPrivateTransaction(value *big.Int, data []byte, key *ecdsa.PrivateKey) (*types.Transaction, *big.Int, common.Address) {
- zeroGasPrice := common.Big0
- defaultTxPoolGasLimit := uint64(1000000)
- arbitraryTx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, value, defaultTxPoolGasLimit, zeroGasPrice, data), types.HomesteadSigner{}, key)
- arbitraryTx.SetPrivate()
- balance := new(big.Int).Add(arbitraryTx.Value(), new(big.Int).Mul(new(big.Int).SetUint64(arbitraryTx.Gas()), arbitraryTx.GasPrice()))
- from, _ := deriveSender(arbitraryTx)
- return arbitraryTx, balance, from
- }
- func TestValidateTx_whenValueNonZeroWithSmartContractForPrivateTransaction(t *testing.T) {
- pool, key := setupQuorumTxPool()
- defer pool.Stop()
- arbitraryValue := common.Big3
- arbitraryTx, balance, from := newPrivateTransaction(arbitraryValue, []byte("arbitrary bytecode"), key)
- pool.currentState.AddBalance(from, balance)
- if err := pool.AddRemote(arbitraryTx); err != ErrEtherValueUnsupported {
- t.Error("expected: ", ErrEtherValueUnsupported, "; got:", err)
- }
- }
- func TestTransactionQueue(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- tx := transaction(0, 100, key)
- from, _ := deriveSender(tx)
- pool.currentState.AddBalance(from, big.NewInt(1000))
- <-pool.requestReset(nil, nil)
- pool.enqueueTx(tx.Hash(), tx, false, true)
- <-pool.requestPromoteExecutables(newAccountSet(pool.signer, from))
- if len(pool.pending) != 1 {
- t.Error("expected valid txs to be 1 is", len(pool.pending))
- }
- tx = transaction(1, 100, key)
- from, _ = deriveSender(tx)
- pool.currentState.SetNonce(from, 2)
- pool.enqueueTx(tx.Hash(), tx, false, true)
- <-pool.requestPromoteExecutables(newAccountSet(pool.signer, from))
- if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok {
- t.Error("expected transaction to be in tx pool")
- }
- if len(pool.queue) > 0 {
- t.Error("expected transaction queue to be empty. is", len(pool.queue))
- }
- }
- func TestTransactionQueue2(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- tx1 := transaction(0, 100, key)
- tx2 := transaction(10, 100, key)
- tx3 := transaction(11, 100, key)
- from, _ := deriveSender(tx1)
- pool.currentState.AddBalance(from, big.NewInt(1000))
- pool.reset(nil, nil)
- pool.enqueueTx(tx1.Hash(), tx1, false, true)
- pool.enqueueTx(tx2.Hash(), tx2, false, true)
- pool.enqueueTx(tx3.Hash(), tx3, false, true)
- pool.promoteExecutables([]common.Address{from})
- if len(pool.pending) != 1 {
- t.Error("expected pending length to be 1, got", len(pool.pending))
- }
- if pool.queue[from].Len() != 2 {
- t.Error("expected len(queue) == 2, got", pool.queue[from].Len())
- }
- }
- func TestTransactionNegativeValue(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(-1), 100, big.NewInt(1), nil), types.HomesteadSigner{}, key)
- from, _ := deriveSender(tx)
- pool.currentState.AddBalance(from, big.NewInt(1))
- if err := pool.AddRemote(tx); err != ErrNegativeValue {
- t.Error("expected", ErrNegativeValue, "got", err)
- }
- }
- func TestTransactionChainFork(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- addr := crypto.PubkeyToAddress(key.PublicKey)
- resetState := func() {
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- statedb.AddBalance(addr, big.NewInt(100000000000000))
- pool.chain = &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- <-pool.requestReset(nil, nil)
- }
- resetState()
- tx := transaction(0, 100000, key)
- if _, err := pool.add(tx, false); err != nil {
- t.Error("didn't expect error", err)
- }
- pool.removeTx(tx.Hash(), true)
- // reset the pool's internal state
- resetState()
- if _, err := pool.add(tx, false); err != nil {
- t.Error("didn't expect error", err)
- }
- }
- func TestTransactionDoubleNonce(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- addr := crypto.PubkeyToAddress(key.PublicKey)
- resetState := func() {
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- statedb.AddBalance(addr, big.NewInt(100000000000000))
- pool.chain = &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- <-pool.requestReset(nil, nil)
- }
- resetState()
- signer := types.HomesteadSigner{}
- tx1, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100000, big.NewInt(1), nil), signer, key)
- tx2, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(2), nil), signer, key)
- tx3, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(1), nil), signer, key)
- // Add the first two transaction, ensure higher priced stays only
- if replace, err := pool.add(tx1, false); err != nil || replace {
- t.Errorf("first transaction insert failed (%v) or reported replacement (%v)", err, replace)
- }
- if replace, err := pool.add(tx2, false); err != nil || !replace {
- t.Errorf("second transaction insert failed (%v) or not reported replacement (%v)", err, replace)
- }
- <-pool.requestPromoteExecutables(newAccountSet(signer, addr))
- if pool.pending[addr].Len() != 1 {
- t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
- }
- if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
- t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
- }
- // Add the third transaction and ensure it's not saved (smaller price)
- pool.add(tx3, false)
- <-pool.requestPromoteExecutables(newAccountSet(signer, addr))
- if pool.pending[addr].Len() != 1 {
- t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
- }
- if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
- t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
- }
- // Ensure the total transaction count is correct
- if pool.all.Count() != 1 {
- t.Error("expected 1 total transactions, got", pool.all.Count())
- }
- }
- func TestTransactionMissingNonce(t *testing.T) {
- t.Parallel()
- pool, key := setupTxPool()
- defer pool.Stop()
- addr := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(addr, big.NewInt(100000000000000))
- tx := transaction(1, 100000, key)
- if _, err := pool.add(tx, false); err != nil {
- t.Error("didn't expect error", err)
- }
- if len(pool.pending) != 0 {
- t.Error("expected 0 pending transactions, got", len(pool.pending))
- }
- if pool.queue[addr].Len() != 1 {
- t.Error("expected 1 queued transaction, got", pool.queue[addr].Len())
- }
- if pool.all.Count() != 1 {
- t.Error("expected 1 total transactions, got", pool.all.Count())
- }
- }
- func TestTransactionNonceRecovery(t *testing.T) {
- t.Parallel()
- const n = 10
- pool, key := setupTxPool()
- defer pool.Stop()
- addr := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.SetNonce(addr, n)
- pool.currentState.AddBalance(addr, big.NewInt(100000000000000))
- <-pool.requestReset(nil, nil)
- tx := transaction(n, 100000, key)
- if err := pool.AddRemote(tx); err != nil {
- t.Error(err)
- }
- // simulate some weird re-order of transactions and missing nonce(s)
- pool.currentState.SetNonce(addr, n-1)
- <-pool.requestReset(nil, nil)
- if fn := pool.Nonce(addr); fn != n-1 {
- t.Errorf("expected nonce to be %d, got %d", n-1, fn)
- }
- }
- // Tests that if an account runs out of funds, any pending and queued transactions
- // are dropped.
- func TestTransactionDropping(t *testing.T) {
- t.Parallel()
- // Create a test account and fund it
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000))
- // Add some pending and some queued transactions
- var (
- tx0 = transaction(0, 100, key)
- tx1 = transaction(1, 200, key)
- tx2 = transaction(2, 300, key)
- tx10 = transaction(10, 100, key)
- tx11 = transaction(11, 200, key)
- tx12 = transaction(12, 300, key)
- )
- pool.all.Add(tx0, false)
- pool.priced.Put(tx0, false)
- pool.promoteTx(account, tx0.Hash(), tx0)
- pool.all.Add(tx1, false)
- pool.priced.Put(tx1, false)
- pool.promoteTx(account, tx1.Hash(), tx1)
- pool.all.Add(tx2, false)
- pool.priced.Put(tx2, false)
- pool.promoteTx(account, tx2.Hash(), tx2)
- pool.enqueueTx(tx10.Hash(), tx10, false, true)
- pool.enqueueTx(tx11.Hash(), tx11, false, true)
- pool.enqueueTx(tx12.Hash(), tx12, false, true)
- // Check that pre and post validations leave the pool as is
- if pool.pending[account].Len() != 3 {
- t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3)
- }
- if pool.queue[account].Len() != 3 {
- t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3)
- }
- if pool.all.Count() != 6 {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6)
- }
- <-pool.requestReset(nil, nil)
- if pool.pending[account].Len() != 3 {
- t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3)
- }
- if pool.queue[account].Len() != 3 {
- t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3)
- }
- if pool.all.Count() != 6 {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6)
- }
- // Reduce the balance of the account, and check that invalidated transactions are dropped
- pool.currentState.AddBalance(account, big.NewInt(-650))
- <-pool.requestReset(nil, nil)
- if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
- t.Errorf("funded pending transaction missing: %v", tx0)
- }
- if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; !ok {
- t.Errorf("funded pending transaction missing: %v", tx0)
- }
- if _, ok := pool.pending[account].txs.items[tx2.Nonce()]; ok {
- t.Errorf("out-of-fund pending transaction present: %v", tx1)
- }
- if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
- t.Errorf("funded queued transaction missing: %v", tx10)
- }
- if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; !ok {
- t.Errorf("funded queued transaction missing: %v", tx10)
- }
- if _, ok := pool.queue[account].txs.items[tx12.Nonce()]; ok {
- t.Errorf("out-of-fund queued transaction present: %v", tx11)
- }
- if pool.all.Count() != 4 {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 4)
- }
- // Reduce the block gas limit, check that invalidated transactions are dropped
- pool.chain.(*testBlockChain).gasLimit = 100
- <-pool.requestReset(nil, nil)
- if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
- t.Errorf("funded pending transaction missing: %v", tx0)
- }
- if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok {
- t.Errorf("over-gased pending transaction present: %v", tx1)
- }
- if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
- t.Errorf("funded queued transaction missing: %v", tx10)
- }
- if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok {
- t.Errorf("over-gased queued transaction present: %v", tx11)
- }
- if pool.all.Count() != 2 {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 2)
- }
- }
- // Tests that if a transaction is dropped from the current pending pool (e.g. out
- // of fund), all consecutive (still valid, but not executable) transactions are
- // postponed back into the future queue to prevent broadcasting them.
- func TestTransactionPostponing(t *testing.T) {
- t.Parallel()
- // Create the pool to test the postponing with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create two test accounts to produce different gap profiles with
- keys := make([]*ecdsa.PrivateKey, 2)
- accs := make([]common.Address, len(keys))
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- accs[i] = crypto.PubkeyToAddress(keys[i].PublicKey)
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(50100))
- }
- // Add a batch consecutive pending transactions for validation
- txs := []*types.Transaction{}
- for i, key := range keys {
- for j := 0; j < 100; j++ {
- var tx *types.Transaction
- if (i+j)%2 == 0 {
- tx = transaction(uint64(j), 25000, key)
- } else {
- tx = transaction(uint64(j), 50000, key)
- }
- txs = append(txs, tx)
- }
- }
- for i, err := range pool.AddRemotesSync(txs) {
- if err != nil {
- t.Fatalf("tx %d: failed to add transactions: %v", i, err)
- }
- }
- // Check that pre and post validations leave the pool as is
- if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) {
- t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs))
- }
- if len(pool.queue) != 0 {
- t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0)
- }
- if pool.all.Count() != len(txs) {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs))
- }
- <-pool.requestReset(nil, nil)
- if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) {
- t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs))
- }
- if len(pool.queue) != 0 {
- t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0)
- }
- if pool.all.Count() != len(txs) {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs))
- }
- // Reduce the balance of the account, and check that transactions are reorganised
- for _, addr := range accs {
- pool.currentState.AddBalance(addr, big.NewInt(-1))
- }
- <-pool.requestReset(nil, nil)
- // The first account's first transaction remains valid, check that subsequent
- // ones are either filtered out, or queued up for later.
- if _, ok := pool.pending[accs[0]].txs.items[txs[0].Nonce()]; !ok {
- t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txs[0])
- }
- if _, ok := pool.queue[accs[0]].txs.items[txs[0].Nonce()]; ok {
- t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txs[0])
- }
- for i, tx := range txs[1:100] {
- if i%2 == 1 {
- if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok {
- t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx)
- }
- if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; !ok {
- t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx)
- }
- } else {
- if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok {
- t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx)
- }
- if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; ok {
- t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx)
- }
- }
- }
- // The second account's first transaction got invalid, check that all transactions
- // are either filtered out, or queued up for later.
- if pool.pending[accs[1]] != nil {
- t.Errorf("invalidated account still has pending transactions")
- }
- for i, tx := range txs[100:] {
- if i%2 == 1 {
- if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; !ok {
- t.Errorf("tx %d: valid but future transaction missing from future queue: %v", 100+i, tx)
- }
- } else {
- if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; ok {
- t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", 100+i, tx)
- }
- }
- }
- if pool.all.Count() != len(txs)/2 {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs)/2)
- }
- }
- // Tests that if the transaction pool has both executable and non-executable
- // transactions from an origin account, filling the nonce gap moves all queued
- // ones into the pending pool.
- func TestTransactionGapFilling(t *testing.T) {
- t.Parallel()
- // Create a test account and fund it
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000))
- // Keep track of transaction events to ensure all executables get announced
- events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
- sub := pool.txFeed.Subscribe(events)
- defer sub.Unsubscribe()
- // Create a pending and a queued transaction with a nonce-gap in between
- pool.AddRemotesSync([]*types.Transaction{
- transaction(0, 100000, key),
- transaction(2, 100000, key),
- })
- pending, queued := pool.Stats()
- if pending != 1 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1)
- }
- if queued != 1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
- }
- if err := validateEvents(events, 1); err != nil {
- t.Fatalf("original event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Fill the nonce gap and ensure all transactions become pending
- if err := pool.addRemoteSync(transaction(1, 100000, key)); err != nil {
- t.Fatalf("failed to add gapped transaction: %v", err)
- }
- pending, queued = pool.Stats()
- if pending != 3 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateEvents(events, 2); err != nil {
- t.Fatalf("gap-filling event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that if the transaction count belonging to a single account goes above
- // some threshold, the higher transactions are dropped to prevent DOS attacks.
- func TestTransactionQueueAccountLimiting(t *testing.T) {
- t.Parallel()
- // Create a test account and fund it
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000))
- // Keep queuing up transactions and make sure all above a limit are dropped
- for i := uint64(1); i <= testTxPoolConfig.AccountQueue+5; i++ {
- if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil {
- t.Fatalf("tx %d: failed to add transaction: %v", i, err)
- }
- if len(pool.pending) != 0 {
- t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0)
- }
- if i <= testTxPoolConfig.AccountQueue {
- if pool.queue[account].Len() != int(i) {
- t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i)
- }
- } else {
- if pool.queue[account].Len() != int(testTxPoolConfig.AccountQueue) {
- t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), testTxPoolConfig.AccountQueue)
- }
- }
- }
- if pool.all.Count() != int(testTxPoolConfig.AccountQueue) {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue)
- }
- }
- // Tests that if the transaction count belonging to multiple accounts go above
- // some threshold, the higher transactions are dropped to prevent DOS attacks.
- //
- // This logic should not hold for local transactions, unless the local tracking
- // mechanism is disabled.
- func TestTransactionQueueGlobalLimiting(t *testing.T) {
- testTransactionQueueGlobalLimiting(t, false)
- }
- func TestTransactionQueueGlobalLimitingNoLocals(t *testing.T) {
- testTransactionQueueGlobalLimiting(t, true)
- }
- func testTransactionQueueGlobalLimiting(t *testing.T, nolocals bool) {
- t.Parallel()
- // Create the pool to test the limit enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.NoLocals = nolocals
- config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible)
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create a number of test accounts and fund them (last one will be the local)
- keys := make([]*ecdsa.PrivateKey, 5)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- local := keys[len(keys)-1]
- // Generate and queue a batch of transactions
- nonces := make(map[common.Address]uint64)
- txs := make(types.Transactions, 0, 3*config.GlobalQueue)
- for len(txs) < cap(txs) {
- key := keys[rand.Intn(len(keys)-1)] // skip adding transactions with the local account
- addr := crypto.PubkeyToAddress(key.PublicKey)
- txs = append(txs, transaction(nonces[addr]+1, 100000, key))
- nonces[addr]++
- }
- // Import the batch and verify that limits have been enforced
- pool.AddRemotesSync(txs)
- queued := 0
- for addr, list := range pool.queue {
- if list.Len() > int(config.AccountQueue) {
- t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue)
- }
- queued += list.Len()
- }
- if queued > int(config.GlobalQueue) {
- t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue)
- }
- // Generate a batch of transactions from the local account and import them
- txs = txs[:0]
- for i := uint64(0); i < 3*config.GlobalQueue; i++ {
- txs = append(txs, transaction(i+1, 100000, local))
- }
- pool.AddLocals(txs)
- // If locals are disabled, the previous eviction algorithm should apply here too
- if nolocals {
- queued := 0
- for addr, list := range pool.queue {
- if list.Len() > int(config.AccountQueue) {
- t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue)
- }
- queued += list.Len()
- }
- if queued > int(config.GlobalQueue) {
- t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue)
- }
- } else {
- // Local exemptions are enabled, make sure the local account owned the queue
- if len(pool.queue) != 1 {
- t.Errorf("multiple accounts in queue: have %v, want %v", len(pool.queue), 1)
- }
- // Also ensure no local transactions are ever dropped, even if above global limits
- if queued := pool.queue[crypto.PubkeyToAddress(local.PublicKey)].Len(); uint64(queued) != 3*config.GlobalQueue {
- t.Fatalf("local account queued transaction count mismatch: have %v, want %v", queued, 3*config.GlobalQueue)
- }
- }
- }
- // Tests that if an account remains idle for a prolonged amount of time, any
- // non-executable transactions queued up are dropped to prevent wasting resources
- // on shuffling them around.
- //
- // This logic should not hold for local transactions, unless the local tracking
- // mechanism is disabled.
- func TestTransactionQueueTimeLimiting(t *testing.T) {
- testTransactionQueueTimeLimiting(t, false)
- }
- func TestTransactionQueueTimeLimitingNoLocals(t *testing.T) {
- testTransactionQueueTimeLimiting(t, true)
- }
- func testTransactionQueueTimeLimiting(t *testing.T, nolocals bool) {
- // Reduce the eviction interval to a testable amount
- defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
- evictionInterval = time.Millisecond * 100
- // Create the pool to test the non-expiration enforcement
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.Lifetime = time.Second
- config.NoLocals = nolocals
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create two test accounts to ensure remotes expire but locals do not
- local, _ := crypto.GenerateKey()
- remote, _ := crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
- pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))
- // Add the two transactions and ensure they both are queued up
- if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
- t.Fatalf("failed to add local transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), remote)); err != nil {
- t.Fatalf("failed to add remote transaction: %v", err)
- }
- pending, queued := pool.Stats()
- if pending != 0 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
- }
- if queued != 2 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Allow the eviction interval to run
- time.Sleep(2 * evictionInterval)
- // Transactions should not be evicted from the queue yet since lifetime duration has not passed
- pending, queued = pool.Stats()
- if pending != 0 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
- }
- if queued != 2 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Wait a bit for eviction to run and clean up any leftovers, and ensure only the local remains
- time.Sleep(2 * config.Lifetime)
- pending, queued = pool.Stats()
- if pending != 0 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
- }
- if nolocals {
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- } else {
- if queued != 1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
- }
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // remove current transactions and increase nonce to prepare for a reset and cleanup
- statedb.SetNonce(crypto.PubkeyToAddress(remote.PublicKey), 2)
- statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2)
- <-pool.requestReset(nil, nil)
- // make sure queue, pending are cleared
- pending, queued = pool.Stats()
- if pending != 0 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Queue gapped transactions
- if err := pool.AddLocal(pricedTransaction(4, 100000, big.NewInt(1), local)); err != nil {
- t.Fatalf("failed to add remote transaction: %v", err)
- }
- if err := pool.addRemoteSync(pricedTransaction(4, 100000, big.NewInt(1), remote)); err != nil {
- t.Fatalf("failed to add remote transaction: %v", err)
- }
- time.Sleep(5 * evictionInterval) // A half lifetime pass
- // Queue executable transactions, the life cycle should be restarted.
- if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil {
- t.Fatalf("failed to add remote transaction: %v", err)
- }
- if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(1), remote)); err != nil {
- t.Fatalf("failed to add remote transaction: %v", err)
- }
- time.Sleep(6 * evictionInterval)
- // All gapped transactions shouldn't be kicked out
- pending, queued = pool.Stats()
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- if queued != 2 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // The whole life time pass after last promotion, kick out stale transactions
- time.Sleep(2 * config.Lifetime)
- pending, queued = pool.Stats()
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- if nolocals {
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- } else {
- if queued != 1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
- }
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that even if the transaction count belonging to a single account goes
- // above some threshold, as long as the transactions are executable, they are
- // accepted.
- func TestTransactionPendingLimiting(t *testing.T) {
- t.Parallel()
- // Create a test account and fund it
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000))
- // Keep track of transaction events to ensure all executables get announced
- events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
- sub := pool.txFeed.Subscribe(events)
- defer sub.Unsubscribe()
- // Keep queuing up transactions and make sure all above a limit are dropped
- for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ {
- if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil {
- t.Fatalf("tx %d: failed to add transaction: %v", i, err)
- }
- if pool.pending[account].Len() != int(i)+1 {
- t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1)
- }
- if len(pool.queue) != 0 {
- t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
- }
- }
- if pool.all.Count() != int(testTxPoolConfig.AccountQueue+5) {
- t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue+5)
- }
- if err := validateEvents(events, int(testTxPoolConfig.AccountQueue+5)); err != nil {
- t.Fatalf("event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that if the transaction count belonging to multiple accounts go above
- // some hard threshold, the higher transactions are dropped to prevent DOS
- // attacks.
- func TestTransactionPendingGlobalLimiting(t *testing.T) {
- t.Parallel()
- // Create the pool to test the limit enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.GlobalSlots = config.AccountSlots * 10
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create a number of test accounts and fund them
- keys := make([]*ecdsa.PrivateKey, 5)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- // Generate and queue a batch of transactions
- nonces := make(map[common.Address]uint64)
- txs := types.Transactions{}
- for _, key := range keys {
- addr := crypto.PubkeyToAddress(key.PublicKey)
- for j := 0; j < int(config.GlobalSlots)/len(keys)*2; j++ {
- txs = append(txs, transaction(nonces[addr], 100000, key))
- nonces[addr]++
- }
- }
- // Import the batch and verify that limits have been enforced
- pool.AddRemotesSync(txs)
- pending := 0
- for _, list := range pool.pending {
- pending += list.Len()
- }
- if pending > int(config.GlobalSlots) {
- t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, config.GlobalSlots)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Test the limit on transaction size is enforced correctly.
- // This test verifies every transaction having allowed size
- // is added to the pool, and longer transactions are rejected.
- func TestTransactionAllowedTxSize(t *testing.T) {
- t.Parallel()
- // Create a test account and fund it
- pool, key := setupQuorumTxPool()
- defer pool.Stop()
- pool.chainconfig.Transitions = []params.Transition{}
- pool.chainconfig.TransactionSizeLimit = params.QuorumTestChainConfig.TransactionSizeLimit
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000000))
- // Compute maximal data size for transactions (lower bound).
- //
- // It is assumed the fields in the transaction (except of the data) are:
- // - nonce <= 32 bytes
- // - gasPrice <= 32 bytes
- // - gasLimit <= 32 bytes
- // - recipient == 20 bytes
- // - value <= 32 bytes
- // - signature == 65 bytes
- // All those fields are summed up to at most 213 bytes.
- baseSize := uint64(213)
- txMaxSize := params.QuorumTestChainConfig.TransactionSizeLimit * 1024
- dataSize := txMaxSize - baseSize
- // Try adding a transaction with maximal allowed size
- gasPrice := big.NewInt(0)
- tx := pricedDataTransaction(0, pool.currentMaxGas, gasPrice, key, dataSize)
- if err := pool.addRemoteSync(tx); err != nil {
- t.Fatalf("failed to add transaction of size %d, close to maximal: %v", int(tx.Size()), err)
- }
- // Try adding a transaction with random allowed size
- if err := pool.addRemoteSync(pricedDataTransaction(1, pool.currentMaxGas, gasPrice, key, uint64(rand.Intn(int(dataSize))))); err != nil {
- t.Fatalf("failed to add transaction of random allowed size: %v", err)
- }
- // Try adding a transaction of minimal not allowed size
- if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, gasPrice, key, txMaxSize)); err == nil {
- t.Fatalf("expected rejection on slightly oversize transaction")
- }
- // Try adding a transaction of random not allowed size
- if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, gasPrice, key, dataSize+1+uint64(rand.Intn(10*int(txMaxSize))))); err == nil {
- t.Fatalf("expected rejection on oversize transaction")
- }
- // Run some sanity checks on the pool internals
- pending, queued := pool.Stats()
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that if transactions start being capped, transactions are also removed from 'all'
- func TestTransactionCapClearsFromAll(t *testing.T) {
- t.Parallel()
- // Create the pool to test the limit enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.AccountSlots = 2
- config.AccountQueue = 2
- config.GlobalSlots = 8
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create a number of test accounts and fund them
- key, _ := crypto.GenerateKey()
- addr := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(addr, big.NewInt(1000000))
- txs := types.Transactions{}
- for j := 0; j < int(config.GlobalSlots)*2; j++ {
- txs = append(txs, transaction(uint64(j), 100000, key))
- }
- // Import the batch and verify that limits have been enforced
- pool.AddRemotes(txs)
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that if the transaction count belonging to multiple accounts go above
- // some hard threshold, if they are under the minimum guaranteed slot count then
- // the transactions are still kept.
- func TestTransactionPendingMinimumAllowance(t *testing.T) {
- t.Parallel()
- // Create the pool to test the limit enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.GlobalSlots = 1
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create a number of test accounts and fund them
- keys := make([]*ecdsa.PrivateKey, 5)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- // Generate and queue a batch of transactions
- nonces := make(map[common.Address]uint64)
- txs := types.Transactions{}
- for _, key := range keys {
- addr := crypto.PubkeyToAddress(key.PublicKey)
- for j := 0; j < int(config.AccountSlots)*2; j++ {
- txs = append(txs, transaction(nonces[addr], 100000, key))
- nonces[addr]++
- }
- }
- // Import the batch and verify that limits have been enforced
- pool.AddRemotesSync(txs)
- for addr, list := range pool.pending {
- if list.Len() != int(config.AccountSlots) {
- t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), config.AccountSlots)
- }
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that setting the transaction pool gas price to a higher value correctly
- // discards everything cheaper than that and moves any gapped transactions back
- // from the pending pool to the queue.
- //
- // Note, local transactions are never allowed to be dropped.
- func TestTransactionPoolRepricing(t *testing.T) {
- t.Parallel()
- // Create the pool to test the pricing enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Keep track of transaction events to ensure all executables get announced
- events := make(chan NewTxsEvent, 32)
- sub := pool.txFeed.Subscribe(events)
- defer sub.Unsubscribe()
- // Create a number of test accounts and fund them
- keys := make([]*ecdsa.PrivateKey, 4)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- // Generate and queue a batch of transactions, both pending and queued
- txs := types.Transactions{}
- txs = append(txs, pricedTransaction(0, 100000, big.NewInt(2), keys[0]))
- txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[0]))
- txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[0]))
- txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1]))
- txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[1]))
- txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[1]))
- txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[2]))
- txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2]))
- txs = append(txs, pricedTransaction(3, 100000, big.NewInt(2), keys[2]))
- ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[3])
- // Import the batch and that both pending and queued transactions match up
- pool.AddRemotesSync(txs)
- pool.AddLocal(ltx)
- pending, queued := pool.Stats()
- if pending != 7 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 7)
- }
- if queued != 3 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
- }
- if err := validateEvents(events, 7); err != nil {
- t.Fatalf("original event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Reprice the pool and check that underpriced transactions get dropped
- pool.SetGasPrice(big.NewInt(2))
- pending, queued = pool.Stats()
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- if queued != 5 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 5)
- }
- if err := validateEvents(events, 0); err != nil {
- t.Fatalf("reprice event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Check that we can't add the old transactions back
- if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), keys[0])); err != ErrUnderpriced {
- t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
- }
- if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
- t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), keys[2])); err != ErrUnderpriced {
- t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
- }
- if err := validateEvents(events, 0); err != nil {
- t.Fatalf("post-reprice event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // However we can add local underpriced transactions
- tx := pricedTransaction(1, 100000, big.NewInt(1), keys[3])
- if err := pool.AddLocal(tx); err != nil {
- t.Fatalf("failed to add underpriced local transaction: %v", err)
- }
- if pending, _ = pool.Stats(); pending != 3 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
- }
- if err := validateEvents(events, 1); err != nil {
- t.Fatalf("post-reprice local event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // And we can fill gaps with properly priced transactions
- if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(2), keys[0])); err != nil {
- t.Fatalf("failed to add pending transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), keys[1])); err != nil {
- t.Fatalf("failed to add pending transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), keys[2])); err != nil {
- t.Fatalf("failed to add queued transaction: %v", err)
- }
- if err := validateEvents(events, 5); err != nil {
- t.Fatalf("post-reprice event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that setting the transaction pool gas price to a higher value does not
- // remove local transactions.
- func TestTransactionPoolRepricingKeepsLocals(t *testing.T) {
- t.Parallel()
- // Create the pool to test the pricing enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create a number of test accounts and fund them
- keys := make([]*ecdsa.PrivateKey, 3)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000*1000000))
- }
- // Create transaction (both pending and queued) with a linearly growing gasprice
- for i := uint64(0); i < 500; i++ {
- // Add pending transaction.
- pendingTx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2])
- if err := pool.AddLocal(pendingTx); err != nil {
- t.Fatal(err)
- }
- // Add queued transaction.
- queuedTx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2])
- if err := pool.AddLocal(queuedTx); err != nil {
- t.Fatal(err)
- }
- }
- pending, queued := pool.Stats()
- expPending, expQueued := 500, 500
- validate := func() {
- pending, queued = pool.Stats()
- if pending != expPending {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, expPending)
- }
- if queued != expQueued {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, expQueued)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- validate()
- // Reprice the pool and check that nothing is dropped
- pool.SetGasPrice(big.NewInt(2))
- validate()
- pool.SetGasPrice(big.NewInt(2))
- pool.SetGasPrice(big.NewInt(4))
- pool.SetGasPrice(big.NewInt(8))
- pool.SetGasPrice(big.NewInt(100))
- validate()
- }
- // Tests that when the pool reaches its global transaction limit, underpriced
- // transactions are gradually shifted out for more expensive ones and any gapped
- // pending transactions are moved into the queue.
- //
- // Note, local transactions are never allowed to be dropped.
- func TestTransactionPoolUnderpricing(t *testing.T) {
- t.Parallel()
- // Create the pool to test the pricing enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.GlobalSlots = 2
- config.GlobalQueue = 2
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Keep track of transaction events to ensure all executables get announced
- events := make(chan NewTxsEvent, 32)
- sub := pool.txFeed.Subscribe(events)
- defer sub.Unsubscribe()
- // Create a number of test accounts and fund them
- keys := make([]*ecdsa.PrivateKey, 4)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- // Generate and queue a batch of transactions, both pending and queued
- txs := types.Transactions{}
- txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0]))
- txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[0]))
- txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[1]))
- ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[2])
- // Import the batch and that both pending and queued transactions match up
- pool.AddRemotes(txs)
- pool.AddLocal(ltx)
- pending, queued := pool.Stats()
- if pending != 3 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
- }
- if queued != 1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
- }
- if err := validateEvents(events, 3); err != nil {
- t.Fatalf("original event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Ensure that adding an underpriced transaction on block limit fails
- if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
- t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
- }
- // Ensure that adding high priced transactions drops cheap ones, but not own
- 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 -
- t.Fatalf("failed to add well priced transaction: %v", err)
- }
- 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
- t.Fatalf("failed to add well priced transaction: %v", err)
- }
- 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
- t.Fatalf("failed to add well priced transaction: %v", err)
- }
- pending, queued = pool.Stats()
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- if queued != 2 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
- }
- if err := validateEvents(events, 1); err != nil {
- t.Fatalf("additional event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Ensure that adding local transactions can push out even higher priced ones
- ltx = pricedTransaction(1, 100000, big.NewInt(0), keys[2])
- if err := pool.AddLocal(ltx); err != nil {
- t.Fatalf("failed to append underpriced local transaction: %v", err)
- }
- ltx = pricedTransaction(0, 100000, big.NewInt(0), keys[3])
- if err := pool.AddLocal(ltx); err != nil {
- t.Fatalf("failed to add new underpriced local transaction: %v", err)
- }
- pending, queued = pool.Stats()
- if pending != 3 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
- }
- if queued != 1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
- }
- if err := validateEvents(events, 2); err != nil {
- t.Fatalf("local event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that more expensive transactions push out cheap ones from the pool, but
- // without producing instability by creating gaps that start jumping transactions
- // back and forth between queued/pending.
- func TestTransactionPoolStableUnderpricing(t *testing.T) {
- t.Parallel()
- // Create the pool to test the pricing enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.GlobalSlots = 128
- config.GlobalQueue = 0
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Keep track of transaction events to ensure all executables get announced
- events := make(chan NewTxsEvent, 32)
- sub := pool.txFeed.Subscribe(events)
- defer sub.Unsubscribe()
- // Create a number of test accounts and fund them
- keys := make([]*ecdsa.PrivateKey, 2)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- // Fill up the entire queue with the same transaction price points
- txs := types.Transactions{}
- for i := uint64(0); i < config.GlobalSlots; i++ {
- txs = append(txs, pricedTransaction(i, 100000, big.NewInt(1), keys[0]))
- }
- pool.AddRemotesSync(txs)
- pending, queued := pool.Stats()
- if pending != int(config.GlobalSlots) {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateEvents(events, int(config.GlobalSlots)); err != nil {
- t.Fatalf("original event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Ensure that adding high priced transactions drops a cheap, but doesn't produce a gap
- if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil {
- t.Fatalf("failed to add well priced transaction: %v", err)
- }
- pending, queued = pool.Stats()
- if pending != int(config.GlobalSlots) {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateEvents(events, 1); err != nil {
- t.Fatalf("additional event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that the pool rejects duplicate transactions.
- func TestTransactionDeduplication(t *testing.T) {
- t.Parallel()
- // Create the pool to test the pricing enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create a test account to add transactions with
- key, _ := crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
- // Create a batch of transactions and add a few of them
- txs := make([]*types.Transaction, 16)
- for i := 0; i < len(txs); i++ {
- txs[i] = pricedTransaction(uint64(i), 100000, big.NewInt(1), key)
- }
- var firsts []*types.Transaction
- for i := 0; i < len(txs); i += 2 {
- firsts = append(firsts, txs[i])
- }
- errs := pool.AddRemotesSync(firsts)
- if len(errs) != len(firsts) {
- t.Fatalf("first add mismatching result count: have %d, want %d", len(errs), len(firsts))
- }
- for i, err := range errs {
- if err != nil {
- t.Errorf("add %d failed: %v", i, err)
- }
- }
- pending, queued := pool.Stats()
- if pending != 1 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1)
- }
- if queued != len(txs)/2-1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, len(txs)/2-1)
- }
- // Try to add all of them now and ensure previous ones error out as knowns
- errs = pool.AddRemotesSync(txs)
- if len(errs) != len(txs) {
- t.Fatalf("all add mismatching result count: have %d, want %d", len(errs), len(txs))
- }
- for i, err := range errs {
- if i%2 == 0 && err == nil {
- t.Errorf("add %d succeeded, should have failed as known", i)
- }
- if i%2 == 1 && err != nil {
- t.Errorf("add %d failed: %v", i, err)
- }
- }
- pending, queued = pool.Stats()
- if pending != len(txs) {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, len(txs))
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that the pool rejects replacement transactions that don't meet the minimum
- // price bump required.
- func TestTransactionReplacement(t *testing.T) {
- t.Parallel()
- // Create the pool to test the pricing enforcement with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Keep track of transaction events to ensure all executables get announced
- events := make(chan NewTxsEvent, 32)
- sub := pool.txFeed.Subscribe(events)
- defer sub.Unsubscribe()
- // Create a test account to add transactions with
- key, _ := crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
- // Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
- price := int64(100)
- threshold := (price * (100 + int64(testTxPoolConfig.PriceBump))) / 100
- if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), key)); err != nil {
- t.Fatalf("failed to add original cheap pending transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced {
- t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
- }
- if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), key)); err != nil {
- t.Fatalf("failed to replace original cheap pending transaction: %v", err)
- }
- if err := validateEvents(events, 2); err != nil {
- t.Fatalf("cheap replacement event firing failed: %v", err)
- }
- if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(price), key)); err != nil {
- t.Fatalf("failed to add original proper pending transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced {
- t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
- }
- if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(threshold), key)); err != nil {
- t.Fatalf("failed to replace original proper pending transaction: %v", err)
- }
- if err := validateEvents(events, 2); err != nil {
- t.Fatalf("proper replacement event firing failed: %v", err)
- }
- // Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
- if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), key)); err != nil {
- t.Fatalf("failed to add original cheap queued transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced {
- t.Fatalf("original cheap queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), key)); err != nil {
- t.Fatalf("failed to replace original cheap queued transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(price), key)); err != nil {
- t.Fatalf("failed to add original proper queued transaction: %v", err)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced {
- t.Fatalf("original proper queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
- }
- if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(threshold), key)); err != nil {
- t.Fatalf("failed to replace original proper queued transaction: %v", err)
- }
- if err := validateEvents(events, 0); err != nil {
- t.Fatalf("queued replacement event firing failed: %v", err)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- }
- // Tests that local transactions are journaled to disk, but remote transactions
- // get discarded between restarts.
- func TestTransactionJournaling(t *testing.T) { testTransactionJournaling(t, false) }
- func TestTransactionJournalingNoLocals(t *testing.T) { testTransactionJournaling(t, true) }
- func testTransactionJournaling(t *testing.T, nolocals bool) {
- t.Parallel()
- // Create a temporary file for the journal
- file, err := ioutil.TempFile("", "")
- if err != nil {
- t.Fatalf("failed to create temporary journal: %v", err)
- }
- journal := file.Name()
- defer os.Remove(journal)
- // Clean up the temporary file, we only need the path for now
- file.Close()
- os.Remove(journal)
- // Create the original pool to inject transaction into the journal
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- config := testTxPoolConfig
- config.NoLocals = nolocals
- config.Journal = journal
- config.Rejournal = time.Second
- pool := NewTxPool(config, params.TestChainConfig, blockchain)
- // Create two test accounts to ensure remotes expire but locals do not
- local, _ := crypto.GenerateKey()
- remote, _ := crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
- pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))
- // Add three local and a remote transactions and ensure they are queued up
- if err := pool.AddLocal(pricedTransaction(0, 100000, big.NewInt(1), local)); err != nil {
- t.Fatalf("failed to add local transaction: %v", err)
- }
- if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
- t.Fatalf("failed to add local transaction: %v", err)
- }
- if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil {
- t.Fatalf("failed to add local transaction: %v", err)
- }
- if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), remote)); err != nil {
- t.Fatalf("failed to add remote transaction: %v", err)
- }
- pending, queued := pool.Stats()
- if pending != 4 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4)
- }
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Terminate the old pool, bump the local nonce, create a new pool and ensure relevant transaction survive
- pool.Stop()
- statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
- blockchain = &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool = NewTxPool(config, params.TestChainConfig, blockchain)
- pending, queued = pool.Stats()
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- if nolocals {
- if pending != 0 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
- }
- } else {
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Bump the nonce temporarily and ensure the newly invalidated transaction is removed
- statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2)
- <-pool.requestReset(nil, nil)
- time.Sleep(2 * config.Rejournal)
- pool.Stop()
- statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
- blockchain = &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool = NewTxPool(config, params.TestChainConfig, blockchain)
- pending, queued = pool.Stats()
- if pending != 0 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
- }
- if nolocals {
- if queued != 0 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
- }
- } else {
- if queued != 1 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
- }
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- pool.Stop()
- }
- // TestTransactionStatusCheck tests that the pool can correctly retrieve the
- // pending status of individual transactions.
- func TestTransactionStatusCheck(t *testing.T) {
- t.Parallel()
- // Create the pool to test the status retrievals with
- statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
- blockchain := &testBlockChain{statedb, nil, 1000000, new(event.Feed)}
- pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
- defer pool.Stop()
- // Create the test accounts to check various transaction statuses with
- keys := make([]*ecdsa.PrivateKey, 3)
- for i := 0; i < len(keys); i++ {
- keys[i], _ = crypto.GenerateKey()
- pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
- }
- // Generate and queue a batch of transactions, both pending and queued
- txs := types.Transactions{}
- txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) // Pending only
- txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) // Pending and queued
- txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[1]))
- txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) // Queued only
- // Import the transaction and ensure they are correctly added
- pool.AddRemotesSync(txs)
- pending, queued := pool.Stats()
- if pending != 2 {
- t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
- }
- if queued != 2 {
- t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
- }
- if err := validateTxPoolInternals(pool); err != nil {
- t.Fatalf("pool internal state corrupted: %v", err)
- }
- // Retrieve the status of each transaction and validate them
- hashes := make([]common.Hash, len(txs))
- for i, tx := range txs {
- hashes[i] = tx.Hash()
- }
- hashes = append(hashes, common.Hash{})
- statuses := pool.Status(hashes)
- expect := []TxStatus{TxStatusPending, TxStatusPending, TxStatusQueued, TxStatusQueued, TxStatusUnknown}
- for i := 0; i < len(statuses); i++ {
- if statuses[i] != expect[i] {
- t.Errorf("transaction %d: status mismatch: have %v, want %v", i, statuses[i], expect[i])
- }
- }
- }
- // Test the transaction slots consumption is computed correctly
- func TestTransactionSlotCount(t *testing.T) {
- t.Parallel()
- key, _ := crypto.GenerateKey()
- // Check that an empty transaction consumes a single slot
- smallTx := pricedDataTransaction(0, 0, big.NewInt(0), key, 0)
- if slots := numSlots(smallTx); slots != 1 {
- t.Fatalf("small transactions slot count mismatch: have %d want %d", slots, 1)
- }
- // Check that a large transaction consumes the correct number of slots
- bigTx := pricedDataTransaction(0, 0, big.NewInt(0), key, uint64(10*txSlotSize))
- if slots := numSlots(bigTx); slots != 11 {
- t.Fatalf("big transactions slot count mismatch: have %d want %d", slots, 11)
- }
- }
- // Benchmarks the speed of validating the contents of the pending queue of the
- // transaction pool.
- func BenchmarkPendingDemotion100(b *testing.B) { benchmarkPendingDemotion(b, 100) }
- func BenchmarkPendingDemotion1000(b *testing.B) { benchmarkPendingDemotion(b, 1000) }
- func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) }
- func benchmarkPendingDemotion(b *testing.B, size int) {
- // Add a batch of transactions to a pool one by one
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000))
- for i := 0; i < size; i++ {
- tx := transaction(uint64(i), 100000, key)
- pool.promoteTx(account, tx.Hash(), tx)
- }
- // Benchmark the speed of pool validation
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- pool.demoteUnexecutables()
- }
- }
- // Benchmarks the speed of scheduling the contents of the future queue of the
- // transaction pool.
- func BenchmarkFuturePromotion100(b *testing.B) { benchmarkFuturePromotion(b, 100) }
- func BenchmarkFuturePromotion1000(b *testing.B) { benchmarkFuturePromotion(b, 1000) }
- func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) }
- func benchmarkFuturePromotion(b *testing.B, size int) {
- // Add a batch of transactions to a pool one by one
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000))
- for i := 0; i < size; i++ {
- tx := transaction(uint64(1+i), 100000, key)
- pool.enqueueTx(tx.Hash(), tx, false, true)
- }
- // Benchmark the speed of pool validation
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- pool.promoteExecutables(nil)
- }
- }
- // Benchmarks the speed of batched transaction insertion.
- func BenchmarkPoolBatchInsert100(b *testing.B) { benchmarkPoolBatchInsert(b, 100, false) }
- func BenchmarkPoolBatchInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000, false) }
- func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000, false) }
- func BenchmarkPoolBatchLocalInsert100(b *testing.B) { benchmarkPoolBatchInsert(b, 100, true) }
- func BenchmarkPoolBatchLocalInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000, true) }
- func BenchmarkPoolBatchLocalInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000, true) }
- func benchmarkPoolBatchInsert(b *testing.B, size int, local bool) {
- // Generate a batch of transactions to enqueue into the pool
- pool, key := setupTxPool()
- defer pool.Stop()
- account := crypto.PubkeyToAddress(key.PublicKey)
- pool.currentState.AddBalance(account, big.NewInt(1000000))
- batches := make([]types.Transactions, b.N)
- for i := 0; i < b.N; i++ {
- batches[i] = make(types.Transactions, size)
- for j := 0; j < size; j++ {
- batches[i][j] = transaction(uint64(size*i+j), 100000, key)
- }
- }
- // Benchmark importing the transactions into the queue
- b.ResetTimer()
- for _, batch := range batches {
- if local {
- pool.AddLocals(batch)
- } else {
- pool.AddRemotes(batch)
- }
- }
- }
- func BenchmarkInsertRemoteWithAllLocals(b *testing.B) {
- // Allocate keys for testing
- key, _ := crypto.GenerateKey()
- account := crypto.PubkeyToAddress(key.PublicKey)
- remoteKey, _ := crypto.GenerateKey()
- remoteAddr := crypto.PubkeyToAddress(remoteKey.PublicKey)
- locals := make([]*types.Transaction, 4096+1024) // Occupy all slots
- for i := 0; i < len(locals); i++ {
- locals[i] = transaction(uint64(i), 100000, key)
- }
- remotes := make([]*types.Transaction, 1000)
- for i := 0; i < len(remotes); i++ {
- remotes[i] = pricedTransaction(uint64(i), 100000, big.NewInt(2), remoteKey) // Higher gasprice
- }
- // Benchmark importing the transactions into the queue
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- b.StopTimer()
- pool, _ := setupTxPool()
- pool.currentState.AddBalance(account, big.NewInt(100000000))
- for _, local := range locals {
- pool.AddLocal(local)
- }
- b.StartTimer()
- // Assign a high enough balance for testing
- pool.currentState.AddBalance(remoteAddr, big.NewInt(100000000))
- for i := 0; i < len(remotes); i++ {
- pool.AddRemotes([]*types.Transaction{remotes[i]})
- }
- pool.Stop()
- }
- }
- // Quorum
- type testPoolConfig struct {
- name string
- homesteadBlock *big.Int
- eip155Block *big.Int
- }
- func setupNewTxPool(tt testPoolConfig) *TxPool {
- db := rawdb.NewMemoryDatabase()
- stateDB, _ := state.New(common.Hash{}, state.NewDatabase(db), nil)
- blockchain := &testBlockChain{stateDB, nil, 1000000, new(event.Feed)}
- chainConfig := ¶ms.ChainConfig{
- ChainID: big.NewInt(10),
- HomesteadBlock: tt.homesteadBlock,
- EIP150Block: big.NewInt(0),
- EIP155Block: tt.eip155Block,
- EIP158Block: big.NewInt(0),
- ByzantiumBlock: big.NewInt(0),
- Ethash: new(params.EthashConfig),
- }
- return NewTxPool(testTxPoolConfig, chainConfig, blockchain)
- }
- //Checks that the EIP155 signer is assigned to the TxPool when eip155Block is different then null, even invalid config
- func TestEIP155SignerOnTxPool(t *testing.T) {
- var flagtests = []testPoolConfig{
- {"hsnileip1550", nil, big.NewInt(0)},
- {"hsnileip155100", nil, big.NewInt(100)},
- {"hs0eip1550", big.NewInt(0), big.NewInt(0)},
- {"hs0eip155100", big.NewInt(0), big.NewInt(100)},
- {"hs100eip1550", big.NewInt(100), big.NewInt(0)},
- {"hs100eip155100", big.NewInt(100), big.NewInt(100)},
- }
- for _, tt := range flagtests {
- t.Run(tt.name, func(t *testing.T) {
- pool := setupNewTxPool(tt)
- if reflect.TypeOf(types.EIP155Signer{}) != reflect.TypeOf(pool.signer) {
- t.Fail()
- }
- })
- }
- }
- func TestHomesteadSignerOnTxPool(t *testing.T) {
- var flagtests = []testPoolConfig{
- {"hsnileip155nil", nil, nil},
- {"hs0eip155nil", big.NewInt(0), nil},
- {"hs100eip155nil", big.NewInt(100), nil},
- }
- for _, tt := range flagtests {
- t.Run(tt.name, func(t *testing.T) {
- pool := setupNewTxPool(tt)
- if reflect.TypeOf(types.HomesteadSigner{}) != reflect.TypeOf(pool.signer) {
- t.Fail()
- }
- })
- }
- }
- // End Quorum
|