tx_pool_test.go 69 KB

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