tx_pool_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. )
  30. func transaction(nonce uint64, gaslimit *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
  31. tx, _ := types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, big.NewInt(1), nil).SignECDSA(key)
  32. return tx
  33. }
  34. func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
  35. db, _ := ethdb.NewMemDatabase()
  36. statedb, _ := state.New(common.Hash{}, db)
  37. key, _ := crypto.GenerateKey()
  38. newPool := NewTxPool(testChainConfig(), new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  39. newPool.resetState()
  40. return newPool, key
  41. }
  42. func TestInvalidTransactions(t *testing.T) {
  43. pool, key := setupTxPool()
  44. tx := transaction(0, big.NewInt(100), key)
  45. if err := pool.Add(tx); err != ErrNonExistentAccount {
  46. t.Error("expected", ErrNonExistentAccount)
  47. }
  48. from, _ := tx.From()
  49. currentState, _ := pool.currentState()
  50. currentState.AddBalance(from, big.NewInt(1))
  51. if err := pool.Add(tx); err != ErrInsufficientFunds {
  52. t.Error("expected", ErrInsufficientFunds)
  53. }
  54. balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice()))
  55. currentState.AddBalance(from, balance)
  56. if err := pool.Add(tx); err != ErrIntrinsicGas {
  57. t.Error("expected", ErrIntrinsicGas, "got", err)
  58. }
  59. currentState.SetNonce(from, 1)
  60. currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
  61. tx = transaction(0, big.NewInt(100000), key)
  62. if err := pool.Add(tx); err != ErrNonce {
  63. t.Error("expected", ErrNonce)
  64. }
  65. tx = transaction(1, big.NewInt(100000), key)
  66. pool.minGasPrice = big.NewInt(1000)
  67. if err := pool.Add(tx); err != ErrCheap {
  68. t.Error("expected", ErrCheap, "got", err)
  69. }
  70. pool.SetLocal(tx)
  71. if err := pool.Add(tx); err != nil {
  72. t.Error("expected", nil, "got", err)
  73. }
  74. }
  75. func TestTransactionQueue(t *testing.T) {
  76. pool, key := setupTxPool()
  77. tx := transaction(0, big.NewInt(100), key)
  78. from, _ := tx.From()
  79. currentState, _ := pool.currentState()
  80. currentState.AddBalance(from, big.NewInt(1000))
  81. pool.enqueueTx(tx.Hash(), tx)
  82. pool.promoteExecutables()
  83. if len(pool.pending) != 1 {
  84. t.Error("expected valid txs to be 1 is", len(pool.pending))
  85. }
  86. tx = transaction(1, big.NewInt(100), key)
  87. from, _ = tx.From()
  88. currentState.SetNonce(from, 2)
  89. pool.enqueueTx(tx.Hash(), tx)
  90. pool.promoteExecutables()
  91. if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok {
  92. t.Error("expected transaction to be in tx pool")
  93. }
  94. if len(pool.queue) > 0 {
  95. t.Error("expected transaction queue to be empty. is", len(pool.queue))
  96. }
  97. pool, key = setupTxPool()
  98. tx1 := transaction(0, big.NewInt(100), key)
  99. tx2 := transaction(10, big.NewInt(100), key)
  100. tx3 := transaction(11, big.NewInt(100), key)
  101. from, _ = tx1.From()
  102. currentState, _ = pool.currentState()
  103. currentState.AddBalance(from, big.NewInt(1000))
  104. pool.enqueueTx(tx1.Hash(), tx1)
  105. pool.enqueueTx(tx2.Hash(), tx2)
  106. pool.enqueueTx(tx3.Hash(), tx3)
  107. pool.promoteExecutables()
  108. if len(pool.pending) != 1 {
  109. t.Error("expected tx pool to be 1, got", len(pool.pending))
  110. }
  111. if pool.queue[from].Len() != 2 {
  112. t.Error("expected len(queue) == 2, got", pool.queue[from].Len())
  113. }
  114. }
  115. func TestRemoveTx(t *testing.T) {
  116. pool, key := setupTxPool()
  117. tx := transaction(0, big.NewInt(100), key)
  118. from, _ := tx.From()
  119. currentState, _ := pool.currentState()
  120. currentState.AddBalance(from, big.NewInt(1))
  121. pool.enqueueTx(tx.Hash(), tx)
  122. pool.promoteTx(from, tx.Hash(), tx)
  123. if len(pool.queue) != 1 {
  124. t.Error("expected queue to be 1, got", len(pool.queue))
  125. }
  126. if len(pool.pending) != 1 {
  127. t.Error("expected pending to be 1, got", len(pool.pending))
  128. }
  129. pool.Remove(tx.Hash())
  130. if len(pool.queue) > 0 {
  131. t.Error("expected queue to be 0, got", len(pool.queue))
  132. }
  133. if len(pool.pending) > 0 {
  134. t.Error("expected pending to be 0, got", len(pool.pending))
  135. }
  136. }
  137. func TestNegativeValue(t *testing.T) {
  138. pool, key := setupTxPool()
  139. tx, _ := types.NewTransaction(0, common.Address{}, big.NewInt(-1), big.NewInt(100), big.NewInt(1), nil).SignECDSA(key)
  140. from, _ := tx.From()
  141. currentState, _ := pool.currentState()
  142. currentState.AddBalance(from, big.NewInt(1))
  143. if err := pool.Add(tx); err != ErrNegativeValue {
  144. t.Error("expected", ErrNegativeValue, "got", err)
  145. }
  146. }
  147. func TestTransactionChainFork(t *testing.T) {
  148. pool, key := setupTxPool()
  149. addr := crypto.PubkeyToAddress(key.PublicKey)
  150. resetState := func() {
  151. db, _ := ethdb.NewMemDatabase()
  152. statedb, _ := state.New(common.Hash{}, db)
  153. pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
  154. currentState, _ := pool.currentState()
  155. currentState.AddBalance(addr, big.NewInt(100000000000000))
  156. pool.resetState()
  157. }
  158. resetState()
  159. tx := transaction(0, big.NewInt(100000), key)
  160. if err := pool.add(tx); err != nil {
  161. t.Error("didn't expect error", err)
  162. }
  163. pool.RemoveBatch([]*types.Transaction{tx})
  164. // reset the pool's internal state
  165. resetState()
  166. if err := pool.add(tx); err != nil {
  167. t.Error("didn't expect error", err)
  168. }
  169. }
  170. func TestTransactionDoubleNonce(t *testing.T) {
  171. pool, key := setupTxPool()
  172. addr := crypto.PubkeyToAddress(key.PublicKey)
  173. resetState := func() {
  174. db, _ := ethdb.NewMemDatabase()
  175. statedb, _ := state.New(common.Hash{}, db)
  176. pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
  177. currentState, _ := pool.currentState()
  178. currentState.AddBalance(addr, big.NewInt(100000000000000))
  179. pool.resetState()
  180. }
  181. resetState()
  182. tx1, _ := types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(100000), big.NewInt(1), nil).SignECDSA(key)
  183. tx2, _ := types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(1000000), big.NewInt(2), nil).SignECDSA(key)
  184. tx3, _ := types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(1000000), big.NewInt(1), nil).SignECDSA(key)
  185. // Add the first two transaction, ensure higher priced stays only
  186. if err := pool.add(tx1); err != nil {
  187. t.Error("didn't expect error", err)
  188. }
  189. if err := pool.add(tx2); err != nil {
  190. t.Error("didn't expect error", err)
  191. }
  192. pool.promoteExecutables()
  193. if pool.pending[addr].Len() != 1 {
  194. t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
  195. }
  196. if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
  197. t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
  198. }
  199. // Add the thid transaction and ensure it's not saved (smaller price)
  200. if err := pool.add(tx3); err != nil {
  201. t.Error("didn't expect error", err)
  202. }
  203. pool.promoteExecutables()
  204. if pool.pending[addr].Len() != 1 {
  205. t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
  206. }
  207. if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
  208. t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
  209. }
  210. // Ensure the total transaction count is correct
  211. if len(pool.all) != 1 {
  212. t.Error("expected 1 total transactions, got", len(pool.all))
  213. }
  214. }
  215. func TestMissingNonce(t *testing.T) {
  216. pool, key := setupTxPool()
  217. addr := crypto.PubkeyToAddress(key.PublicKey)
  218. currentState, _ := pool.currentState()
  219. currentState.AddBalance(addr, big.NewInt(100000000000000))
  220. tx := transaction(1, big.NewInt(100000), key)
  221. if err := pool.add(tx); err != nil {
  222. t.Error("didn't expect error", err)
  223. }
  224. if len(pool.pending) != 0 {
  225. t.Error("expected 0 pending transactions, got", len(pool.pending))
  226. }
  227. if pool.queue[addr].Len() != 1 {
  228. t.Error("expected 1 queued transaction, got", pool.queue[addr].Len())
  229. }
  230. if len(pool.all) != 1 {
  231. t.Error("expected 1 total transactions, got", len(pool.all))
  232. }
  233. }
  234. func TestNonceRecovery(t *testing.T) {
  235. const n = 10
  236. pool, key := setupTxPool()
  237. addr := crypto.PubkeyToAddress(key.PublicKey)
  238. currentState, _ := pool.currentState()
  239. currentState.SetNonce(addr, n)
  240. currentState.AddBalance(addr, big.NewInt(100000000000000))
  241. pool.resetState()
  242. tx := transaction(n, big.NewInt(100000), key)
  243. if err := pool.Add(tx); err != nil {
  244. t.Error(err)
  245. }
  246. // simulate some weird re-order of transactions and missing nonce(s)
  247. currentState.SetNonce(addr, n-1)
  248. pool.resetState()
  249. if fn := pool.pendingState.GetNonce(addr); fn != n+1 {
  250. t.Errorf("expected nonce to be %d, got %d", n+1, fn)
  251. }
  252. }
  253. func TestRemovedTxEvent(t *testing.T) {
  254. pool, key := setupTxPool()
  255. tx := transaction(0, big.NewInt(1000000), key)
  256. from, _ := tx.From()
  257. currentState, _ := pool.currentState()
  258. currentState.AddBalance(from, big.NewInt(1000000000000))
  259. pool.eventMux.Post(RemovedTransactionEvent{types.Transactions{tx}})
  260. pool.eventMux.Post(ChainHeadEvent{nil})
  261. if pool.pending[from].Len() != 1 {
  262. t.Error("expected 1 pending tx, got", pool.pending[from].Len())
  263. }
  264. if len(pool.all) != 1 {
  265. t.Error("expected 1 total transactions, got", len(pool.all))
  266. }
  267. }
  268. // Tests that if an account runs out of funds, any pending and queued transactions
  269. // are dropped.
  270. func TestTransactionDropping(t *testing.T) {
  271. // Create a test account and fund it
  272. pool, key := setupTxPool()
  273. account, _ := transaction(0, big.NewInt(0), key).From()
  274. state, _ := pool.currentState()
  275. state.AddBalance(account, big.NewInt(1000))
  276. // Add some pending and some queued transactions
  277. var (
  278. tx0 = transaction(0, big.NewInt(100), key)
  279. tx1 = transaction(1, big.NewInt(200), key)
  280. tx10 = transaction(10, big.NewInt(100), key)
  281. tx11 = transaction(11, big.NewInt(200), key)
  282. )
  283. pool.promoteTx(account, tx0.Hash(), tx0)
  284. pool.promoteTx(account, tx1.Hash(), tx1)
  285. pool.enqueueTx(tx10.Hash(), tx10)
  286. pool.enqueueTx(tx11.Hash(), tx11)
  287. // Check that pre and post validations leave the pool as is
  288. if pool.pending[account].Len() != 2 {
  289. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 2)
  290. }
  291. if pool.queue[account].Len() != 2 {
  292. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 2)
  293. }
  294. if len(pool.all) != 4 {
  295. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 4)
  296. }
  297. pool.resetState()
  298. if pool.pending[account].Len() != 2 {
  299. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 2)
  300. }
  301. if pool.queue[account].Len() != 2 {
  302. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 2)
  303. }
  304. if len(pool.all) != 4 {
  305. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 4)
  306. }
  307. // Reduce the balance of the account, and check that invalidated transactions are dropped
  308. state.AddBalance(account, big.NewInt(-750))
  309. pool.resetState()
  310. if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
  311. t.Errorf("funded pending transaction missing: %v", tx0)
  312. }
  313. if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok {
  314. t.Errorf("out-of-fund pending transaction present: %v", tx1)
  315. }
  316. if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
  317. t.Errorf("funded queued transaction missing: %v", tx10)
  318. }
  319. if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok {
  320. t.Errorf("out-of-fund queued transaction present: %v", tx11)
  321. }
  322. if len(pool.all) != 2 {
  323. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 2)
  324. }
  325. }
  326. // Tests that if a transaction is dropped from the current pending pool (e.g. out
  327. // of fund), all consecutive (still valid, but not executable) transactions are
  328. // postponed back into the future queue to prevent broadcasting them.
  329. func TestTransactionPostponing(t *testing.T) {
  330. // Create a test account and fund it
  331. pool, key := setupTxPool()
  332. account, _ := transaction(0, big.NewInt(0), key).From()
  333. state, _ := pool.currentState()
  334. state.AddBalance(account, big.NewInt(1000))
  335. // Add a batch consecutive pending transactions for validation
  336. txns := []*types.Transaction{}
  337. for i := 0; i < 100; i++ {
  338. var tx *types.Transaction
  339. if i%2 == 0 {
  340. tx = transaction(uint64(i), big.NewInt(100), key)
  341. } else {
  342. tx = transaction(uint64(i), big.NewInt(500), key)
  343. }
  344. pool.promoteTx(account, tx.Hash(), tx)
  345. txns = append(txns, tx)
  346. }
  347. // Check that pre and post validations leave the pool as is
  348. if pool.pending[account].Len() != len(txns) {
  349. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), len(txns))
  350. }
  351. if len(pool.queue) != 0 {
  352. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 0)
  353. }
  354. if len(pool.all) != len(txns) {
  355. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns))
  356. }
  357. pool.resetState()
  358. if pool.pending[account].Len() != len(txns) {
  359. t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), len(txns))
  360. }
  361. if len(pool.queue) != 0 {
  362. t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 0)
  363. }
  364. if len(pool.all) != len(txns) {
  365. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns))
  366. }
  367. // Reduce the balance of the account, and check that transactions are reorganised
  368. state.AddBalance(account, big.NewInt(-750))
  369. pool.resetState()
  370. if _, ok := pool.pending[account].txs.items[txns[0].Nonce()]; !ok {
  371. t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txns[0])
  372. }
  373. if _, ok := pool.queue[account].txs.items[txns[0].Nonce()]; ok {
  374. t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txns[0])
  375. }
  376. for i, tx := range txns[1:] {
  377. if i%2 == 1 {
  378. if _, ok := pool.pending[account].txs.items[tx.Nonce()]; ok {
  379. t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx)
  380. }
  381. if _, ok := pool.queue[account].txs.items[tx.Nonce()]; !ok {
  382. t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx)
  383. }
  384. } else {
  385. if _, ok := pool.pending[account].txs.items[tx.Nonce()]; ok {
  386. t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx)
  387. }
  388. if _, ok := pool.queue[account].txs.items[tx.Nonce()]; ok {
  389. t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx)
  390. }
  391. }
  392. }
  393. if len(pool.all) != len(txns)/2 {
  394. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns)/2)
  395. }
  396. }
  397. // Tests that if the transaction count belonging to a single account goes above
  398. // some threshold, the higher transactions are dropped to prevent DOS attacks.
  399. func TestTransactionQueueAccountLimiting(t *testing.T) {
  400. // Create a test account and fund it
  401. pool, key := setupTxPool()
  402. account, _ := transaction(0, big.NewInt(0), key).From()
  403. state, _ := pool.currentState()
  404. state.AddBalance(account, big.NewInt(1000000))
  405. // Keep queuing up transactions and make sure all above a limit are dropped
  406. for i := uint64(1); i <= maxQueuedPerAccount+5; i++ {
  407. if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
  408. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  409. }
  410. if len(pool.pending) != 0 {
  411. t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0)
  412. }
  413. if i <= maxQueuedPerAccount {
  414. if pool.queue[account].Len() != int(i) {
  415. t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i)
  416. }
  417. } else {
  418. if pool.queue[account].Len() != int(maxQueuedPerAccount) {
  419. t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), maxQueuedPerAccount)
  420. }
  421. }
  422. }
  423. if len(pool.all) != int(maxQueuedPerAccount) {
  424. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), maxQueuedPerAccount)
  425. }
  426. }
  427. // Tests that if the transaction count belonging to multiple accounts go above
  428. // some threshold, the higher transactions are dropped to prevent DOS attacks.
  429. func TestTransactionQueueGlobalLimiting(t *testing.T) {
  430. // Reduce the queue limits to shorten test time
  431. defer func(old uint64) { maxQueuedInTotal = old }(maxQueuedInTotal)
  432. maxQueuedInTotal = maxQueuedPerAccount * 3
  433. // Create the pool to test the limit enforcement with
  434. db, _ := ethdb.NewMemDatabase()
  435. statedb, _ := state.New(common.Hash{}, db)
  436. pool := NewTxPool(testChainConfig(), new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
  437. pool.resetState()
  438. // Create a number of test accounts and fund them
  439. state, _ := pool.currentState()
  440. keys := make([]*ecdsa.PrivateKey, 5)
  441. for i := 0; i < len(keys); i++ {
  442. keys[i], _ = crypto.GenerateKey()
  443. state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
  444. }
  445. // Generate and queue a batch of transactions
  446. nonces := make(map[common.Address]uint64)
  447. txs := make(types.Transactions, 0, 3*maxQueuedInTotal)
  448. for len(txs) < cap(txs) {
  449. key := keys[rand.Intn(len(keys))]
  450. addr := crypto.PubkeyToAddress(key.PublicKey)
  451. txs = append(txs, transaction(nonces[addr]+1, big.NewInt(100000), key))
  452. nonces[addr]++
  453. }
  454. // Import the batch and verify that limits have been enforced
  455. pool.AddBatch(txs)
  456. queued := 0
  457. for addr, list := range pool.queue {
  458. if list.Len() > int(maxQueuedPerAccount) {
  459. t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), maxQueuedPerAccount)
  460. }
  461. queued += list.Len()
  462. }
  463. if queued > int(maxQueuedInTotal) {
  464. t.Fatalf("total transactions overflow allowance: %d > %d", queued, maxQueuedInTotal)
  465. }
  466. }
  467. // Tests that if an account remains idle for a prolonged amount of time, any
  468. // non-executable transactions queued up are dropped to prevent wasting resources
  469. // on shuffling them around.
  470. func TestTransactionQueueTimeLimiting(t *testing.T) {
  471. // Reduce the queue limits to shorten test time
  472. defer func(old time.Duration) { maxQueuedLifetime = old }(maxQueuedLifetime)
  473. defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
  474. maxQueuedLifetime = time.Second
  475. evictionInterval = time.Second
  476. // Create a test account and fund it
  477. pool, key := setupTxPool()
  478. account, _ := transaction(0, big.NewInt(0), key).From()
  479. state, _ := pool.currentState()
  480. state.AddBalance(account, big.NewInt(1000000))
  481. // Queue up a batch of transactions
  482. for i := uint64(1); i <= maxQueuedPerAccount; i++ {
  483. if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
  484. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  485. }
  486. }
  487. // Wait until at least two expiration cycles hit and make sure the transactions are gone
  488. time.Sleep(2 * evictionInterval)
  489. if len(pool.queue) > 0 {
  490. t.Fatalf("old transactions remained after eviction")
  491. }
  492. }
  493. // Tests that even if the transaction count belonging to a single account goes
  494. // above some threshold, as long as the transactions are executable, they are
  495. // accepted.
  496. func TestTransactionPendingLimiting(t *testing.T) {
  497. // Create a test account and fund it
  498. pool, key := setupTxPool()
  499. account, _ := transaction(0, big.NewInt(0), key).From()
  500. state, _ := pool.currentState()
  501. state.AddBalance(account, big.NewInt(1000000))
  502. // Keep queuing up transactions and make sure all above a limit are dropped
  503. for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
  504. if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
  505. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  506. }
  507. if pool.pending[account].Len() != int(i)+1 {
  508. t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1)
  509. }
  510. if len(pool.queue) != 0 {
  511. t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
  512. }
  513. }
  514. if len(pool.all) != int(maxQueuedPerAccount+5) {
  515. t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), maxQueuedPerAccount+5)
  516. }
  517. }
  518. // Tests that the transaction limits are enforced the same way irrelevant whether
  519. // the transactions are added one by one or in batches.
  520. func TestTransactionQueueLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 1) }
  521. func TestTransactionPendingLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 0) }
  522. func testTransactionLimitingEquivalency(t *testing.T, origin uint64) {
  523. // Add a batch of transactions to a pool one by one
  524. pool1, key1 := setupTxPool()
  525. account1, _ := transaction(0, big.NewInt(0), key1).From()
  526. state1, _ := pool1.currentState()
  527. state1.AddBalance(account1, big.NewInt(1000000))
  528. for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
  529. if err := pool1.Add(transaction(origin+i, big.NewInt(100000), key1)); err != nil {
  530. t.Fatalf("tx %d: failed to add transaction: %v", i, err)
  531. }
  532. }
  533. // Add a batch of transactions to a pool in one big batch
  534. pool2, key2 := setupTxPool()
  535. account2, _ := transaction(0, big.NewInt(0), key2).From()
  536. state2, _ := pool2.currentState()
  537. state2.AddBalance(account2, big.NewInt(1000000))
  538. txns := []*types.Transaction{}
  539. for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
  540. txns = append(txns, transaction(origin+i, big.NewInt(100000), key2))
  541. }
  542. pool2.AddBatch(txns)
  543. // Ensure the batch optimization honors the same pool mechanics
  544. if len(pool1.pending) != len(pool2.pending) {
  545. t.Errorf("pending transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.pending), len(pool2.pending))
  546. }
  547. if len(pool1.queue) != len(pool2.queue) {
  548. t.Errorf("queued transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.queue), len(pool2.queue))
  549. }
  550. if len(pool1.all) != len(pool2.all) {
  551. t.Errorf("total transaction count mismatch: one-by-one algo %d, batch algo %d", len(pool1.all), len(pool2.all))
  552. }
  553. }
  554. // Benchmarks the speed of validating the contents of the pending queue of the
  555. // transaction pool.
  556. func BenchmarkPendingDemotion100(b *testing.B) { benchmarkPendingDemotion(b, 100) }
  557. func BenchmarkPendingDemotion1000(b *testing.B) { benchmarkPendingDemotion(b, 1000) }
  558. func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) }
  559. func benchmarkPendingDemotion(b *testing.B, size int) {
  560. // Add a batch of transactions to a pool one by one
  561. pool, key := setupTxPool()
  562. account, _ := transaction(0, big.NewInt(0), key).From()
  563. state, _ := pool.currentState()
  564. state.AddBalance(account, big.NewInt(1000000))
  565. for i := 0; i < size; i++ {
  566. tx := transaction(uint64(i), big.NewInt(100000), key)
  567. pool.promoteTx(account, tx.Hash(), tx)
  568. }
  569. // Benchmark the speed of pool validation
  570. b.ResetTimer()
  571. for i := 0; i < b.N; i++ {
  572. pool.demoteUnexecutables()
  573. }
  574. }
  575. // Benchmarks the speed of scheduling the contents of the future queue of the
  576. // transaction pool.
  577. func BenchmarkFuturePromotion100(b *testing.B) { benchmarkFuturePromotion(b, 100) }
  578. func BenchmarkFuturePromotion1000(b *testing.B) { benchmarkFuturePromotion(b, 1000) }
  579. func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) }
  580. func benchmarkFuturePromotion(b *testing.B, size int) {
  581. // Add a batch of transactions to a pool one by one
  582. pool, key := setupTxPool()
  583. account, _ := transaction(0, big.NewInt(0), key).From()
  584. state, _ := pool.currentState()
  585. state.AddBalance(account, big.NewInt(1000000))
  586. for i := 0; i < size; i++ {
  587. tx := transaction(uint64(1+i), big.NewInt(100000), key)
  588. pool.enqueueTx(tx.Hash(), tx)
  589. }
  590. // Benchmark the speed of pool validation
  591. b.ResetTimer()
  592. for i := 0; i < b.N; i++ {
  593. pool.promoteExecutables()
  594. }
  595. }
  596. // Benchmarks the speed of iterative transaction insertion.
  597. func BenchmarkPoolInsert(b *testing.B) {
  598. // Generate a batch of transactions to enqueue into the pool
  599. pool, key := setupTxPool()
  600. account, _ := transaction(0, big.NewInt(0), key).From()
  601. state, _ := pool.currentState()
  602. state.AddBalance(account, big.NewInt(1000000))
  603. txs := make(types.Transactions, b.N)
  604. for i := 0; i < b.N; i++ {
  605. txs[i] = transaction(uint64(i), big.NewInt(100000), key)
  606. }
  607. // Benchmark importing the transactions into the queue
  608. b.ResetTimer()
  609. for _, tx := range txs {
  610. pool.Add(tx)
  611. }
  612. }
  613. // Benchmarks the speed of batched transaction insertion.
  614. func BenchmarkPoolBatchInsert100(b *testing.B) { benchmarkPoolBatchInsert(b, 100) }
  615. func BenchmarkPoolBatchInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000) }
  616. func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000) }
  617. func benchmarkPoolBatchInsert(b *testing.B, size int) {
  618. // Generate a batch of transactions to enqueue into the pool
  619. pool, key := setupTxPool()
  620. account, _ := transaction(0, big.NewInt(0), key).From()
  621. state, _ := pool.currentState()
  622. state.AddBalance(account, big.NewInt(1000000))
  623. batches := make([]types.Transactions, b.N)
  624. for i := 0; i < b.N; i++ {
  625. batches[i] = make(types.Transactions, size)
  626. for j := 0; j < size; j++ {
  627. batches[i][j] = transaction(uint64(size*i+j), big.NewInt(100000), key)
  628. }
  629. }
  630. // Benchmark importing the transactions into the queue
  631. b.ResetTimer()
  632. for _, batch := range batches {
  633. pool.AddBatch(batch)
  634. }
  635. }