tx_pool_test.go 69 KB

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