tx_pool_test.go 72 KB

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