tx_pool_test.go 81 KB

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