tx_pool_test.go 75 KB

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