tx_pool_test.go 93 KB

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