tx_pool_test.go 63 KB

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