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