tx_pool_test.go 69 KB

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