tx_pool_test.go 66 KB

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