github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/core/tx_pool_test.go (about) 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 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 "github.com/intfoundation/intchain/common" 30 "github.com/intfoundation/intchain/core/rawdb" 31 "github.com/intfoundation/intchain/core/state" 32 "github.com/intfoundation/intchain/core/types" 33 "github.com/intfoundation/intchain/crypto" 34 "github.com/intfoundation/intchain/event" 35 "github.com/intfoundation/intchain/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 := rawdb.NewMemoryDatabase() 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, nil) 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 := rawdb.NewMemoryDatabase() 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.INT)) 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 = rawdb.NewMemoryDatabase() 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.INT)) 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, nil) 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 := rawdb.NewMemoryDatabase() 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 := rawdb.NewMemoryDatabase() 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 the pool to test the postponing with 561 db := rawdb.NewMemoryDatabase() 562 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 563 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 564 565 pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain, nil) 566 defer pool.Stop() 567 568 // Create two test accounts to produce different gap profiles with 569 keys := make([]*ecdsa.PrivateKey, 2) 570 accs := make([]common.Address, len(keys)) 571 572 for i := 0; i < len(keys); i++ { 573 keys[i], _ = crypto.GenerateKey() 574 accs[i] = crypto.PubkeyToAddress(keys[i].PublicKey) 575 576 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(50100)) 577 } 578 // Add a batch consecutive pending transactions for validation 579 txs := []*types.Transaction{} 580 for i, key := range keys { 581 582 for j := 0; j < 100; j++ { 583 var tx *types.Transaction 584 if (i+j)%2 == 0 { 585 tx = transaction(uint64(j), 25000, key) 586 } else { 587 tx = transaction(uint64(j), 50000, key) 588 } 589 txs = append(txs, tx) 590 } 591 } 592 for i, err := range pool.AddRemotes(txs) { 593 if err != nil { 594 t.Fatalf("tx %d: failed to add transactions: %v", i, err) 595 } 596 } 597 // Check that pre and post validations leave the pool as is 598 if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) { 599 t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs)) 600 } 601 if len(pool.queue) != 0 { 602 t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0) 603 } 604 if len(pool.all) != len(txs) { 605 t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txs)) 606 } 607 pool.lockedReset(nil, nil) 608 if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) { 609 t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs)) 610 } 611 if len(pool.queue) != 0 { 612 t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0) 613 } 614 if len(pool.all) != len(txs) { 615 t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txs)) 616 } 617 // Reduce the balance of the account, and check that transactions are reorganised 618 for _, addr := range accs { 619 pool.currentState.AddBalance(addr, big.NewInt(-1)) 620 } 621 pool.lockedReset(nil, nil) 622 623 // The first account's first transaction remains valid, check that subsequent 624 // ones are either filtered out, or queued up for later. 625 if _, ok := pool.pending[accs[0]].txs.items[txs[0].Nonce()]; !ok { 626 t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txs[0]) 627 } 628 if _, ok := pool.queue[accs[0]].txs.items[txs[0].Nonce()]; ok { 629 t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txs[0]) 630 } 631 for i, tx := range txs[1:100] { 632 if i%2 == 1 { 633 if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok { 634 t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx) 635 } 636 if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; !ok { 637 t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx) 638 } 639 } else { 640 if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok { 641 t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx) 642 } 643 if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; ok { 644 t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx) 645 } 646 } 647 } 648 // The second account's first transaction got invalid, check that all transactions 649 // are either filtered out, or queued up for later. 650 if pool.pending[accs[1]] != nil { 651 t.Errorf("invalidated account still has pending transactions") 652 } 653 for i, tx := range txs[100:] { 654 if i%2 == 1 { 655 if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; !ok { 656 t.Errorf("tx %d: valid but future transaction missing from future queue: %v", 100+i, tx) 657 } 658 } else { 659 if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; ok { 660 t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", 100+i, tx) 661 } 662 } 663 } 664 if len(pool.all) != len(txs)/2 { 665 t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txs)/2) 666 } 667 } 668 669 // Tests that if the transaction pool has both executable and non-executable 670 // transactions from an origin account, filling the nonce gap moves all queued 671 // ones into the pending pool. 672 func TestTransactionGapFilling(t *testing.T) { 673 t.Parallel() 674 675 // Create a test account and fund it 676 pool, key := setupTxPool() 677 defer pool.Stop() 678 679 account, _ := deriveSender(transaction(0, 0, key)) 680 pool.currentState.AddBalance(account, big.NewInt(1000000)) 681 682 // Keep track of transaction events to ensure all executables get announced 683 events := make(chan TxPreEvent, testTxPoolConfig.AccountQueue+5) 684 sub := pool.txFeed.Subscribe(events) 685 defer sub.Unsubscribe() 686 687 // Create a pending and a queued transaction with a nonce-gap in between 688 if err := pool.AddRemote(transaction(0, 100000, key)); err != nil { 689 t.Fatalf("failed to add pending transaction: %v", err) 690 } 691 if err := pool.AddRemote(transaction(2, 100000, key)); err != nil { 692 t.Fatalf("failed to add queued transaction: %v", err) 693 } 694 pending, queued := pool.Stats() 695 if pending != 1 { 696 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1) 697 } 698 if queued != 1 { 699 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) 700 } 701 if err := validateEvents(events, 1); err != nil { 702 t.Fatalf("original event firing failed: %v", err) 703 } 704 if err := validateTxPoolInternals(pool); err != nil { 705 t.Fatalf("pool internal state corrupted: %v", err) 706 } 707 // Fill the nonce gap and ensure all transactions become pending 708 if err := pool.AddRemote(transaction(1, 100000, key)); err != nil { 709 t.Fatalf("failed to add gapped transaction: %v", err) 710 } 711 pending, queued = pool.Stats() 712 if pending != 3 { 713 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) 714 } 715 if queued != 0 { 716 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) 717 } 718 if err := validateEvents(events, 2); err != nil { 719 t.Fatalf("gap-filling event firing failed: %v", err) 720 } 721 if err := validateTxPoolInternals(pool); err != nil { 722 t.Fatalf("pool internal state corrupted: %v", err) 723 } 724 } 725 726 // Tests that if the transaction count belonging to a single account goes above 727 // some threshold, the higher transactions are dropped to prevent DOS attacks. 728 func TestTransactionQueueAccountLimiting(t *testing.T) { 729 t.Parallel() 730 731 // Create a test account and fund it 732 pool, key := setupTxPool() 733 defer pool.Stop() 734 735 account, _ := deriveSender(transaction(0, 0, key)) 736 pool.currentState.AddBalance(account, big.NewInt(1000000)) 737 738 // Keep queuing up transactions and make sure all above a limit are dropped 739 for i := uint64(1); i <= testTxPoolConfig.AccountQueue+5; i++ { 740 if err := pool.AddRemote(transaction(i, 100000, key)); err != nil { 741 t.Fatalf("tx %d: failed to add transaction: %v", i, err) 742 } 743 if len(pool.pending) != 0 { 744 t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0) 745 } 746 if i <= testTxPoolConfig.AccountQueue { 747 if pool.queue[account].Len() != int(i) { 748 t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i) 749 } 750 } else { 751 if pool.queue[account].Len() != int(testTxPoolConfig.AccountQueue) { 752 t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), testTxPoolConfig.AccountQueue) 753 } 754 } 755 } 756 if len(pool.all) != int(testTxPoolConfig.AccountQueue) { 757 t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), testTxPoolConfig.AccountQueue) 758 } 759 } 760 761 // Tests that if the transaction count belonging to multiple accounts go above 762 // some threshold, the higher transactions are dropped to prevent DOS attacks. 763 // 764 // This logic should not hold for local transactions, unless the local tracking 765 // mechanism is disabled. 766 func TestTransactionQueueGlobalLimiting(t *testing.T) { 767 testTransactionQueueGlobalLimiting(t, false) 768 } 769 func TestTransactionQueueGlobalLimitingNoLocals(t *testing.T) { 770 testTransactionQueueGlobalLimiting(t, true) 771 } 772 773 func testTransactionQueueGlobalLimiting(t *testing.T, nolocals bool) { 774 t.Parallel() 775 776 // Create the pool to test the limit enforcement with 777 db := rawdb.NewMemoryDatabase() 778 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 779 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 780 781 config := testTxPoolConfig 782 config.NoLocals = nolocals 783 config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible) 784 785 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 786 defer pool.Stop() 787 788 // Create a number of test accounts and fund them (last one will be the local) 789 keys := make([]*ecdsa.PrivateKey, 5) 790 for i := 0; i < len(keys); i++ { 791 keys[i], _ = crypto.GenerateKey() 792 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) 793 } 794 local := keys[len(keys)-1] 795 796 // Generate and queue a batch of transactions 797 nonces := make(map[common.Address]uint64) 798 799 txs := make(types.Transactions, 0, 3*config.GlobalQueue) 800 for len(txs) < cap(txs) { 801 key := keys[rand.Intn(len(keys)-1)] // skip adding transactions with the local account 802 addr := crypto.PubkeyToAddress(key.PublicKey) 803 804 txs = append(txs, transaction(nonces[addr]+1, 100000, key)) 805 nonces[addr]++ 806 } 807 // Import the batch and verify that limits have been enforced 808 pool.AddRemotes(txs) 809 810 queued := 0 811 for addr, list := range pool.queue { 812 if list.Len() > int(config.AccountQueue) { 813 t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue) 814 } 815 queued += list.Len() 816 } 817 if queued > int(config.GlobalQueue) { 818 t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue) 819 } 820 // Generate a batch of transactions from the local account and import them 821 txs = txs[:0] 822 for i := uint64(0); i < 3*config.GlobalQueue; i++ { 823 txs = append(txs, transaction(i+1, 100000, local)) 824 } 825 pool.AddLocals(txs) 826 827 // If locals are disabled, the previous eviction algorithm should apply here too 828 if nolocals { 829 queued := 0 830 for addr, list := range pool.queue { 831 if list.Len() > int(config.AccountQueue) { 832 t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue) 833 } 834 queued += list.Len() 835 } 836 if queued > int(config.GlobalQueue) { 837 t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue) 838 } 839 } else { 840 // Local exemptions are enabled, make sure the local account owned the queue 841 if len(pool.queue) != 1 { 842 t.Errorf("multiple accounts in queue: have %v, want %v", len(pool.queue), 1) 843 } 844 // Also ensure no local transactions are ever dropped, even if above global limits 845 if queued := pool.queue[crypto.PubkeyToAddress(local.PublicKey)].Len(); uint64(queued) != 3*config.GlobalQueue { 846 t.Fatalf("local account queued transaction count mismatch: have %v, want %v", queued, 3*config.GlobalQueue) 847 } 848 } 849 } 850 851 // Tests that if an account remains idle for a prolonged amount of time, any 852 // non-executable transactions queued up are dropped to prevent wasting resources 853 // on shuffling them around. 854 // 855 // This logic should not hold for local transactions, unless the local tracking 856 // mechanism is disabled. 857 func TestTransactionQueueTimeLimiting(t *testing.T) { testTransactionQueueTimeLimiting(t, false) } 858 func TestTransactionQueueTimeLimitingNoLocals(t *testing.T) { testTransactionQueueTimeLimiting(t, true) } 859 860 func testTransactionQueueTimeLimiting(t *testing.T, nolocals bool) { 861 // Reduce the eviction interval to a testable amount 862 defer func(old time.Duration) { evictionInterval = old }(evictionInterval) 863 evictionInterval = time.Second 864 865 // Create the pool to test the non-expiration enforcement 866 db := rawdb.NewMemoryDatabase() 867 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 868 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 869 870 config := testTxPoolConfig 871 config.Lifetime = time.Second 872 config.NoLocals = nolocals 873 874 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 875 defer pool.Stop() 876 877 // Create two test accounts to ensure remotes expire but locals do not 878 local, _ := crypto.GenerateKey() 879 remote, _ := crypto.GenerateKey() 880 881 pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000)) 882 pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000)) 883 884 // Add the two transactions and ensure they both are queued up 885 if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil { 886 t.Fatalf("failed to add local transaction: %v", err) 887 } 888 if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), remote)); err != nil { 889 t.Fatalf("failed to add remote transaction: %v", err) 890 } 891 pending, queued := pool.Stats() 892 if pending != 0 { 893 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) 894 } 895 if queued != 2 { 896 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) 897 } 898 if err := validateTxPoolInternals(pool); err != nil { 899 t.Fatalf("pool internal state corrupted: %v", err) 900 } 901 // Wait a bit for eviction to run and clean up any leftovers, and ensure only the local remains 902 time.Sleep(2 * config.Lifetime) 903 904 pending, queued = pool.Stats() 905 if pending != 0 { 906 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) 907 } 908 if nolocals { 909 if queued != 0 { 910 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) 911 } 912 } else { 913 if queued != 1 { 914 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) 915 } 916 } 917 if err := validateTxPoolInternals(pool); err != nil { 918 t.Fatalf("pool internal state corrupted: %v", err) 919 } 920 } 921 922 // Tests that even if the transaction count belonging to a single account goes 923 // above some threshold, as long as the transactions are executable, they are 924 // accepted. 925 func TestTransactionPendingLimiting(t *testing.T) { 926 t.Parallel() 927 928 // Create a test account and fund it 929 pool, key := setupTxPool() 930 defer pool.Stop() 931 932 account, _ := deriveSender(transaction(0, 0, key)) 933 pool.currentState.AddBalance(account, big.NewInt(1000000)) 934 935 // Keep track of transaction events to ensure all executables get announced 936 events := make(chan TxPreEvent, testTxPoolConfig.AccountQueue+5) 937 sub := pool.txFeed.Subscribe(events) 938 defer sub.Unsubscribe() 939 940 // Keep queuing up transactions and make sure all above a limit are dropped 941 for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ { 942 if err := pool.AddRemote(transaction(i, 100000, key)); err != nil { 943 t.Fatalf("tx %d: failed to add transaction: %v", i, err) 944 } 945 if pool.pending[account].Len() != int(i)+1 { 946 t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1) 947 } 948 if len(pool.queue) != 0 { 949 t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0) 950 } 951 } 952 if len(pool.all) != int(testTxPoolConfig.AccountQueue+5) { 953 t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), testTxPoolConfig.AccountQueue+5) 954 } 955 if err := validateEvents(events, int(testTxPoolConfig.AccountQueue+5)); err != nil { 956 t.Fatalf("event firing failed: %v", err) 957 } 958 if err := validateTxPoolInternals(pool); err != nil { 959 t.Fatalf("pool internal state corrupted: %v", err) 960 } 961 } 962 963 // Tests that the transaction limits are enforced the same way irrelevant whether 964 // the transactions are added one by one or in batches. 965 func TestTransactionQueueLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 1) } 966 func TestTransactionPendingLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 0) } 967 968 func testTransactionLimitingEquivalency(t *testing.T, origin uint64) { 969 t.Parallel() 970 971 // Add a batch of transactions to a pool one by one 972 pool1, key1 := setupTxPool() 973 defer pool1.Stop() 974 975 account1, _ := deriveSender(transaction(0, 0, key1)) 976 pool1.currentState.AddBalance(account1, big.NewInt(1000000)) 977 978 for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ { 979 if err := pool1.AddRemote(transaction(origin+i, 100000, key1)); err != nil { 980 t.Fatalf("tx %d: failed to add transaction: %v", i, err) 981 } 982 } 983 // Add a batch of transactions to a pool in one big batch 984 pool2, key2 := setupTxPool() 985 defer pool2.Stop() 986 987 account2, _ := deriveSender(transaction(0, 0, key2)) 988 pool2.currentState.AddBalance(account2, big.NewInt(1000000)) 989 990 txs := []*types.Transaction{} 991 for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ { 992 txs = append(txs, transaction(origin+i, 100000, key2)) 993 } 994 pool2.AddRemotes(txs) 995 996 // Ensure the batch optimization honors the same pool mechanics 997 if len(pool1.pending) != len(pool2.pending) { 998 t.Errorf("pending transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.pending), len(pool2.pending)) 999 } 1000 if len(pool1.queue) != len(pool2.queue) { 1001 t.Errorf("queued transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.queue), len(pool2.queue)) 1002 } 1003 if len(pool1.all) != len(pool2.all) { 1004 t.Errorf("total transaction count mismatch: one-by-one algo %d, batch algo %d", len(pool1.all), len(pool2.all)) 1005 } 1006 if err := validateTxPoolInternals(pool1); err != nil { 1007 t.Errorf("pool 1 internal state corrupted: %v", err) 1008 } 1009 if err := validateTxPoolInternals(pool2); err != nil { 1010 t.Errorf("pool 2 internal state corrupted: %v", err) 1011 } 1012 } 1013 1014 // Tests that if the transaction count belonging to multiple accounts go above 1015 // some hard threshold, the higher transactions are dropped to prevent DOS 1016 // attacks. 1017 func TestTransactionPendingGlobalLimiting(t *testing.T) { 1018 t.Parallel() 1019 1020 // Create the pool to test the limit enforcement with 1021 db := rawdb.NewMemoryDatabase() 1022 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1023 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1024 1025 config := testTxPoolConfig 1026 config.GlobalSlots = config.AccountSlots * 10 1027 1028 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 1029 defer pool.Stop() 1030 1031 // Create a number of test accounts and fund them 1032 keys := make([]*ecdsa.PrivateKey, 5) 1033 for i := 0; i < len(keys); i++ { 1034 keys[i], _ = crypto.GenerateKey() 1035 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) 1036 } 1037 // Generate and queue a batch of transactions 1038 nonces := make(map[common.Address]uint64) 1039 1040 txs := types.Transactions{} 1041 for _, key := range keys { 1042 addr := crypto.PubkeyToAddress(key.PublicKey) 1043 for j := 0; j < int(config.GlobalSlots)/len(keys)*2; j++ { 1044 txs = append(txs, transaction(nonces[addr], 100000, key)) 1045 nonces[addr]++ 1046 } 1047 } 1048 // Import the batch and verify that limits have been enforced 1049 pool.AddRemotes(txs) 1050 1051 pending := 0 1052 for _, list := range pool.pending { 1053 pending += list.Len() 1054 } 1055 if pending > int(config.GlobalSlots) { 1056 t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, config.GlobalSlots) 1057 } 1058 if err := validateTxPoolInternals(pool); err != nil { 1059 t.Fatalf("pool internal state corrupted: %v", err) 1060 } 1061 } 1062 1063 // Tests that if transactions start being capped, transactions are also removed from 'all' 1064 func TestTransactionCapClearsFromAll(t *testing.T) { 1065 t.Parallel() 1066 1067 // Create the pool to test the limit enforcement with 1068 db := rawdb.NewMemoryDatabase() 1069 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1070 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1071 1072 config := testTxPoolConfig 1073 config.AccountSlots = 2 1074 config.AccountQueue = 2 1075 config.GlobalSlots = 8 1076 1077 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 1078 defer pool.Stop() 1079 1080 // Create a number of test accounts and fund them 1081 key, _ := crypto.GenerateKey() 1082 addr := crypto.PubkeyToAddress(key.PublicKey) 1083 pool.currentState.AddBalance(addr, big.NewInt(1000000)) 1084 1085 txs := types.Transactions{} 1086 for j := 0; j < int(config.GlobalSlots)*2; j++ { 1087 txs = append(txs, transaction(uint64(j), 100000, key)) 1088 } 1089 // Import the batch and verify that limits have been enforced 1090 pool.AddRemotes(txs) 1091 if err := validateTxPoolInternals(pool); err != nil { 1092 t.Fatalf("pool internal state corrupted: %v", err) 1093 } 1094 } 1095 1096 // Tests that if the transaction count belonging to multiple accounts go above 1097 // some hard threshold, if they are under the minimum guaranteed slot count then 1098 // the transactions are still kept. 1099 func TestTransactionPendingMinimumAllowance(t *testing.T) { 1100 t.Parallel() 1101 1102 // Create the pool to test the limit enforcement with 1103 db := rawdb.NewMemoryDatabase() 1104 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1105 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1106 1107 config := testTxPoolConfig 1108 config.GlobalSlots = 0 1109 1110 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 1111 defer pool.Stop() 1112 1113 // Create a number of test accounts and fund them 1114 keys := make([]*ecdsa.PrivateKey, 5) 1115 for i := 0; i < len(keys); i++ { 1116 keys[i], _ = crypto.GenerateKey() 1117 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) 1118 } 1119 // Generate and queue a batch of transactions 1120 nonces := make(map[common.Address]uint64) 1121 1122 txs := types.Transactions{} 1123 for _, key := range keys { 1124 addr := crypto.PubkeyToAddress(key.PublicKey) 1125 for j := 0; j < int(config.AccountSlots)*2; j++ { 1126 txs = append(txs, transaction(nonces[addr], 100000, key)) 1127 nonces[addr]++ 1128 } 1129 } 1130 // Import the batch and verify that limits have been enforced 1131 pool.AddRemotes(txs) 1132 1133 for addr, list := range pool.pending { 1134 if list.Len() != int(config.AccountSlots) { 1135 t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), config.AccountSlots) 1136 } 1137 } 1138 if err := validateTxPoolInternals(pool); err != nil { 1139 t.Fatalf("pool internal state corrupted: %v", err) 1140 } 1141 } 1142 1143 // Tests that setting the transaction pool gas price to a higher value correctly 1144 // discards everything cheaper than that and moves any gapped transactions back 1145 // from the pending pool to the queue. 1146 // 1147 // Note, local transactions are never allowed to be dropped. 1148 func TestTransactionPoolRepricing(t *testing.T) { 1149 t.Parallel() 1150 1151 // Create the pool to test the pricing enforcement with 1152 db := rawdb.NewMemoryDatabase() 1153 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1154 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1155 1156 pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain, nil) 1157 defer pool.Stop() 1158 1159 // Keep track of transaction events to ensure all executables get announced 1160 events := make(chan TxPreEvent, 32) 1161 sub := pool.txFeed.Subscribe(events) 1162 defer sub.Unsubscribe() 1163 1164 // Create a number of test accounts and fund them 1165 keys := make([]*ecdsa.PrivateKey, 4) 1166 for i := 0; i < len(keys); i++ { 1167 keys[i], _ = crypto.GenerateKey() 1168 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) 1169 } 1170 // Generate and queue a batch of transactions, both pending and queued 1171 txs := types.Transactions{} 1172 1173 txs = append(txs, pricedTransaction(0, 100000, big.NewInt(2), keys[0])) 1174 txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[0])) 1175 txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[0])) 1176 1177 txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) 1178 txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[1])) 1179 txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[1])) 1180 1181 txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[2])) 1182 txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) 1183 txs = append(txs, pricedTransaction(3, 100000, big.NewInt(2), keys[2])) 1184 1185 ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[3]) 1186 1187 // Import the batch and that both pending and queued transactions match up 1188 pool.AddRemotes(txs) 1189 pool.AddLocal(ltx) 1190 1191 pending, queued := pool.Stats() 1192 if pending != 7 { 1193 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 7) 1194 } 1195 if queued != 3 { 1196 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3) 1197 } 1198 if err := validateEvents(events, 7); err != nil { 1199 t.Fatalf("original event firing failed: %v", err) 1200 } 1201 if err := validateTxPoolInternals(pool); err != nil { 1202 t.Fatalf("pool internal state corrupted: %v", err) 1203 } 1204 // Reprice the pool and check that underpriced transactions get dropped 1205 pool.SetGasPrice(big.NewInt(2)) 1206 1207 pending, queued = pool.Stats() 1208 if pending != 2 { 1209 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) 1210 } 1211 if queued != 5 { 1212 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 5) 1213 } 1214 if err := validateEvents(events, 0); err != nil { 1215 t.Fatalf("reprice event firing failed: %v", err) 1216 } 1217 if err := validateTxPoolInternals(pool); err != nil { 1218 t.Fatalf("pool internal state corrupted: %v", err) 1219 } 1220 // Check that we can't add the old transactions back 1221 if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), keys[0])); err != ErrUnderpriced { 1222 t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced) 1223 } 1224 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced { 1225 t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced) 1226 } 1227 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), keys[2])); err != ErrUnderpriced { 1228 t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced) 1229 } 1230 if err := validateEvents(events, 0); err != nil { 1231 t.Fatalf("post-reprice event firing failed: %v", err) 1232 } 1233 if err := validateTxPoolInternals(pool); err != nil { 1234 t.Fatalf("pool internal state corrupted: %v", err) 1235 } 1236 // However we can add local underpriced transactions 1237 tx := pricedTransaction(1, 100000, big.NewInt(1), keys[3]) 1238 if err := pool.AddLocal(tx); err != nil { 1239 t.Fatalf("failed to add underpriced local transaction: %v", err) 1240 } 1241 if pending, _ = pool.Stats(); pending != 3 { 1242 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) 1243 } 1244 if err := validateEvents(events, 1); err != nil { 1245 t.Fatalf("post-reprice local event firing failed: %v", err) 1246 } 1247 if err := validateTxPoolInternals(pool); err != nil { 1248 t.Fatalf("pool internal state corrupted: %v", err) 1249 } 1250 // And we can fill gaps with properly priced transactions 1251 if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(2), keys[0])); err != nil { 1252 t.Fatalf("failed to add pending transaction: %v", err) 1253 } 1254 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), keys[1])); err != nil { 1255 t.Fatalf("failed to add pending transaction: %v", err) 1256 } 1257 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), keys[2])); err != nil { 1258 t.Fatalf("failed to add queued transaction: %v", err) 1259 } 1260 if err := validateEvents(events, 5); err != nil { 1261 t.Fatalf("post-reprice event firing failed: %v", err) 1262 } 1263 if err := validateTxPoolInternals(pool); err != nil { 1264 t.Fatalf("pool internal state corrupted: %v", err) 1265 } 1266 } 1267 1268 // Tests that setting the transaction pool gas price to a higher value does not 1269 // remove local transactions. 1270 func TestTransactionPoolRepricingKeepsLocals(t *testing.T) { 1271 t.Parallel() 1272 1273 // Create the pool to test the pricing enforcement with 1274 db := rawdb.NewMemoryDatabase() 1275 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1276 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1277 1278 pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain, nil) 1279 defer pool.Stop() 1280 1281 // Create a number of test accounts and fund them 1282 keys := make([]*ecdsa.PrivateKey, 3) 1283 for i := 0; i < len(keys); i++ { 1284 keys[i], _ = crypto.GenerateKey() 1285 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000*1000000)) 1286 } 1287 // Create transaction (both pending and queued) with a linearly growing gasprice 1288 for i := uint64(0); i < 500; i++ { 1289 // Add pending 1290 p_tx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2]) 1291 if err := pool.AddLocal(p_tx); err != nil { 1292 t.Fatal(err) 1293 } 1294 // Add queued 1295 q_tx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2]) 1296 if err := pool.AddLocal(q_tx); err != nil { 1297 t.Fatal(err) 1298 } 1299 } 1300 pending, queued := pool.Stats() 1301 expPending, expQueued := 500, 500 1302 validate := func() { 1303 pending, queued = pool.Stats() 1304 if pending != expPending { 1305 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, expPending) 1306 } 1307 if queued != expQueued { 1308 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, expQueued) 1309 } 1310 1311 if err := validateTxPoolInternals(pool); err != nil { 1312 t.Fatalf("pool internal state corrupted: %v", err) 1313 } 1314 } 1315 validate() 1316 1317 // Reprice the pool and check that nothing is dropped 1318 pool.SetGasPrice(big.NewInt(2)) 1319 validate() 1320 1321 pool.SetGasPrice(big.NewInt(2)) 1322 pool.SetGasPrice(big.NewInt(4)) 1323 pool.SetGasPrice(big.NewInt(8)) 1324 pool.SetGasPrice(big.NewInt(100)) 1325 validate() 1326 } 1327 1328 // Tests that when the pool reaches its global transaction limit, underpriced 1329 // transactions are gradually shifted out for more expensive ones and any gapped 1330 // pending transactions are moved into the queue. 1331 // 1332 // Note, local transactions are never allowed to be dropped. 1333 func TestTransactionPoolUnderpricing(t *testing.T) { 1334 t.Parallel() 1335 1336 // Create the pool to test the pricing enforcement with 1337 db := rawdb.NewMemoryDatabase() 1338 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1339 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1340 1341 config := testTxPoolConfig 1342 config.GlobalSlots = 2 1343 config.GlobalQueue = 2 1344 1345 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 1346 defer pool.Stop() 1347 1348 // Keep track of transaction events to ensure all executables get announced 1349 events := make(chan TxPreEvent, 32) 1350 sub := pool.txFeed.Subscribe(events) 1351 defer sub.Unsubscribe() 1352 1353 // Create a number of test accounts and fund them 1354 keys := make([]*ecdsa.PrivateKey, 3) 1355 for i := 0; i < len(keys); i++ { 1356 keys[i], _ = crypto.GenerateKey() 1357 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) 1358 } 1359 // Generate and queue a batch of transactions, both pending and queued 1360 txs := types.Transactions{} 1361 1362 txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) 1363 txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[0])) 1364 1365 txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[1])) 1366 1367 ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[2]) 1368 1369 // Import the batch and that both pending and queued transactions match up 1370 pool.AddRemotes(txs) 1371 pool.AddLocal(ltx) 1372 1373 pending, queued := pool.Stats() 1374 if pending != 3 { 1375 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) 1376 } 1377 if queued != 1 { 1378 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) 1379 } 1380 if err := validateEvents(events, 3); err != nil { 1381 t.Fatalf("original event firing failed: %v", err) 1382 } 1383 if err := validateTxPoolInternals(pool); err != nil { 1384 t.Fatalf("pool internal state corrupted: %v", err) 1385 } 1386 // Ensure that adding an underpriced transaction on block limit fails 1387 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced { 1388 t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced) 1389 } 1390 // Ensure that adding high priced transactions drops cheap ones, but not own 1391 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil { 1392 t.Fatalf("failed to add well priced transaction: %v", err) 1393 } 1394 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(4), keys[1])); err != nil { 1395 t.Fatalf("failed to add well priced transaction: %v", err) 1396 } 1397 if err := pool.AddRemote(pricedTransaction(3, 100000, big.NewInt(5), keys[1])); err != nil { 1398 t.Fatalf("failed to add well priced transaction: %v", err) 1399 } 1400 pending, queued = pool.Stats() 1401 if pending != 2 { 1402 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) 1403 } 1404 if queued != 2 { 1405 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) 1406 } 1407 if err := validateEvents(events, 2); err != nil { 1408 t.Fatalf("additional event firing failed: %v", err) 1409 } 1410 if err := validateTxPoolInternals(pool); err != nil { 1411 t.Fatalf("pool internal state corrupted: %v", err) 1412 } 1413 // Ensure that adding local transactions can push out even higher priced ones 1414 tx := pricedTransaction(1, 100000, big.NewInt(0), keys[2]) 1415 if err := pool.AddLocal(tx); err != nil { 1416 t.Fatalf("failed to add underpriced local transaction: %v", err) 1417 } 1418 pending, queued = pool.Stats() 1419 if pending != 2 { 1420 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) 1421 } 1422 if queued != 2 { 1423 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) 1424 } 1425 if err := validateEvents(events, 1); err != nil { 1426 t.Fatalf("local event firing failed: %v", err) 1427 } 1428 if err := validateTxPoolInternals(pool); err != nil { 1429 t.Fatalf("pool internal state corrupted: %v", err) 1430 } 1431 } 1432 1433 // Tests that the pool rejects replacement transactions that don't meet the minimum 1434 // price bump required. 1435 func TestTransactionReplacement(t *testing.T) { 1436 t.Parallel() 1437 1438 // Create the pool to test the pricing enforcement with 1439 db := rawdb.NewMemoryDatabase() 1440 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1441 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1442 1443 pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain, nil) 1444 defer pool.Stop() 1445 1446 // Keep track of transaction events to ensure all executables get announced 1447 events := make(chan TxPreEvent, 32) 1448 sub := pool.txFeed.Subscribe(events) 1449 defer sub.Unsubscribe() 1450 1451 // Create a test account to add transactions with 1452 key, _ := crypto.GenerateKey() 1453 pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000)) 1454 1455 // Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too) 1456 price := int64(100) 1457 threshold := (price * (100 + int64(testTxPoolConfig.PriceBump))) / 100 1458 1459 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), key)); err != nil { 1460 t.Fatalf("failed to add original cheap pending transaction: %v", err) 1461 } 1462 if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced { 1463 t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) 1464 } 1465 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), key)); err != nil { 1466 t.Fatalf("failed to replace original cheap pending transaction: %v", err) 1467 } 1468 if err := validateEvents(events, 2); err != nil { 1469 t.Fatalf("cheap replacement event firing failed: %v", err) 1470 } 1471 1472 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(price), key)); err != nil { 1473 t.Fatalf("failed to add original proper pending transaction: %v", err) 1474 } 1475 if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced { 1476 t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) 1477 } 1478 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(threshold), key)); err != nil { 1479 t.Fatalf("failed to replace original proper pending transaction: %v", err) 1480 } 1481 if err := validateEvents(events, 2); err != nil { 1482 t.Fatalf("proper replacement event firing failed: %v", err) 1483 } 1484 // Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too) 1485 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), key)); err != nil { 1486 t.Fatalf("failed to add original cheap queued transaction: %v", err) 1487 } 1488 if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced { 1489 t.Fatalf("original cheap queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) 1490 } 1491 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), key)); err != nil { 1492 t.Fatalf("failed to replace original cheap queued transaction: %v", err) 1493 } 1494 1495 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(price), key)); err != nil { 1496 t.Fatalf("failed to add original proper queued transaction: %v", err) 1497 } 1498 if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced { 1499 t.Fatalf("original proper queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) 1500 } 1501 if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(threshold), key)); err != nil { 1502 t.Fatalf("failed to replace original proper queued transaction: %v", err) 1503 } 1504 1505 if err := validateEvents(events, 0); err != nil { 1506 t.Fatalf("queued replacement event firing failed: %v", err) 1507 } 1508 if err := validateTxPoolInternals(pool); err != nil { 1509 t.Fatalf("pool internal state corrupted: %v", err) 1510 } 1511 } 1512 1513 // Tests that local transactions are journaled to disk, but remote transactions 1514 // get discarded between restarts. 1515 func TestTransactionJournaling(t *testing.T) { testTransactionJournaling(t, false) } 1516 func TestTransactionJournalingNoLocals(t *testing.T) { testTransactionJournaling(t, true) } 1517 1518 func testTransactionJournaling(t *testing.T, nolocals bool) { 1519 t.Parallel() 1520 1521 // Create a temporary file for the journal 1522 file, err := ioutil.TempFile("", "") 1523 if err != nil { 1524 t.Fatalf("failed to create temporary journal: %v", err) 1525 } 1526 journal := file.Name() 1527 defer os.Remove(journal) 1528 1529 // Clean up the temporary file, we only need the path for now 1530 file.Close() 1531 os.Remove(journal) 1532 1533 // Create the original pool to inject transaction into the journal 1534 db := rawdb.NewMemoryDatabase() 1535 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1536 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1537 1538 config := testTxPoolConfig 1539 config.NoLocals = nolocals 1540 config.Journal = journal 1541 config.Rejournal = time.Second 1542 1543 pool := NewTxPool(config, params.TestChainConfig, blockchain, nil) 1544 1545 // Create two test accounts to ensure remotes expire but locals do not 1546 local, _ := crypto.GenerateKey() 1547 remote, _ := crypto.GenerateKey() 1548 1549 pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000)) 1550 pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000)) 1551 1552 // Add three local and a remote transactions and ensure they are queued up 1553 if err := pool.AddLocal(pricedTransaction(0, 100000, big.NewInt(1), local)); err != nil { 1554 t.Fatalf("failed to add local transaction: %v", err) 1555 } 1556 if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil { 1557 t.Fatalf("failed to add local transaction: %v", err) 1558 } 1559 if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil { 1560 t.Fatalf("failed to add local transaction: %v", err) 1561 } 1562 if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), remote)); err != nil { 1563 t.Fatalf("failed to add remote transaction: %v", err) 1564 } 1565 pending, queued := pool.Stats() 1566 if pending != 4 { 1567 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4) 1568 } 1569 if queued != 0 { 1570 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) 1571 } 1572 if err := validateTxPoolInternals(pool); err != nil { 1573 t.Fatalf("pool internal state corrupted: %v", err) 1574 } 1575 // Terminate the old pool, bump the local nonce, create a new pool and ensure relevant transaction survive 1576 pool.Stop() 1577 statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1) 1578 blockchain = &testBlockChain{statedb, 1000000, new(event.Feed)} 1579 1580 pool = NewTxPool(config, params.TestChainConfig, blockchain, nil) 1581 1582 pending, queued = pool.Stats() 1583 if queued != 0 { 1584 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) 1585 } 1586 if nolocals { 1587 if pending != 0 { 1588 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) 1589 } 1590 } else { 1591 if pending != 2 { 1592 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) 1593 } 1594 } 1595 if err := validateTxPoolInternals(pool); err != nil { 1596 t.Fatalf("pool internal state corrupted: %v", err) 1597 } 1598 // Bump the nonce temporarily and ensure the newly invalidated transaction is removed 1599 statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2) 1600 pool.lockedReset(nil, nil) 1601 time.Sleep(2 * config.Rejournal) 1602 pool.Stop() 1603 1604 statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1) 1605 blockchain = &testBlockChain{statedb, 1000000, new(event.Feed)} 1606 pool = NewTxPool(config, params.TestChainConfig, blockchain, nil) 1607 1608 pending, queued = pool.Stats() 1609 if pending != 0 { 1610 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) 1611 } 1612 if nolocals { 1613 if queued != 0 { 1614 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) 1615 } 1616 } else { 1617 if queued != 1 { 1618 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) 1619 } 1620 } 1621 if err := validateTxPoolInternals(pool); err != nil { 1622 t.Fatalf("pool internal state corrupted: %v", err) 1623 } 1624 pool.Stop() 1625 } 1626 1627 // TestTransactionStatusCheck tests that the pool can correctly retrieve the 1628 // pending status of individual transactions. 1629 func TestTransactionStatusCheck(t *testing.T) { 1630 t.Parallel() 1631 1632 // Create the pool to test the status retrievals with 1633 db := rawdb.NewMemoryDatabase() 1634 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 1635 blockchain := &testBlockChain{statedb, 1000000, new(event.Feed)} 1636 1637 pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain, nil) 1638 defer pool.Stop() 1639 1640 // Create the test accounts to check various transaction statuses with 1641 keys := make([]*ecdsa.PrivateKey, 3) 1642 for i := 0; i < len(keys); i++ { 1643 keys[i], _ = crypto.GenerateKey() 1644 pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) 1645 } 1646 // Generate and queue a batch of transactions, both pending and queued 1647 txs := types.Transactions{} 1648 1649 txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) // Pending only 1650 txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) // Pending and queued 1651 txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[1])) 1652 txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) // Queued only 1653 1654 // Import the transaction and ensure they are correctly added 1655 pool.AddRemotes(txs) 1656 1657 pending, queued := pool.Stats() 1658 if pending != 2 { 1659 t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) 1660 } 1661 if queued != 2 { 1662 t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) 1663 } 1664 if err := validateTxPoolInternals(pool); err != nil { 1665 t.Fatalf("pool internal state corrupted: %v", err) 1666 } 1667 // Retrieve the status of each transaction and validate them 1668 hashes := make([]common.Hash, len(txs)) 1669 for i, tx := range txs { 1670 hashes[i] = tx.Hash() 1671 } 1672 hashes = append(hashes, common.Hash{}) 1673 1674 statuses := pool.Status(hashes) 1675 expect := []TxStatus{TxStatusPending, TxStatusPending, TxStatusQueued, TxStatusQueued, TxStatusUnknown} 1676 1677 for i := 0; i < len(statuses); i++ { 1678 if statuses[i] != expect[i] { 1679 t.Errorf("transaction %d: status mismatch: have %v, want %v", i, statuses[i], expect[i]) 1680 } 1681 } 1682 } 1683 1684 // Benchmarks the speed of validating the contents of the pending queue of the 1685 // transaction pool. 1686 func BenchmarkPendingDemotion100(b *testing.B) { benchmarkPendingDemotion(b, 100) } 1687 func BenchmarkPendingDemotion1000(b *testing.B) { benchmarkPendingDemotion(b, 1000) } 1688 func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) } 1689 1690 func benchmarkPendingDemotion(b *testing.B, size int) { 1691 // Add a batch of transactions to a pool one by one 1692 pool, key := setupTxPool() 1693 defer pool.Stop() 1694 1695 account, _ := deriveSender(transaction(0, 0, key)) 1696 pool.currentState.AddBalance(account, big.NewInt(1000000)) 1697 1698 for i := 0; i < size; i++ { 1699 tx := transaction(uint64(i), 100000, key) 1700 pool.promoteTx(account, tx.Hash(), tx) 1701 } 1702 // Benchmark the speed of pool validation 1703 b.ResetTimer() 1704 for i := 0; i < b.N; i++ { 1705 pool.demoteUnexecutables() 1706 } 1707 } 1708 1709 // Benchmarks the speed of scheduling the contents of the future queue of the 1710 // transaction pool. 1711 func BenchmarkFuturePromotion100(b *testing.B) { benchmarkFuturePromotion(b, 100) } 1712 func BenchmarkFuturePromotion1000(b *testing.B) { benchmarkFuturePromotion(b, 1000) } 1713 func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) } 1714 1715 func benchmarkFuturePromotion(b *testing.B, size int) { 1716 // Add a batch of transactions to a pool one by one 1717 pool, key := setupTxPool() 1718 defer pool.Stop() 1719 1720 account, _ := deriveSender(transaction(0, 0, key)) 1721 pool.currentState.AddBalance(account, big.NewInt(1000000)) 1722 1723 for i := 0; i < size; i++ { 1724 tx := transaction(uint64(1+i), 100000, key) 1725 pool.enqueueTx(tx.Hash(), tx) 1726 } 1727 // Benchmark the speed of pool validation 1728 b.ResetTimer() 1729 for i := 0; i < b.N; i++ { 1730 pool.promoteExecutables(nil) 1731 } 1732 } 1733 1734 // Benchmarks the speed of iterative transaction insertion. 1735 func BenchmarkPoolInsert(b *testing.B) { 1736 // Generate a batch of transactions to enqueue into the pool 1737 pool, key := setupTxPool() 1738 defer pool.Stop() 1739 1740 account, _ := deriveSender(transaction(0, 0, key)) 1741 pool.currentState.AddBalance(account, big.NewInt(1000000)) 1742 1743 txs := make(types.Transactions, b.N) 1744 for i := 0; i < b.N; i++ { 1745 txs[i] = transaction(uint64(i), 100000, key) 1746 } 1747 // Benchmark importing the transactions into the queue 1748 b.ResetTimer() 1749 for _, tx := range txs { 1750 pool.AddRemote(tx) 1751 } 1752 } 1753 1754 // Benchmarks the speed of batched transaction insertion. 1755 func BenchmarkPoolBatchInsert100(b *testing.B) { benchmarkPoolBatchInsert(b, 100) } 1756 func BenchmarkPoolBatchInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000) } 1757 func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000) } 1758 1759 func benchmarkPoolBatchInsert(b *testing.B, size int) { 1760 // Generate a batch of transactions to enqueue into the pool 1761 pool, key := setupTxPool() 1762 defer pool.Stop() 1763 1764 account, _ := deriveSender(transaction(0, 0, key)) 1765 pool.currentState.AddBalance(account, big.NewInt(1000000)) 1766 1767 batches := make([]types.Transactions, b.N) 1768 for i := 0; i < b.N; i++ { 1769 batches[i] = make(types.Transactions, size) 1770 for j := 0; j < size; j++ { 1771 batches[i][j] = transaction(uint64(size*i+j), 100000, key) 1772 } 1773 } 1774 // Benchmark importing the transactions into the queue 1775 b.ResetTimer() 1776 for _, batch := range batches { 1777 pool.AddRemotes(batch) 1778 } 1779 }