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