tx_pool_test.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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. "math/big"
  20. "math/rand"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/state"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/params"
  30. )
  31. func transaction(nonce uint64, gaslimit *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
  32. return pricedTransaction(nonce, gaslimit, big.NewInt(1), key)
  33. }
  34. func pricedTransaction(nonce uint64, gaslimit, gasprice *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
  35. tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, gasprice, nil), types.HomesteadSigner{}, key)
  36. return tx
  37. }
  38. func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
  39. db, _ := ethdb.NewMemDatabase()
  40. statedb, _ := state.New(common.Hash{}, db)
  41. key, _ := crypto.GenerateKey()
  42. newPool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  43. newPool.resetState()
  44. return newPool, key
  45. }
  46. func deriveSender(tx *types.Transaction) (common.Address, error) {
  47. return types.Sender(types.HomesteadSigner{}, tx)
  48. }
  49. // This test simulates a scenario where a new block is imported during a
  50. // state reset and tests whether the pending state is in sync with the
  51. // block head event that initiated the resetState().
  52. func TestStateChangeDuringPoolReset(t *testing.T) {
  53. var (
  54. db, _ = ethdb.NewMemDatabase()
  55. key, _ = crypto.GenerateKey()
  56. address = crypto.PubkeyToAddress(key.PublicKey)
  57. mux = new(event.TypeMux)
  58. statedb, _ = state.New(common.Hash{}, db)
  59. trigger = false
  60. )
  61. // setup pool with 2 transaction in it
  62. statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
  63. tx0 := transaction(0, big.NewInt(100000), key)
  64. tx1 := transaction(1, big.NewInt(100000), key)
  65. // stateFunc is used multiple times to reset the pending state.
  66. // when simulate is true it will create a state that indicates
  67. // that tx0 and tx1 are included in the chain.
  68. stateFunc := func() (*state.StateDB, error) {
  69. // delay "state change" by one. The tx pool fetches the
  70. // state multiple times and by delaying it a bit we simulate
  71. // a state change between those fetches.
  72. stdb := statedb
  73. if trigger {
  74. statedb, _ = state.New(common.Hash{}, db)
  75. // simulate that the new head block included tx0 and tx1
  76. statedb.SetNonce(address, 2)
  77. statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
  78. trigger = false
  79. }
  80. return stdb, nil
  81. }
  82. gasLimitFunc := func() *big.Int { return big.NewInt(1000000000) }
  83. txpool := NewTxPool(params.TestChainConfig, mux, stateFunc, gasLimitFunc)
  84. txpool.resetState()
  85. nonce := txpool.State().GetNonce(address)
  86. if nonce != 0 {
  87. t.Fatalf("Invalid nonce, want 0, got %d", nonce)
  88. }
  89. txpool.AddBatch(types.Transactions{tx0, tx1})
  90. nonce = txpool.State().GetNonce(address)
  91. if nonce != 2 {
  92. t.Fatalf("Invalid nonce, want 2, got %d", nonce)
  93. }
  94. // trigger state change in the background
  95. trigger = true
  96. txpool.resetState()
  97. pendingTx, err := txpool.Pending()
  98. if err != nil {
  99. t.Fatalf("Could not fetch pending transactions: %v", err)
  100. }
  101. for addr, txs := range pendingTx {
  102. t.Logf("%0x: %d\n", addr, len(txs))
  103. }
  104. nonce = txpool.State().GetNonce(address)
  105. if nonce != 2 {
  106. t.Fatalf("Invalid nonce, want 2, got %d", nonce)
  107. }
  108. }
  109. func TestInvalidTransactions(t *testing.T) {
  110. pool, key := setupTxPool()
  111. tx := transaction(0, big.NewInt(100), key)
  112. from, _ := deriveSender(tx)
  113. currentState, _ := pool.currentState()
  114. currentState.AddBalance(from, big.NewInt(1))
  115. if err := pool.Add(tx); err != ErrInsufficientFunds {
  116. t.Error("expected", ErrInsufficientFunds)
  117. }
  118. balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice()))
  119. currentState.AddBalance(from, balance)
  120. if err := pool.Add(tx); err != ErrIntrinsicGas {
  121. t.Error("expected", ErrIntrinsicGas, "got", err)
  122. }
  123. currentState.SetNonce(from, 1)
  124. currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
  125. tx = transaction(0, big.NewInt(100000), key)
  126. if err := pool.Add(tx); err != ErrNonce {
  127. t.Error("expected", ErrNonce)
  128. }
  129. tx = transaction(1, big.NewInt(100000), key)
  130. pool.gasPrice = big.NewInt(1000)
  131. if err := pool.Add(tx); err != ErrUnderpriced {
  132. t.Error("expected", ErrUnderpriced, "got", err)
  133. }
  134. pool.SetLocal(tx)
  135. if err := pool.Add(tx); err != nil {
  136. t.Error("expected", nil, "got", err)
  137. }
  138. }
  139. func TestTransactionQueue(t *testing.T) {
  140. pool, key := setupTxPool()
  141. tx := transaction(0, big.NewInt(100), key)
  142. from, _ := deriveSender(tx)
  143. currentState, _ := pool.currentState()
  144. currentState.AddBalance(from, big.NewInt(1000))
  145. pool.resetState()
  146. pool.enqueueTx(tx.Hash(), tx)
  147. pool.promoteExecutables(currentState)
  148. if len(pool.pending) != 1 {
  149. t.Error("expected valid txs to be 1 is", len(pool.pending))
  150. }
  151. tx = transaction(1, big.NewInt(100), key)
  152. from, _ = deriveSender(tx)
  153. currentState.SetNonce(from, 2)
  154. pool.enqueueTx(tx.Hash(), tx)
  155. pool.promoteExecutables(currentState)
  156. if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok {
  157. t.Error("expected transaction to be in tx pool")
  158. }
  159. if len(pool.queue) > 0 {
  160. t.Error("expected transaction queue to be empty. is", len(pool.queue))
  161. }
  162. pool, key = setupTxPool()
  163. tx1 := transaction(0, big.NewInt(100), key)
  164. tx2 := transaction(10, big.NewInt(100), key)
  165. tx3 := transaction(11, big.NewInt(100), key)
  166. from, _ = deriveSender(tx1)
  167. currentState, _ = pool.currentState()
  168. currentState.AddBalance(from, big.NewInt(1000))
  169. pool.resetState()
  170. pool.enqueueTx(tx1.Hash(), tx1)
  171. pool.enqueueTx(tx2.Hash(), tx2)
  172. pool.enqueueTx(tx3.Hash(), tx3)
  173. pool.promoteExecutables(currentState)
  174. if len(pool.pending) != 1 {
  175. t.Error("expected tx pool to be 1, got", len(pool.pending))
  176. }
  177. if pool.queue[from].Len() != 2 {
  178. t.Error("expected len(queue) == 2, got", pool.queue[from].Len())
  179. }
  180. }
  181. func TestRemoveTx(t *testing.T) {
  182. pool, key := setupTxPool()
  183. tx := transaction(0, big.NewInt(100), key)
  184. from, _ := deriveSender(tx)
  185. currentState, _ := pool.currentState()
  186. currentState.AddBalance(from, big.NewInt(1))
  187. pool.enqueueTx(tx.Hash(), tx)
  188. pool.promoteTx(from, tx.Hash(), tx)
  189. if len(pool.queue) != 1 {
  190. t.Error("expected queue to be 1, got", len(pool.queue))
  191. }
  192. if len(pool.pending) != 1 {
  193. t.Error("expected pending to be 1, got", len(pool.pending))
  194. }
  195. pool.Remove(tx.Hash())
  196. if len(pool.queue) > 0 {
  197. t.Error("expected queue to be 0, got", len(pool.queue))
  198. }
  199. if len(pool.pending) > 0 {
  200. t.Error("expected pending to be 0, got", len(pool.pending))
  201. }
  202. }
  203. func TestNegativeValue(t *testing.T) {
  204. pool, key := setupTxPool()
  205. tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(-1), big.NewInt(100), big.NewInt(1), nil), types.HomesteadSigner{}, key)
  206. from, _ := deriveSender(tx)
  207. currentState, _ := pool.currentState()
  208. currentState.AddBalance(from, big.NewInt(1))
  209. if err := pool.Add(tx); err != ErrNegativeValue {
  210. t.Error("expected", ErrNegativeValue, "got", err)
  211. }
  212. }
  213. func TestTransactionChainFork(t *testing.T) {
  214. pool, key := setupTxPool()
  215. addr := crypto.PubkeyToAddress(key.PublicKey)
  216. resetState := func() {
  217. db, _ := ethdb.NewMemDatabase()
  218. statedb, _ := state.New(common.Hash{}, db)
  219. pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
  220. currentState, _ := pool.currentState()
  221. currentState.AddBalance(addr, big.NewInt(100000000000000))
  222. pool.resetState()
  223. }
  224. resetState()
  225. tx := transaction(0, big.NewInt(100000), key)
  226. if _, err := pool.add(tx); err != nil {
  227. t.Error("didn't expect error", err)
  228. }
  229. pool.RemoveBatch([]*types.Transaction{tx})
  230. // reset the pool's internal state
  231. resetState()
  232. if _, err := pool.add(tx); err != nil {
  233. t.Error("didn't expect error", err)
  234. }
  235. }
  236. func TestTransactionDoubleNonce(t *testing.T) {
  237. pool, key := setupTxPool()
  238. addr := crypto.PubkeyToAddress(key.PublicKey)
  239. resetState := func() {
  240. db, _ := ethdb.NewMemDatabase()
  241. statedb, _ := state.New(common.Hash{}, db)
  242. pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
  243. currentState, _ := pool.currentState()
  244. currentState.AddBalance(addr, big.NewInt(100000000000000))
  245. pool.resetState()
  246. }
  247. resetState()
  248. signer := types.HomesteadSigner{}
  249. tx1, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(100000), big.NewInt(1), nil), signer, key)
  250. tx2, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(1000000), big.NewInt(2), nil), signer, key)
  251. tx3, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(1000000), big.NewInt(1), nil), signer, key)
  252. // Add the first two transaction, ensure higher priced stays only
  253. if replace, err := pool.add(tx1); err != nil || replace {
  254. t.Errorf("first transaction insert failed (%v) or reported replacement (%v)", err, replace)
  255. }
  256. if replace, err := pool.add(tx2); err != nil || !replace {
  257. t.Errorf("second transaction insert failed (%v) or not reported replacement (%v)", err, replace)
  258. }
  259. state, _ := pool.currentState()
  260. pool.promoteExecutables(state)
  261. if pool.pending[addr].Len() != 1 {
  262. t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
  263. }
  264. if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
  265. t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
  266. }
  267. // Add the thid transaction and ensure it's not saved (smaller price)
  268. pool.add(tx3)
  269. pool.promoteExecutables(state)
  270. if pool.pending[addr].Len() != 1 {
  271. t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
  272. }
  273. if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
  274. t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
  275. }
  276. // Ensure the total transaction count is correct
  277. if len(pool.all) != 1 {
  278. t.Error("expected 1 total transactions, got", len(pool.all))
  279. }
  280. }
  281. func TestMissingNonce(t *testing.T) {
  282. pool, key := setupTxPool()
  283. addr := crypto.PubkeyToAddress(key.PublicKey)
  284. currentState, _ := pool.currentState()
  285. currentState.AddBalance(addr, big.NewInt(100000000000000))
  286. tx := transaction(1, big.NewInt(100000), key)
  287. if _, err := pool.add(tx); err != nil {
  288. t.Error("didn't expect error", err)
  289. }
  290. if len(pool.pending) != 0 {
  291. t.Error("expected 0 pending transactions, got", len(pool.pending))
  292. }
  293. if pool.queue[addr].Len() != 1 {
  294. t.Error("expected 1 queued transaction, got", pool.queue[addr].Len())
  295. }
  296. if len(pool.all) != 1 {
  297. t.Error("expected 1 total transactions, got", len(pool.all))
  298. }
  299. }
  300. func TestNonceRecovery(t *testing.T) {
  301. const n = 10
  302. pool, key := setupTxPool()
  303. addr := crypto.PubkeyToAddress(key.PublicKey)
  304. currentState, _ := pool.currentState()
  305. currentState.SetNonce(addr, n)
  306. currentState.AddBalance(addr, big.NewInt(100000000000000))
  307. pool.resetState()
  308. tx := transaction(n, big.NewInt(100000), key)
  309. if err := pool.Add(tx); err != nil {
  310. t.Error(err)
  311. }
  312. // simulate some weird re-order of transactions and missing nonce(s)
  313. currentState.SetNonce(addr, n-1)
  314. pool.resetState()
  315. if fn := pool.pendingState.GetNonce(addr); fn != n+1 {
  316. t.Errorf("expected nonce to be %d, got %d", n+1, fn)
  317. }
  318. }
  319. func TestRemovedTxEvent(t *testing.T) {
  320. pool, key := setupTxPool()
  321. tx := transaction(0, big.NewInt(1000000), key)
  322. from, _ := deriveSender(tx)
  323. currentState, _ := pool.currentState()
  324. currentState.AddBalance(from, big.NewInt(1000000000000))
  325. pool.resetState()
  326. pool.eventMux.Post(RemovedTransactionEvent{types.Transactions{tx}})
  327. pool.eventMux.Post(ChainHeadEvent{nil})
  328. if pool.pending[from].Len() != 1 {
  329. t.Error("expected 1 pending tx, got", pool.pending[from].Len())
  330. }
  331. if len(pool.all) != 1 {
  332. t.Error("expected 1 total transactions, got", len(pool.all))
  333. }
  334. }
  335. // Tests that if an account runs out of funds, any pending and queued transactions
  336. // are dropped.
  337. func TestTransactionDropping(t *testing.T) {
  338. // Create a test account and fund it
  339. pool, key := setupTxPool()
  340. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  341. state, _ := pool.currentState()
  342. state.AddBalance(account, big.NewInt(1000))
  343. // Add some pending and some queued transactions
  344. var (
  345. tx0 = transaction(0, big.NewInt(100), key)
  346. tx1 = transaction(1, big.NewInt(200), key)
  347. tx10 = transaction(10, big.NewInt(100), key)
  348. tx11 = transaction(11, big.NewInt(200), key)
  349. )
  350. pool.promoteTx(account, tx0.Hash(), tx0)
  351. pool.promoteTx(account, tx1.Hash(), tx1)
  352. pool.enqueueTx(tx10.Hash(), tx10)
  353. pool.enqueueTx(tx11.Hash(), tx11)
  354. // Check that pre and post validations leave the pool as is
  355. if pool.pending[account].Len() != 2 {
  356. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 2)
  357. }
  358. if pool.queue[account].Len() != 2 {
  359. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 2)
  360. }
  361. if len(pool.all) != 4 {
  362. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 4)
  363. }
  364. pool.resetState()
  365. if pool.pending[account].Len() != 2 {
  366. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 2)
  367. }
  368. if pool.queue[account].Len() != 2 {
  369. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 2)
  370. }
  371. if len(pool.all) != 4 {
  372. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 4)
  373. }
  374. // Reduce the balance of the account, and check that invalidated transactions are dropped
  375. state.AddBalance(account, big.NewInt(-750))
  376. pool.resetState()
  377. if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
  378. t.Errorf("funded pending transaction missing: %v", tx0)
  379. }
  380. if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok {
  381. t.Errorf("out-of-fund pending transaction present: %v", tx1)
  382. }
  383. if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
  384. t.Errorf("funded queued transaction missing: %v", tx10)
  385. }
  386. if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok {
  387. t.Errorf("out-of-fund queued transaction present: %v", tx11)
  388. }
  389. if len(pool.all) != 2 {
  390. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 2)
  391. }
  392. }
  393. // Tests that if a transaction is dropped from the current pending pool (e.g. out
  394. // of fund), all consecutive (still valid, but not executable) transactions are
  395. // postponed back into the future queue to prevent broadcasting them.
  396. func TestTransactionPostponing(t *testing.T) {
  397. // Create a test account and fund it
  398. pool, key := setupTxPool()
  399. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  400. state, _ := pool.currentState()
  401. state.AddBalance(account, big.NewInt(1000))
  402. // Add a batch consecutive pending transactions for validation
  403. txns := []*types.Transaction{}
  404. for i := 0; i < 100; i++ {
  405. var tx *types.Transaction
  406. if i%2 == 0 {
  407. tx = transaction(uint64(i), big.NewInt(100), key)
  408. } else {
  409. tx = transaction(uint64(i), big.NewInt(500), key)
  410. }
  411. pool.promoteTx(account, tx.Hash(), tx)
  412. txns = append(txns, tx)
  413. }
  414. // Check that pre and post validations leave the pool as is
  415. if pool.pending[account].Len() != len(txns) {
  416. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), len(txns))
  417. }
  418. if len(pool.queue) != 0 {
  419. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 0)
  420. }
  421. if len(pool.all) != len(txns) {
  422. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns))
  423. }
  424. pool.resetState()
  425. if pool.pending[account].Len() != len(txns) {
  426. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), len(txns))
  427. }
  428. if len(pool.queue) != 0 {
  429. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 0)
  430. }
  431. if len(pool.all) != len(txns) {
  432. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns))
  433. }
  434. // Reduce the balance of the account, and check that transactions are reorganised
  435. state.AddBalance(account, big.NewInt(-750))
  436. pool.resetState()
  437. if _, ok := pool.pending[account].txs.items[txns[0].Nonce()]; !ok {
  438. t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txns[0])
  439. }
  440. if _, ok := pool.queue[account].txs.items[txns[0].Nonce()]; ok {
  441. t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txns[0])
  442. }
  443. for i, tx := range txns[1:] {
  444. if i%2 == 1 {
  445. if _, ok := pool.pending[account].txs.items[tx.Nonce()]; ok {
  446. t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx)
  447. }
  448. if _, ok := pool.queue[account].txs.items[tx.Nonce()]; !ok {
  449. t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx)
  450. }
  451. } else {
  452. if _, ok := pool.pending[account].txs.items[tx.Nonce()]; ok {
  453. t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx)
  454. }
  455. if _, ok := pool.queue[account].txs.items[tx.Nonce()]; ok {
  456. t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx)
  457. }
  458. }
  459. }
  460. if len(pool.all) != len(txns)/2 {
  461. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns)/2)
  462. }
  463. }
  464. // Tests that if the transaction count belonging to a single account goes above
  465. // some threshold, the higher transactions are dropped to prevent DOS attacks.
  466. func TestTransactionQueueAccountLimiting(t *testing.T) {
  467. // Create a test account and fund it
  468. pool, key := setupTxPool()
  469. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  470. state, _ := pool.currentState()
  471. state.AddBalance(account, big.NewInt(1000000))
  472. pool.resetState()
  473. // Keep queuing up transactions and make sure all above a limit are dropped
  474. for i := uint64(1); i <= maxQueuedPerAccount+5; i++ {
  475. if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
  476. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  477. }
  478. if len(pool.pending) != 0 {
  479. t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0)
  480. }
  481. if i <= maxQueuedPerAccount {
  482. if pool.queue[account].Len() != int(i) {
  483. t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i)
  484. }
  485. } else {
  486. if pool.queue[account].Len() != int(maxQueuedPerAccount) {
  487. t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), maxQueuedPerAccount)
  488. }
  489. }
  490. }
  491. if len(pool.all) != int(maxQueuedPerAccount) {
  492. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), maxQueuedPerAccount)
  493. }
  494. }
  495. // Tests that if the transaction count belonging to multiple accounts go above
  496. // some threshold, the higher transactions are dropped to prevent DOS attacks.
  497. func TestTransactionQueueGlobalLimiting(t *testing.T) {
  498. // Reduce the queue limits to shorten test time
  499. defer func(old uint64) { maxQueuedTotal = old }(maxQueuedTotal)
  500. maxQueuedTotal = maxQueuedPerAccount * 3
  501. // Create the pool to test the limit enforcement with
  502. db, _ := ethdb.NewMemDatabase()
  503. statedb, _ := state.New(common.Hash{}, db)
  504. pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  505. pool.resetState()
  506. // Create a number of test accounts and fund them
  507. state, _ := pool.currentState()
  508. keys := make([]*ecdsa.PrivateKey, 5)
  509. for i := 0; i < len(keys); i++ {
  510. keys[i], _ = crypto.GenerateKey()
  511. state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  512. }
  513. // Generate and queue a batch of transactions
  514. nonces := make(map[common.Address]uint64)
  515. txs := make(types.Transactions, 0, 3*maxQueuedTotal)
  516. for len(txs) < cap(txs) {
  517. key := keys[rand.Intn(len(keys))]
  518. addr := crypto.PubkeyToAddress(key.PublicKey)
  519. txs = append(txs, transaction(nonces[addr]+1, big.NewInt(100000), key))
  520. nonces[addr]++
  521. }
  522. // Import the batch and verify that limits have been enforced
  523. pool.AddBatch(txs)
  524. queued := 0
  525. for addr, list := range pool.queue {
  526. if list.Len() > int(maxQueuedPerAccount) {
  527. t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), maxQueuedPerAccount)
  528. }
  529. queued += list.Len()
  530. }
  531. if queued > int(maxQueuedTotal) {
  532. t.Fatalf("total transactions overflow allowance: %d > %d", queued, maxQueuedTotal)
  533. }
  534. }
  535. // Tests that if an account remains idle for a prolonged amount of time, any
  536. // non-executable transactions queued up are dropped to prevent wasting resources
  537. // on shuffling them around.
  538. func TestTransactionQueueTimeLimiting(t *testing.T) {
  539. // Reduce the queue limits to shorten test time
  540. defer func(old time.Duration) { maxQueuedLifetime = old }(maxQueuedLifetime)
  541. defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
  542. maxQueuedLifetime = time.Second
  543. evictionInterval = time.Second
  544. // Create a test account and fund it
  545. pool, key := setupTxPool()
  546. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  547. state, _ := pool.currentState()
  548. state.AddBalance(account, big.NewInt(1000000))
  549. // Queue up a batch of transactions
  550. for i := uint64(1); i <= maxQueuedPerAccount; i++ {
  551. if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
  552. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  553. }
  554. }
  555. // Wait until at least two expiration cycles hit and make sure the transactions are gone
  556. time.Sleep(2 * evictionInterval)
  557. if len(pool.queue) > 0 {
  558. t.Fatalf("old transactions remained after eviction")
  559. }
  560. }
  561. // Tests that even if the transaction count belonging to a single account goes
  562. // above some threshold, as long as the transactions are executable, they are
  563. // accepted.
  564. func TestTransactionPendingLimiting(t *testing.T) {
  565. // Create a test account and fund it
  566. pool, key := setupTxPool()
  567. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  568. state, _ := pool.currentState()
  569. state.AddBalance(account, big.NewInt(1000000))
  570. pool.resetState()
  571. // Keep queuing up transactions and make sure all above a limit are dropped
  572. for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
  573. if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
  574. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  575. }
  576. if pool.pending[account].Len() != int(i)+1 {
  577. t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1)
  578. }
  579. if len(pool.queue) != 0 {
  580. t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
  581. }
  582. }
  583. if len(pool.all) != int(maxQueuedPerAccount+5) {
  584. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), maxQueuedPerAccount+5)
  585. }
  586. }
  587. // Tests that the transaction limits are enforced the same way irrelevant whether
  588. // the transactions are added one by one or in batches.
  589. func TestTransactionQueueLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 1) }
  590. func TestTransactionPendingLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 0) }
  591. func testTransactionLimitingEquivalency(t *testing.T, origin uint64) {
  592. // Add a batch of transactions to a pool one by one
  593. pool1, key1 := setupTxPool()
  594. account1, _ := deriveSender(transaction(0, big.NewInt(0), key1))
  595. state1, _ := pool1.currentState()
  596. state1.AddBalance(account1, big.NewInt(1000000))
  597. for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
  598. if err := pool1.Add(transaction(origin+i, big.NewInt(100000), key1)); err != nil {
  599. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  600. }
  601. }
  602. // Add a batch of transactions to a pool in one big batch
  603. pool2, key2 := setupTxPool()
  604. account2, _ := deriveSender(transaction(0, big.NewInt(0), key2))
  605. state2, _ := pool2.currentState()
  606. state2.AddBalance(account2, big.NewInt(1000000))
  607. txns := []*types.Transaction{}
  608. for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
  609. txns = append(txns, transaction(origin+i, big.NewInt(100000), key2))
  610. }
  611. pool2.AddBatch(txns)
  612. // Ensure the batch optimization honors the same pool mechanics
  613. if len(pool1.pending) != len(pool2.pending) {
  614. t.Errorf("pending transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.pending), len(pool2.pending))
  615. }
  616. if len(pool1.queue) != len(pool2.queue) {
  617. t.Errorf("queued transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.queue), len(pool2.queue))
  618. }
  619. if len(pool1.all) != len(pool2.all) {
  620. t.Errorf("total transaction count mismatch: one-by-one algo %d, batch algo %d", len(pool1.all), len(pool2.all))
  621. }
  622. }
  623. // Tests that if the transaction count belonging to multiple accounts go above
  624. // some hard threshold, the higher transactions are dropped to prevent DOS
  625. // attacks.
  626. func TestTransactionPendingGlobalLimiting(t *testing.T) {
  627. // Reduce the queue limits to shorten test time
  628. defer func(old uint64) { maxPendingTotal = old }(maxPendingTotal)
  629. maxPendingTotal = minPendingPerAccount * 10
  630. // Create the pool to test the limit enforcement with
  631. db, _ := ethdb.NewMemDatabase()
  632. statedb, _ := state.New(common.Hash{}, db)
  633. pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  634. pool.resetState()
  635. // Create a number of test accounts and fund them
  636. state, _ := pool.currentState()
  637. keys := make([]*ecdsa.PrivateKey, 5)
  638. for i := 0; i < len(keys); i++ {
  639. keys[i], _ = crypto.GenerateKey()
  640. state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  641. }
  642. // Generate and queue a batch of transactions
  643. nonces := make(map[common.Address]uint64)
  644. txs := types.Transactions{}
  645. for _, key := range keys {
  646. addr := crypto.PubkeyToAddress(key.PublicKey)
  647. for j := 0; j < int(maxPendingTotal)/len(keys)*2; j++ {
  648. txs = append(txs, transaction(nonces[addr], big.NewInt(100000), key))
  649. nonces[addr]++
  650. }
  651. }
  652. // Import the batch and verify that limits have been enforced
  653. pool.AddBatch(txs)
  654. pending := 0
  655. for _, list := range pool.pending {
  656. pending += list.Len()
  657. }
  658. if pending > int(maxPendingTotal) {
  659. t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, maxPendingTotal)
  660. }
  661. }
  662. // Tests that if the transaction count belonging to multiple accounts go above
  663. // some hard threshold, if they are under the minimum guaranteed slot count then
  664. // the transactions are still kept.
  665. func TestTransactionPendingMinimumAllowance(t *testing.T) {
  666. // Reduce the queue limits to shorten test time
  667. defer func(old uint64) { maxPendingTotal = old }(maxPendingTotal)
  668. maxPendingTotal = 0
  669. // Create the pool to test the limit enforcement with
  670. db, _ := ethdb.NewMemDatabase()
  671. statedb, _ := state.New(common.Hash{}, db)
  672. pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  673. pool.resetState()
  674. // Create a number of test accounts and fund them
  675. state, _ := pool.currentState()
  676. keys := make([]*ecdsa.PrivateKey, 5)
  677. for i := 0; i < len(keys); i++ {
  678. keys[i], _ = crypto.GenerateKey()
  679. state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  680. }
  681. // Generate and queue a batch of transactions
  682. nonces := make(map[common.Address]uint64)
  683. txs := types.Transactions{}
  684. for _, key := range keys {
  685. addr := crypto.PubkeyToAddress(key.PublicKey)
  686. for j := 0; j < int(minPendingPerAccount)*2; j++ {
  687. txs = append(txs, transaction(nonces[addr], big.NewInt(100000), key))
  688. nonces[addr]++
  689. }
  690. }
  691. // Import the batch and verify that limits have been enforced
  692. pool.AddBatch(txs)
  693. for addr, list := range pool.pending {
  694. if list.Len() != int(minPendingPerAccount) {
  695. t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), minPendingPerAccount)
  696. }
  697. }
  698. }
  699. // Tests that setting the transaction pool gas price to a higher value correctly
  700. // discards everything cheaper than that and moves any gapped transactions back
  701. // from the pending pool to the queue.
  702. //
  703. // Note, local transactions are never allowed to be dropped.
  704. func TestTransactionPoolRepricing(t *testing.T) {
  705. // Create the pool to test the pricing enforcement with
  706. db, _ := ethdb.NewMemDatabase()
  707. statedb, _ := state.New(common.Hash{}, db)
  708. pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  709. pool.resetState()
  710. // Create a number of test accounts and fund them
  711. state, _ := pool.currentState()
  712. keys := make([]*ecdsa.PrivateKey, 3)
  713. for i := 0; i < len(keys); i++ {
  714. keys[i], _ = crypto.GenerateKey()
  715. state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  716. }
  717. // Generate and queue a batch of transactions, both pending and queued
  718. txs := types.Transactions{}
  719. txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(2), keys[0]))
  720. txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[0]))
  721. txs = append(txs, pricedTransaction(2, big.NewInt(100000), big.NewInt(2), keys[0]))
  722. txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(2), keys[1]))
  723. txs = append(txs, pricedTransaction(2, big.NewInt(100000), big.NewInt(1), keys[1]))
  724. txs = append(txs, pricedTransaction(3, big.NewInt(100000), big.NewInt(2), keys[1]))
  725. txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[2]))
  726. pool.SetLocal(txs[len(txs)-1]) // prevent this one from ever being dropped
  727. // Import the batch and that both pending and queued transactions match up
  728. pool.AddBatch(txs)
  729. pending, queued := pool.stats()
  730. if pending != 4 {
  731. t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4)
  732. }
  733. if queued != 3 {
  734. t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
  735. }
  736. // Reprice the pool and check that underpriced transactions get dropped
  737. pool.SetGasPrice(big.NewInt(2))
  738. pending, queued = pool.stats()
  739. if pending != 2 {
  740. t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  741. }
  742. if queued != 3 {
  743. t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
  744. }
  745. // Check that we can't add the old transactions back
  746. if err := pool.Add(pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[0])); err != ErrUnderpriced {
  747. t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  748. }
  749. if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(1), keys[1])); err != ErrUnderpriced {
  750. t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  751. }
  752. // However we can add local underpriced transactions
  753. tx := pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[2])
  754. pool.SetLocal(tx) // prevent this one from ever being dropped
  755. if err := pool.Add(tx); err != nil {
  756. t.Fatalf("failed to add underpriced local transaction: %v", err)
  757. }
  758. if pending, _ = pool.stats(); pending != 3 {
  759. t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  760. }
  761. }
  762. // Tests that when the pool reaches its global transaction limit, underpriced
  763. // transactions are gradually shifted out for more expensive ones and any gapped
  764. // pending transactions are moved into te queue.
  765. //
  766. // Note, local transactions are never allowed to be dropped.
  767. func TestTransactionPoolUnderpricing(t *testing.T) {
  768. // Reduce the queue limits to shorten test time
  769. defer func(old uint64) { maxPendingTotal = old }(maxPendingTotal)
  770. maxPendingTotal = 2
  771. defer func(old uint64) { maxQueuedTotal = old }(maxQueuedTotal)
  772. maxQueuedTotal = 2
  773. // Create the pool to test the pricing enforcement with
  774. db, _ := ethdb.NewMemDatabase()
  775. statedb, _ := state.New(common.Hash{}, db)
  776. pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  777. pool.resetState()
  778. // Create a number of test accounts and fund them
  779. state, _ := pool.currentState()
  780. keys := make([]*ecdsa.PrivateKey, 3)
  781. for i := 0; i < len(keys); i++ {
  782. keys[i], _ = crypto.GenerateKey()
  783. state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  784. }
  785. // Generate and queue a batch of transactions, both pending and queued
  786. txs := types.Transactions{}
  787. txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[0]))
  788. txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(2), keys[0]))
  789. txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[1]))
  790. txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[2]))
  791. pool.SetLocal(txs[len(txs)-1]) // prevent this one from ever being dropped
  792. // Import the batch and that both pending and queued transactions match up
  793. pool.AddBatch(txs)
  794. pending, queued := pool.stats()
  795. if pending != 3 {
  796. t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
  797. }
  798. if queued != 1 {
  799. t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
  800. }
  801. // Ensure that adding an underpriced transaction on block limit fails
  802. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[1])); err != ErrUnderpriced {
  803. t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
  804. }
  805. // Ensure that adding high priced transactions drops cheap ones, but not own
  806. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(3), keys[1])); err != nil {
  807. t.Fatalf("failed to add well priced transaction: %v", err)
  808. }
  809. if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(4), keys[1])); err != nil {
  810. t.Fatalf("failed to add well priced transaction: %v", err)
  811. }
  812. if err := pool.Add(pricedTransaction(3, big.NewInt(100000), big.NewInt(5), keys[1])); err != nil {
  813. t.Fatalf("failed to add well priced transaction: %v", err)
  814. }
  815. pending, queued = pool.stats()
  816. if pending != 2 {
  817. t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  818. }
  819. if queued != 2 {
  820. t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
  821. }
  822. // Ensure that adding local transactions can push out even higher priced ones
  823. tx := pricedTransaction(1, big.NewInt(100000), big.NewInt(0), keys[2])
  824. pool.SetLocal(tx) // prevent this one from ever being dropped
  825. if err := pool.Add(tx); err != nil {
  826. t.Fatalf("failed to add underpriced local transaction: %v", err)
  827. }
  828. pending, queued = pool.stats()
  829. if pending != 2 {
  830. t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
  831. }
  832. if queued != 2 {
  833. t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
  834. }
  835. }
  836. // Tests that the pool rejects replacement transactions that don't meet the minimum
  837. // price bump required.
  838. func TestTransactionReplacement(t *testing.T) {
  839. // Create the pool to test the pricing enforcement with
  840. db, _ := ethdb.NewMemDatabase()
  841. statedb, _ := state.New(common.Hash{}, db)
  842. pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  843. pool.resetState()
  844. // Create a a test account to add transactions with
  845. key, _ := crypto.GenerateKey()
  846. state, _ := pool.currentState()
  847. state.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))
  848. // Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
  849. price := int64(100)
  850. threshold := (price * (100 + minPriceBumpPercent)) / 100
  851. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(1), key)); err != nil {
  852. t.Fatalf("failed to add original cheap pending transaction: %v", err)
  853. }
  854. if err := pool.Add(pricedTransaction(0, big.NewInt(100001), big.NewInt(1), key)); err != ErrReplaceUnderpriced {
  855. t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  856. }
  857. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(2), key)); err != nil {
  858. t.Fatalf("failed to replace original cheap pending transaction: %v", err)
  859. }
  860. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(price), key)); err != nil {
  861. t.Fatalf("failed to add original proper pending transaction: %v", err)
  862. }
  863. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(threshold), key)); err != ErrReplaceUnderpriced {
  864. t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  865. }
  866. if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(threshold+1), key)); err != nil {
  867. t.Fatalf("failed to replace original proper pending transaction: %v", err)
  868. }
  869. // Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
  870. if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(1), key)); err != nil {
  871. t.Fatalf("failed to add original queued transaction: %v", err)
  872. }
  873. if err := pool.Add(pricedTransaction(2, big.NewInt(100001), big.NewInt(1), key)); err != ErrReplaceUnderpriced {
  874. t.Fatalf("original queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  875. }
  876. if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(2), key)); err != nil {
  877. t.Fatalf("failed to replace original queued transaction: %v", err)
  878. }
  879. if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(price), key)); err != nil {
  880. t.Fatalf("failed to add original queued transaction: %v", err)
  881. }
  882. if err := pool.Add(pricedTransaction(2, big.NewInt(100001), big.NewInt(threshold), key)); err != ErrReplaceUnderpriced {
  883. t.Fatalf("original queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
  884. }
  885. if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(threshold+1), key)); err != nil {
  886. t.Fatalf("failed to replace original queued transaction: %v", err)
  887. }
  888. }
  889. // Benchmarks the speed of validating the contents of the pending queue of the
  890. // transaction pool.
  891. func BenchmarkPendingDemotion100(b *testing.B) { benchmarkPendingDemotion(b, 100) }
  892. func BenchmarkPendingDemotion1000(b *testing.B) { benchmarkPendingDemotion(b, 1000) }
  893. func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) }
  894. func benchmarkPendingDemotion(b *testing.B, size int) {
  895. // Add a batch of transactions to a pool one by one
  896. pool, key := setupTxPool()
  897. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  898. state, _ := pool.currentState()
  899. state.AddBalance(account, big.NewInt(1000000))
  900. for i := 0; i < size; i++ {
  901. tx := transaction(uint64(i), big.NewInt(100000), key)
  902. pool.promoteTx(account, tx.Hash(), tx)
  903. }
  904. // Benchmark the speed of pool validation
  905. b.ResetTimer()
  906. for i := 0; i < b.N; i++ {
  907. pool.demoteUnexecutables(state)
  908. }
  909. }
  910. // Benchmarks the speed of scheduling the contents of the future queue of the
  911. // transaction pool.
  912. func BenchmarkFuturePromotion100(b *testing.B) { benchmarkFuturePromotion(b, 100) }
  913. func BenchmarkFuturePromotion1000(b *testing.B) { benchmarkFuturePromotion(b, 1000) }
  914. func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) }
  915. func benchmarkFuturePromotion(b *testing.B, size int) {
  916. // Add a batch of transactions to a pool one by one
  917. pool, key := setupTxPool()
  918. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  919. state, _ := pool.currentState()
  920. state.AddBalance(account, big.NewInt(1000000))
  921. for i := 0; i < size; i++ {
  922. tx := transaction(uint64(1+i), big.NewInt(100000), key)
  923. pool.enqueueTx(tx.Hash(), tx)
  924. }
  925. // Benchmark the speed of pool validation
  926. b.ResetTimer()
  927. for i := 0; i < b.N; i++ {
  928. pool.promoteExecutables(state)
  929. }
  930. }
  931. // Benchmarks the speed of iterative transaction insertion.
  932. func BenchmarkPoolInsert(b *testing.B) {
  933. // Generate a batch of transactions to enqueue into the pool
  934. pool, key := setupTxPool()
  935. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  936. state, _ := pool.currentState()
  937. state.AddBalance(account, big.NewInt(1000000))
  938. txs := make(types.Transactions, b.N)
  939. for i := 0; i < b.N; i++ {
  940. txs[i] = transaction(uint64(i), big.NewInt(100000), key)
  941. }
  942. // Benchmark importing the transactions into the queue
  943. b.ResetTimer()
  944. for _, tx := range txs {
  945. pool.Add(tx)
  946. }
  947. }
  948. // Benchmarks the speed of batched transaction insertion.
  949. func BenchmarkPoolBatchInsert100(b *testing.B) { benchmarkPoolBatchInsert(b, 100) }
  950. func BenchmarkPoolBatchInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000) }
  951. func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000) }
  952. func benchmarkPoolBatchInsert(b *testing.B, size int) {
  953. // Generate a batch of transactions to enqueue into the pool
  954. pool, key := setupTxPool()
  955. account, _ := deriveSender(transaction(0, big.NewInt(0), key))
  956. state, _ := pool.currentState()
  957. state.AddBalance(account, big.NewInt(1000000))
  958. batches := make([]types.Transactions, b.N)
  959. for i := 0; i < b.N; i++ {
  960. batches[i] = make(types.Transactions, size)
  961. for j := 0; j < size; j++ {
  962. batches[i][j] = transaction(uint64(size*i+j), big.NewInt(100000), key)
  963. }
  964. }
  965. // Benchmark importing the transactions into the queue
  966. b.ResetTimer()
  967. for _, batch := range batches {
  968. pool.AddBatch(batch)
  969. }
  970. }