tx_pool_test.go 41.2 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2015 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU Lesser General Public License for more details.
//
// 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/>.
F
Felix Lange 已提交
16

17 18 19 20
package core

import (
	"crypto/ecdsa"
21
	"math/big"
22
	"math/rand"
23
	"testing"
24
	"time"
25

F
Felix Lange 已提交
26
	"github.com/ethereum/go-ethereum/common"
27
	"github.com/ethereum/go-ethereum/core/state"
28 29
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
O
obscuren 已提交
30
	"github.com/ethereum/go-ethereum/ethdb"
31
	"github.com/ethereum/go-ethereum/event"
32
	"github.com/ethereum/go-ethereum/params"
33 34
)

35
func transaction(nonce uint64, gaslimit *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
36 37 38 39 40
	return pricedTransaction(nonce, gaslimit, big.NewInt(1), key)
}

func pricedTransaction(nonce uint64, gaslimit, gasprice *big.Int, key *ecdsa.PrivateKey) *types.Transaction {
	tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, gasprice, nil), types.HomesteadSigner{}, key)
41
	return tx
42 43
}

O
obscuren 已提交
44 45
func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
	db, _ := ethdb.NewMemDatabase()
46
	statedb, _ := state.New(common.Hash{}, db)
O
obscuren 已提交
47

48
	key, _ := crypto.GenerateKey()
F
Felix Lange 已提交
49
	newPool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
50
	newPool.resetState()
51

52
	return newPool, key
53 54
}

J
Jeffrey Wilcke 已提交
55 56 57 58
func deriveSender(tx *types.Transaction) (common.Address, error) {
	return types.Sender(types.HomesteadSigner{}, tx)
}

59 60 61 62 63 64 65 66 67 68 69 70 71 72
// This test simulates a scenario where a new block is imported during a
// state reset and tests whether the pending state is in sync with the
// block head event that initiated the resetState().
func TestStateChangeDuringPoolReset(t *testing.T) {
	var (
		db, _      = ethdb.NewMemDatabase()
		key, _     = crypto.GenerateKey()
		address    = crypto.PubkeyToAddress(key.PublicKey)
		mux        = new(event.TypeMux)
		statedb, _ = state.New(common.Hash{}, db)
		trigger    = false
	)

	// setup pool with 2 transaction in it
73
	statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

	tx0 := transaction(0, big.NewInt(100000), key)
	tx1 := transaction(1, big.NewInt(100000), key)

	// stateFunc is used multiple times to reset the pending state.
	// when simulate is true it will create a state that indicates
	// that tx0 and tx1 are included in the chain.
	stateFunc := func() (*state.StateDB, error) {
		// delay "state change" by one. The tx pool fetches the
		// state multiple times and by delaying it a bit we simulate
		// a state change between those fetches.
		stdb := statedb
		if trigger {
			statedb, _ = state.New(common.Hash{}, db)
			// simulate that the new head block included tx0 and tx1
			statedb.SetNonce(address, 2)
90
			statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
91 92 93 94 95 96 97
			trigger = false
		}
		return stdb, nil
	}

	gasLimitFunc := func() *big.Int { return big.NewInt(1000000000) }

F
Felix Lange 已提交
98
	txpool := NewTxPool(params.TestChainConfig, mux, stateFunc, gasLimitFunc)
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
	txpool.resetState()

	nonce := txpool.State().GetNonce(address)
	if nonce != 0 {
		t.Fatalf("Invalid nonce, want 0, got %d", nonce)
	}

	txpool.AddBatch(types.Transactions{tx0, tx1})

	nonce = txpool.State().GetNonce(address)
	if nonce != 2 {
		t.Fatalf("Invalid nonce, want 2, got %d", nonce)
	}

	// trigger state change in the background
	trigger = true

	txpool.resetState()

	pendingTx, err := txpool.Pending()
	if err != nil {
		t.Fatalf("Could not fetch pending transactions: %v", err)
	}

	for addr, txs := range pendingTx {
		t.Logf("%0x: %d\n", addr, len(txs))
	}

	nonce = txpool.State().GetNonce(address)
	if nonce != 2 {
		t.Fatalf("Invalid nonce, want 2, got %d", nonce)
	}
}

O
obscuren 已提交
133 134
func TestInvalidTransactions(t *testing.T) {
	pool, key := setupTxPool()
135

136
	tx := transaction(0, big.NewInt(100), key)
J
Jeffrey Wilcke 已提交
137
	from, _ := deriveSender(tx)
138 139
	currentState, _ := pool.currentState()
	currentState.AddBalance(from, big.NewInt(1))
140
	if err := pool.Add(tx); err != ErrInsufficientFunds {
O
obscuren 已提交
141
		t.Error("expected", ErrInsufficientFunds)
142 143
	}

144
	balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice()))
145
	currentState.AddBalance(from, balance)
146
	if err := pool.Add(tx); err != ErrIntrinsicGas {
147
		t.Error("expected", ErrIntrinsicGas, "got", err)
148
	}
O
obscuren 已提交
149

150 151
	currentState.SetNonce(from, 1)
	currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
152 153
	tx = transaction(0, big.NewInt(100000), key)
	if err := pool.Add(tx); err != ErrNonce {
154 155
		t.Error("expected", ErrNonce)
	}
156 157

	tx = transaction(1, big.NewInt(100000), key)
158 159 160
	pool.gasPrice = big.NewInt(1000)
	if err := pool.Add(tx); err != ErrUnderpriced {
		t.Error("expected", ErrUnderpriced, "got", err)
161 162 163 164 165 166
	}

	pool.SetLocal(tx)
	if err := pool.Add(tx); err != nil {
		t.Error("expected", nil, "got", err)
	}
167 168 169 170
}

func TestTransactionQueue(t *testing.T) {
	pool, key := setupTxPool()
171
	tx := transaction(0, big.NewInt(100), key)
J
Jeffrey Wilcke 已提交
172
	from, _ := deriveSender(tx)
173
	currentState, _ := pool.currentState()
174
	currentState.AddBalance(from, big.NewInt(1000))
175
	pool.resetState()
176
	pool.enqueueTx(tx.Hash(), tx)
177

178
	pool.promoteExecutables(currentState)
O
obscuren 已提交
179 180
	if len(pool.pending) != 1 {
		t.Error("expected valid txs to be 1 is", len(pool.pending))
181 182
	}

183
	tx = transaction(1, big.NewInt(100), key)
J
Jeffrey Wilcke 已提交
184
	from, _ = deriveSender(tx)
185
	currentState.SetNonce(from, 2)
186
	pool.enqueueTx(tx.Hash(), tx)
187
	pool.promoteExecutables(currentState)
188
	if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok {
189 190 191
		t.Error("expected transaction to be in tx pool")
	}

192 193
	if len(pool.queue) > 0 {
		t.Error("expected transaction queue to be empty. is", len(pool.queue))
194 195 196
	}

	pool, key = setupTxPool()
197 198 199
	tx1 := transaction(0, big.NewInt(100), key)
	tx2 := transaction(10, big.NewInt(100), key)
	tx3 := transaction(11, big.NewInt(100), key)
J
Jeffrey Wilcke 已提交
200
	from, _ = deriveSender(tx1)
201 202
	currentState, _ = pool.currentState()
	currentState.AddBalance(from, big.NewInt(1000))
203 204
	pool.resetState()

205 206 207
	pool.enqueueTx(tx1.Hash(), tx1)
	pool.enqueueTx(tx2.Hash(), tx2)
	pool.enqueueTx(tx3.Hash(), tx3)
208

209
	pool.promoteExecutables(currentState)
210

O
obscuren 已提交
211
	if len(pool.pending) != 1 {
212
		t.Error("expected tx pool to be 1, got", len(pool.pending))
213
	}
214 215
	if pool.queue[from].Len() != 2 {
		t.Error("expected len(queue) == 2, got", pool.queue[from].Len())
216 217
	}
}
218 219 220

func TestRemoveTx(t *testing.T) {
	pool, key := setupTxPool()
221
	tx := transaction(0, big.NewInt(100), key)
J
Jeffrey Wilcke 已提交
222
	from, _ := deriveSender(tx)
223 224
	currentState, _ := pool.currentState()
	currentState.AddBalance(from, big.NewInt(1))
225 226 227

	pool.enqueueTx(tx.Hash(), tx)
	pool.promoteTx(from, tx.Hash(), tx)
228 229 230
	if len(pool.queue) != 1 {
		t.Error("expected queue to be 1, got", len(pool.queue))
	}
O
obscuren 已提交
231
	if len(pool.pending) != 1 {
232
		t.Error("expected pending to be 1, got", len(pool.pending))
233
	}
234
	pool.Remove(tx.Hash())
235 236 237
	if len(pool.queue) > 0 {
		t.Error("expected queue to be 0, got", len(pool.queue))
	}
O
obscuren 已提交
238
	if len(pool.pending) > 0 {
239
		t.Error("expected pending to be 0, got", len(pool.pending))
240 241
	}
}
242 243 244 245

func TestNegativeValue(t *testing.T) {
	pool, key := setupTxPool()

246
	tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(-1), big.NewInt(100), big.NewInt(1), nil), types.HomesteadSigner{}, key)
J
Jeffrey Wilcke 已提交
247
	from, _ := deriveSender(tx)
248 249
	currentState, _ := pool.currentState()
	currentState.AddBalance(from, big.NewInt(1))
250
	if err := pool.Add(tx); err != ErrNegativeValue {
251 252 253
		t.Error("expected", ErrNegativeValue, "got", err)
	}
}
254 255 256 257

func TestTransactionChainFork(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
258 259
	resetState := func() {
		db, _ := ethdb.NewMemDatabase()
260 261 262 263
		statedb, _ := state.New(common.Hash{}, db)
		pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
		currentState, _ := pool.currentState()
		currentState.AddBalance(addr, big.NewInt(100000000000000))
264 265 266 267
		pool.resetState()
	}
	resetState()

268
	tx := transaction(0, big.NewInt(100000), key)
269
	if _, err := pool.add(tx); err != nil {
270 271
		t.Error("didn't expect error", err)
	}
272
	pool.RemoveBatch([]*types.Transaction{tx})
273 274

	// reset the pool's internal state
275
	resetState()
276
	if _, err := pool.add(tx); err != nil {
277 278 279 280 281 282 283
		t.Error("didn't expect error", err)
	}
}

func TestTransactionDoubleNonce(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
284 285
	resetState := func() {
		db, _ := ethdb.NewMemDatabase()
286 287 288 289
		statedb, _ := state.New(common.Hash{}, db)
		pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
		currentState, _ := pool.currentState()
		currentState.AddBalance(addr, big.NewInt(100000000000000))
290 291 292 293
		pool.resetState()
	}
	resetState()

J
Jeffrey Wilcke 已提交
294
	signer := types.HomesteadSigner{}
295 296 297
	tx1, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(100000), big.NewInt(1), nil), signer, key)
	tx2, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(1000000), big.NewInt(2), nil), signer, key)
	tx3, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), big.NewInt(1000000), big.NewInt(1), nil), signer, key)
298 299

	// Add the first two transaction, ensure higher priced stays only
300 301
	if replace, err := pool.add(tx1); err != nil || replace {
		t.Errorf("first transaction insert failed (%v) or reported replacement (%v)", err, replace)
302
	}
303 304
	if replace, err := pool.add(tx2); err != nil || !replace {
		t.Errorf("second transaction insert failed (%v) or not reported replacement (%v)", err, replace)
305
	}
306 307
	state, _ := pool.currentState()
	pool.promoteExecutables(state)
308 309
	if pool.pending[addr].Len() != 1 {
		t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
310
	}
311
	if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
312 313 314
		t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
	}
	// Add the thid transaction and ensure it's not saved (smaller price)
315
	pool.add(tx3)
316
	pool.promoteExecutables(state)
317 318
	if pool.pending[addr].Len() != 1 {
		t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
319
	}
320
	if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
321 322 323 324 325
		t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
	}
	// Ensure the total transaction count is correct
	if len(pool.all) != 1 {
		t.Error("expected 1 total transactions, got", len(pool.all))
326 327
	}
}
O
obscuren 已提交
328 329 330 331

func TestMissingNonce(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
332 333
	currentState, _ := pool.currentState()
	currentState.AddBalance(addr, big.NewInt(100000000000000))
334
	tx := transaction(1, big.NewInt(100000), key)
335
	if _, err := pool.add(tx); err != nil {
O
obscuren 已提交
336 337
		t.Error("didn't expect error", err)
	}
338 339
	if len(pool.pending) != 0 {
		t.Error("expected 0 pending transactions, got", len(pool.pending))
O
obscuren 已提交
340
	}
341 342
	if pool.queue[addr].Len() != 1 {
		t.Error("expected 1 queued transaction, got", pool.queue[addr].Len())
O
obscuren 已提交
343
	}
344 345 346
	if len(pool.all) != 1 {
		t.Error("expected 1 total transactions, got", len(pool.all))
	}
O
obscuren 已提交
347
}
348 349 350 351 352

func TestNonceRecovery(t *testing.T) {
	const n = 10
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
353 354 355
	currentState, _ := pool.currentState()
	currentState.SetNonce(addr, n)
	currentState.AddBalance(addr, big.NewInt(100000000000000))
356 357 358 359 360 361
	pool.resetState()
	tx := transaction(n, big.NewInt(100000), key)
	if err := pool.Add(tx); err != nil {
		t.Error(err)
	}
	// simulate some weird re-order of transactions and missing nonce(s)
362
	currentState.SetNonce(addr, n-1)
363 364 365 366 367
	pool.resetState()
	if fn := pool.pendingState.GetNonce(addr); fn != n+1 {
		t.Errorf("expected nonce to be %d, got %d", n+1, fn)
	}
}
368 369 370 371

func TestRemovedTxEvent(t *testing.T) {
	pool, key := setupTxPool()
	tx := transaction(0, big.NewInt(1000000), key)
J
Jeffrey Wilcke 已提交
372
	from, _ := deriveSender(tx)
373 374
	currentState, _ := pool.currentState()
	currentState.AddBalance(from, big.NewInt(1000000000000))
375
	pool.resetState()
376 377
	pool.eventMux.Post(RemovedTransactionEvent{types.Transactions{tx}})
	pool.eventMux.Post(ChainHeadEvent{nil})
378 379
	if pool.pending[from].Len() != 1 {
		t.Error("expected 1 pending tx, got", pool.pending[from].Len())
380 381 382
	}
	if len(pool.all) != 1 {
		t.Error("expected 1 total transactions, got", len(pool.all))
383 384
	}
}
385 386 387 388 389 390

// Tests that if an account runs out of funds, any pending and queued transactions
// are dropped.
func TestTransactionDropping(t *testing.T) {
	// Create a test account and fund it
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
391
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
392 393 394 395 396 397 398 399 400 401 402

	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000))

	// Add some pending and some queued transactions
	var (
		tx0  = transaction(0, big.NewInt(100), key)
		tx1  = transaction(1, big.NewInt(200), key)
		tx10 = transaction(10, big.NewInt(100), key)
		tx11 = transaction(11, big.NewInt(200), key)
	)
403 404 405 406
	pool.promoteTx(account, tx0.Hash(), tx0)
	pool.promoteTx(account, tx1.Hash(), tx1)
	pool.enqueueTx(tx10.Hash(), tx10)
	pool.enqueueTx(tx11.Hash(), tx11)
407 408

	// Check that pre and post validations leave the pool as is
409 410
	if pool.pending[account].Len() != 2 {
		t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 2)
411
	}
412 413
	if pool.queue[account].Len() != 2 {
		t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 2)
414 415 416
	}
	if len(pool.all) != 4 {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 4)
417 418
	}
	pool.resetState()
419 420
	if pool.pending[account].Len() != 2 {
		t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 2)
421
	}
422 423
	if pool.queue[account].Len() != 2 {
		t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 2)
424 425 426
	}
	if len(pool.all) != 4 {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 4)
427 428 429 430 431
	}
	// Reduce the balance of the account, and check that invalidated transactions are dropped
	state.AddBalance(account, big.NewInt(-750))
	pool.resetState()

432
	if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
433 434
		t.Errorf("funded pending transaction missing: %v", tx0)
	}
435
	if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok {
436 437
		t.Errorf("out-of-fund pending transaction present: %v", tx1)
	}
438
	if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
439 440
		t.Errorf("funded queued transaction missing: %v", tx10)
	}
441
	if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok {
442 443
		t.Errorf("out-of-fund queued transaction present: %v", tx11)
	}
444 445 446
	if len(pool.all) != 2 {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), 2)
	}
447 448 449 450
}

// Tests that if a transaction is dropped from the current pending pool (e.g. out
// of fund), all consecutive (still valid, but not executable) transactions are
L
Leif Jurvetson 已提交
451
// postponed back into the future queue to prevent broadcasting them.
452 453 454
func TestTransactionPostponing(t *testing.T) {
	// Create a test account and fund it
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
455
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
456 457 458 459 460 461 462 463 464 465 466 467 468

	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000))

	// Add a batch consecutive pending transactions for validation
	txns := []*types.Transaction{}
	for i := 0; i < 100; i++ {
		var tx *types.Transaction
		if i%2 == 0 {
			tx = transaction(uint64(i), big.NewInt(100), key)
		} else {
			tx = transaction(uint64(i), big.NewInt(500), key)
		}
469
		pool.promoteTx(account, tx.Hash(), tx)
470 471 472
		txns = append(txns, tx)
	}
	// Check that pre and post validations leave the pool as is
473 474
	if pool.pending[account].Len() != len(txns) {
		t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), len(txns))
475
	}
476 477
	if len(pool.queue) != 0 {
		t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 0)
478 479 480
	}
	if len(pool.all) != len(txns) {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns))
481 482
	}
	pool.resetState()
483 484
	if pool.pending[account].Len() != len(txns) {
		t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), len(txns))
485
	}
486 487
	if len(pool.queue) != 0 {
		t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 0)
488 489 490
	}
	if len(pool.all) != len(txns) {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns))
491
	}
492
	// Reduce the balance of the account, and check that transactions are reorganised
493 494 495
	state.AddBalance(account, big.NewInt(-750))
	pool.resetState()

496
	if _, ok := pool.pending[account].txs.items[txns[0].Nonce()]; !ok {
497 498
		t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txns[0])
	}
499
	if _, ok := pool.queue[account].txs.items[txns[0].Nonce()]; ok {
500 501 502 503
		t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txns[0])
	}
	for i, tx := range txns[1:] {
		if i%2 == 1 {
504
			if _, ok := pool.pending[account].txs.items[tx.Nonce()]; ok {
505 506
				t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx)
			}
507
			if _, ok := pool.queue[account].txs.items[tx.Nonce()]; !ok {
508 509 510
				t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx)
			}
		} else {
511
			if _, ok := pool.pending[account].txs.items[tx.Nonce()]; ok {
512 513
				t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx)
			}
514
			if _, ok := pool.queue[account].txs.items[tx.Nonce()]; ok {
515 516 517 518
				t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx)
			}
		}
	}
519 520 521
	if len(pool.all) != len(txns)/2 {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), len(txns)/2)
	}
522 523 524 525
}

// Tests that if the transaction count belonging to a single account goes above
// some threshold, the higher transactions are dropped to prevent DOS attacks.
526
func TestTransactionQueueAccountLimiting(t *testing.T) {
527 528
	// Create a test account and fund it
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
529
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
530 531 532

	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))
533
	pool.resetState()
534 535

	// Keep queuing up transactions and make sure all above a limit are dropped
536
	for i := uint64(1); i <= maxQueuedPerAccount+5; i++ {
537 538 539 540 541 542
		if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
		}
		if len(pool.pending) != 0 {
			t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0)
		}
543
		if i <= maxQueuedPerAccount {
544 545
			if pool.queue[account].Len() != int(i) {
				t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i)
546 547
			}
		} else {
548 549
			if pool.queue[account].Len() != int(maxQueuedPerAccount) {
				t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), maxQueuedPerAccount)
550 551 552
			}
		}
	}
553 554 555 556 557 558 559 560 561
	if len(pool.all) != int(maxQueuedPerAccount) {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), maxQueuedPerAccount)
	}
}

// Tests that if the transaction count belonging to multiple accounts go above
// some threshold, the higher transactions are dropped to prevent DOS attacks.
func TestTransactionQueueGlobalLimiting(t *testing.T) {
	// Reduce the queue limits to shorten test time
562 563
	defer func(old uint64) { maxQueuedTotal = old }(maxQueuedTotal)
	maxQueuedTotal = maxQueuedPerAccount * 3
564 565 566 567 568

	// Create the pool to test the limit enforcement with
	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)

F
Felix Lange 已提交
569
	pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
570 571 572 573 574 575 576 577 578 579 580 581 582
	pool.resetState()

	// Create a number of test accounts and fund them
	state, _ := pool.currentState()

	keys := make([]*ecdsa.PrivateKey, 5)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
		state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
	}
	// Generate and queue a batch of transactions
	nonces := make(map[common.Address]uint64)

583
	txs := make(types.Transactions, 0, 3*maxQueuedTotal)
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
	for len(txs) < cap(txs) {
		key := keys[rand.Intn(len(keys))]
		addr := crypto.PubkeyToAddress(key.PublicKey)

		txs = append(txs, transaction(nonces[addr]+1, big.NewInt(100000), key))
		nonces[addr]++
	}
	// Import the batch and verify that limits have been enforced
	pool.AddBatch(txs)

	queued := 0
	for addr, list := range pool.queue {
		if list.Len() > int(maxQueuedPerAccount) {
			t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), maxQueuedPerAccount)
		}
		queued += list.Len()
	}
601 602
	if queued > int(maxQueuedTotal) {
		t.Fatalf("total transactions overflow allowance: %d > %d", queued, maxQueuedTotal)
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
	}
}

// Tests that if an account remains idle for a prolonged amount of time, any
// non-executable transactions queued up are dropped to prevent wasting resources
// on shuffling them around.
func TestTransactionQueueTimeLimiting(t *testing.T) {
	// Reduce the queue limits to shorten test time
	defer func(old time.Duration) { maxQueuedLifetime = old }(maxQueuedLifetime)
	defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
	maxQueuedLifetime = time.Second
	evictionInterval = time.Second

	// Create a test account and fund it
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
618
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
619 620 621 622 623 624 625 626 627 628 629 630 631 632

	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))

	// Queue up a batch of transactions
	for i := uint64(1); i <= maxQueuedPerAccount; i++ {
		if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
		}
	}
	// Wait until at least two expiration cycles hit and make sure the transactions are gone
	time.Sleep(2 * evictionInterval)
	if len(pool.queue) > 0 {
		t.Fatalf("old transactions remained after eviction")
633
	}
634 635 636 637 638 639 640 641
}

// Tests that even if the transaction count belonging to a single account goes
// above some threshold, as long as the transactions are executable, they are
// accepted.
func TestTransactionPendingLimiting(t *testing.T) {
	// Create a test account and fund it
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
642
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
643 644 645

	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))
646
	pool.resetState()
647 648

	// Keep queuing up transactions and make sure all above a limit are dropped
649
	for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
650 651 652
		if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
		}
653 654
		if pool.pending[account].Len() != int(i)+1 {
			t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1)
655
		}
656 657
		if len(pool.queue) != 0 {
			t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
658 659
		}
	}
660 661
	if len(pool.all) != int(maxQueuedPerAccount+5) {
		t.Errorf("total transaction mismatch: have %d, want %d", len(pool.all), maxQueuedPerAccount+5)
662
	}
663 664 665 666 667 668 669 670 671 672
}

// Tests that the transaction limits are enforced the same way irrelevant whether
// the transactions are added one by one or in batches.
func TestTransactionQueueLimitingEquivalency(t *testing.T)   { testTransactionLimitingEquivalency(t, 1) }
func TestTransactionPendingLimitingEquivalency(t *testing.T) { testTransactionLimitingEquivalency(t, 0) }

func testTransactionLimitingEquivalency(t *testing.T, origin uint64) {
	// Add a batch of transactions to a pool one by one
	pool1, key1 := setupTxPool()
J
Jeffrey Wilcke 已提交
673
	account1, _ := deriveSender(transaction(0, big.NewInt(0), key1))
674 675 676
	state1, _ := pool1.currentState()
	state1.AddBalance(account1, big.NewInt(1000000))

677
	for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
678 679 680 681
		if err := pool1.Add(transaction(origin+i, big.NewInt(100000), key1)); err != nil {
			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
		}
	}
682
	// Add a batch of transactions to a pool in one big batch
683
	pool2, key2 := setupTxPool()
J
Jeffrey Wilcke 已提交
684
	account2, _ := deriveSender(transaction(0, big.NewInt(0), key2))
685 686 687 688
	state2, _ := pool2.currentState()
	state2.AddBalance(account2, big.NewInt(1000000))

	txns := []*types.Transaction{}
689
	for i := uint64(0); i < maxQueuedPerAccount+5; i++ {
690 691
		txns = append(txns, transaction(origin+i, big.NewInt(100000), key2))
	}
692
	pool2.AddBatch(txns)
693 694 695 696 697

	// Ensure the batch optimization honors the same pool mechanics
	if len(pool1.pending) != len(pool2.pending) {
		t.Errorf("pending transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.pending), len(pool2.pending))
	}
698 699
	if len(pool1.queue) != len(pool2.queue) {
		t.Errorf("queued transaction count mismatch: one-by-one algo: %d, batch algo: %d", len(pool1.queue), len(pool2.queue))
700
	}
701 702 703
	if len(pool1.all) != len(pool2.all) {
		t.Errorf("total transaction count mismatch: one-by-one algo %d, batch algo %d", len(pool1.all), len(pool2.all))
	}
704 705
}

706 707 708 709 710 711 712 713 714 715 716 717
// Tests that if the transaction count belonging to multiple accounts go above
// some hard threshold, the higher transactions are dropped to prevent DOS
// attacks.
func TestTransactionPendingGlobalLimiting(t *testing.T) {
	// Reduce the queue limits to shorten test time
	defer func(old uint64) { maxPendingTotal = old }(maxPendingTotal)
	maxPendingTotal = minPendingPerAccount * 10

	// Create the pool to test the limit enforcement with
	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)

F
Felix Lange 已提交
718
	pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
	pool.resetState()

	// Create a number of test accounts and fund them
	state, _ := pool.currentState()

	keys := make([]*ecdsa.PrivateKey, 5)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
		state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
	}
	// Generate and queue a batch of transactions
	nonces := make(map[common.Address]uint64)

	txs := types.Transactions{}
	for _, key := range keys {
		addr := crypto.PubkeyToAddress(key.PublicKey)
		for j := 0; j < int(maxPendingTotal)/len(keys)*2; j++ {
			txs = append(txs, transaction(nonces[addr], big.NewInt(100000), key))
			nonces[addr]++
		}
	}
	// Import the batch and verify that limits have been enforced
	pool.AddBatch(txs)

	pending := 0
	for _, list := range pool.pending {
		pending += list.Len()
	}
	if pending > int(maxPendingTotal) {
		t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, maxPendingTotal)
	}
}

// Tests that if the transaction count belonging to multiple accounts go above
// some hard threshold, if they are under the minimum guaranteed slot count then
// the transactions are still kept.
func TestTransactionPendingMinimumAllowance(t *testing.T) {
	// Reduce the queue limits to shorten test time
	defer func(old uint64) { maxPendingTotal = old }(maxPendingTotal)
	maxPendingTotal = 0

	// Create the pool to test the limit enforcement with
	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)

F
Felix Lange 已提交
764
	pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
	pool.resetState()

	// Create a number of test accounts and fund them
	state, _ := pool.currentState()

	keys := make([]*ecdsa.PrivateKey, 5)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
		state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
	}
	// Generate and queue a batch of transactions
	nonces := make(map[common.Address]uint64)

	txs := types.Transactions{}
	for _, key := range keys {
		addr := crypto.PubkeyToAddress(key.PublicKey)
		for j := 0; j < int(minPendingPerAccount)*2; j++ {
			txs = append(txs, transaction(nonces[addr], big.NewInt(100000), key))
			nonces[addr]++
		}
	}
	// Import the batch and verify that limits have been enforced
	pool.AddBatch(txs)

	for addr, list := range pool.pending {
		if list.Len() != int(minPendingPerAccount) {
			t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), minPendingPerAccount)
		}
	}
}

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
// Tests that setting the transaction pool gas price to a higher value correctly
// discards everything cheaper than that and moves any gapped transactions back
// from the pending pool to the queue.
//
// Note, local transactions are never allowed to be dropped.
func TestTransactionPoolRepricing(t *testing.T) {
	// Create the pool to test the pricing enforcement with
	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)

	pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
	pool.resetState()

	// Create a number of test accounts and fund them
	state, _ := pool.currentState()

	keys := make([]*ecdsa.PrivateKey, 3)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
		state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
	}
	// Generate and queue a batch of transactions, both pending and queued
	txs := types.Transactions{}

	txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(2), keys[0]))
	txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[0]))
	txs = append(txs, pricedTransaction(2, big.NewInt(100000), big.NewInt(2), keys[0]))

	txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(2), keys[1]))
	txs = append(txs, pricedTransaction(2, big.NewInt(100000), big.NewInt(1), keys[1]))
	txs = append(txs, pricedTransaction(3, big.NewInt(100000), big.NewInt(2), keys[1]))

	txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[2]))
	pool.SetLocal(txs[len(txs)-1]) // prevent this one from ever being dropped

	// Import the batch and that both pending and queued transactions match up
	pool.AddBatch(txs)

	pending, queued := pool.stats()
	if pending != 4 {
		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4)
	}
	if queued != 3 {
		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
	}
	// Reprice the pool and check that underpriced transactions get dropped
	pool.SetGasPrice(big.NewInt(2))

	pending, queued = pool.stats()
	if pending != 2 {
		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
	}
	if queued != 3 {
		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
	}
	// Check that we can't add the old transactions back
	if err := pool.Add(pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[0])); err != ErrUnderpriced {
		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
	}
	if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(1), keys[1])); err != ErrUnderpriced {
		t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
	}
	// However we can add local underpriced transactions
	tx := pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[2])

	pool.SetLocal(tx) // prevent this one from ever being dropped
	if err := pool.Add(tx); err != nil {
		t.Fatalf("failed to add underpriced local transaction: %v", err)
	}
	if pending, _ = pool.stats(); pending != 3 {
		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
	}
}

// Tests that when the pool reaches its global transaction limit, underpriced
// transactions are gradually shifted out for more expensive ones and any gapped
// pending transactions are moved into te queue.
//
// Note, local transactions are never allowed to be dropped.
func TestTransactionPoolUnderpricing(t *testing.T) {
	// Reduce the queue limits to shorten test time
	defer func(old uint64) { maxPendingTotal = old }(maxPendingTotal)
	maxPendingTotal = 2

	defer func(old uint64) { maxQueuedTotal = old }(maxQueuedTotal)
	maxQueuedTotal = 2

	// Create the pool to test the pricing enforcement with
	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)

	pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
	pool.resetState()

	// Create a number of test accounts and fund them
	state, _ := pool.currentState()

	keys := make([]*ecdsa.PrivateKey, 3)
	for i := 0; i < len(keys); i++ {
		keys[i], _ = crypto.GenerateKey()
		state.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
	}
	// Generate and queue a batch of transactions, both pending and queued
	txs := types.Transactions{}

	txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[0]))
	txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(2), keys[0]))

	txs = append(txs, pricedTransaction(1, big.NewInt(100000), big.NewInt(1), keys[1]))

	txs = append(txs, pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[2]))
	pool.SetLocal(txs[len(txs)-1]) // prevent this one from ever being dropped

	// Import the batch and that both pending and queued transactions match up
	pool.AddBatch(txs)

	pending, queued := pool.stats()
	if pending != 3 {
		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
	}
	if queued != 1 {
		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
	}
	// Ensure that adding an underpriced transaction on block limit fails
	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(1), keys[1])); err != ErrUnderpriced {
		t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
	}
	// Ensure that adding high priced transactions drops cheap ones, but not own
	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(3), keys[1])); err != nil {
		t.Fatalf("failed to add well priced transaction: %v", err)
	}
	if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(4), keys[1])); err != nil {
		t.Fatalf("failed to add well priced transaction: %v", err)
	}
	if err := pool.Add(pricedTransaction(3, big.NewInt(100000), big.NewInt(5), keys[1])); err != nil {
		t.Fatalf("failed to add well priced transaction: %v", err)
	}
	pending, queued = pool.stats()
	if pending != 2 {
		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
	}
	if queued != 2 {
		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
	}
	// Ensure that adding local transactions can push out even higher priced ones
	tx := pricedTransaction(1, big.NewInt(100000), big.NewInt(0), keys[2])

	pool.SetLocal(tx) // prevent this one from ever being dropped
	if err := pool.Add(tx); err != nil {
		t.Fatalf("failed to add underpriced local transaction: %v", err)
	}
	pending, queued = pool.stats()
	if pending != 2 {
		t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
	}
	if queued != 2 {
		t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
	}
}

// Tests that the pool rejects replacement transactions that don't meet the minimum
// price bump required.
func TestTransactionReplacement(t *testing.T) {
	// Create the pool to test the pricing enforcement with
	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)

	pool := NewTxPool(params.TestChainConfig, new(event.TypeMux), func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
	pool.resetState()

	// Create a a test account to add transactions with
	key, _ := crypto.GenerateKey()

	state, _ := pool.currentState()
	state.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000))

	// Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
	price := int64(100)
	threshold := (price * (100 + minPriceBumpPercent)) / 100

	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(1), key)); err != nil {
		t.Fatalf("failed to add original cheap pending transaction: %v", err)
	}
	if err := pool.Add(pricedTransaction(0, big.NewInt(100001), big.NewInt(1), key)); err != ErrReplaceUnderpriced {
		t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
	}
	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(2), key)); err != nil {
		t.Fatalf("failed to replace original cheap pending transaction: %v", err)
	}

	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(price), key)); err != nil {
		t.Fatalf("failed to add original proper pending transaction: %v", err)
	}
	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(threshold), key)); err != ErrReplaceUnderpriced {
		t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
	}
	if err := pool.Add(pricedTransaction(0, big.NewInt(100000), big.NewInt(threshold+1), key)); err != nil {
		t.Fatalf("failed to replace original proper pending transaction: %v", err)
	}
	// Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too)
	if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(1), key)); err != nil {
		t.Fatalf("failed to add original queued transaction: %v", err)
	}
	if err := pool.Add(pricedTransaction(2, big.NewInt(100001), big.NewInt(1), key)); err != ErrReplaceUnderpriced {
		t.Fatalf("original queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
	}
	if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(2), key)); err != nil {
		t.Fatalf("failed to replace original queued transaction: %v", err)
	}

	if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(price), key)); err != nil {
		t.Fatalf("failed to add original queued transaction: %v", err)
	}
	if err := pool.Add(pricedTransaction(2, big.NewInt(100001), big.NewInt(threshold), key)); err != ErrReplaceUnderpriced {
		t.Fatalf("original queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced)
	}
	if err := pool.Add(pricedTransaction(2, big.NewInt(100000), big.NewInt(threshold+1), key)); err != nil {
		t.Fatalf("failed to replace original queued transaction: %v", err)
	}
}

1017 1018
// Benchmarks the speed of validating the contents of the pending queue of the
// transaction pool.
1019 1020 1021
func BenchmarkPendingDemotion100(b *testing.B)   { benchmarkPendingDemotion(b, 100) }
func BenchmarkPendingDemotion1000(b *testing.B)  { benchmarkPendingDemotion(b, 1000) }
func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) }
1022

1023
func benchmarkPendingDemotion(b *testing.B, size int) {
1024 1025
	// Add a batch of transactions to a pool one by one
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
1026
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
1027 1028 1029 1030 1031
	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))

	for i := 0; i < size; i++ {
		tx := transaction(uint64(i), big.NewInt(100000), key)
1032
		pool.promoteTx(account, tx.Hash(), tx)
1033 1034 1035 1036
	}
	// Benchmark the speed of pool validation
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
1037
		pool.demoteUnexecutables(state)
1038 1039 1040 1041 1042
	}
}

// Benchmarks the speed of scheduling the contents of the future queue of the
// transaction pool.
1043 1044 1045
func BenchmarkFuturePromotion100(b *testing.B)   { benchmarkFuturePromotion(b, 100) }
func BenchmarkFuturePromotion1000(b *testing.B)  { benchmarkFuturePromotion(b, 1000) }
func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) }
1046

1047
func benchmarkFuturePromotion(b *testing.B, size int) {
1048 1049
	// Add a batch of transactions to a pool one by one
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
1050
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
1051 1052 1053 1054 1055
	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))

	for i := 0; i < size; i++ {
		tx := transaction(uint64(1+i), big.NewInt(100000), key)
1056
		pool.enqueueTx(tx.Hash(), tx)
1057 1058 1059 1060
	}
	// Benchmark the speed of pool validation
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
1061
		pool.promoteExecutables(state)
1062 1063 1064 1065 1066 1067 1068
	}
}

// Benchmarks the speed of iterative transaction insertion.
func BenchmarkPoolInsert(b *testing.B) {
	// Generate a batch of transactions to enqueue into the pool
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
1069
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))

	txs := make(types.Transactions, b.N)
	for i := 0; i < b.N; i++ {
		txs[i] = transaction(uint64(i), big.NewInt(100000), key)
	}
	// Benchmark importing the transactions into the queue
	b.ResetTimer()
	for _, tx := range txs {
		pool.Add(tx)
	}
}

// Benchmarks the speed of batched transaction insertion.
func BenchmarkPoolBatchInsert100(b *testing.B)   { benchmarkPoolBatchInsert(b, 100) }
func BenchmarkPoolBatchInsert1000(b *testing.B)  { benchmarkPoolBatchInsert(b, 1000) }
func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000) }

func benchmarkPoolBatchInsert(b *testing.B, size int) {
	// Generate a batch of transactions to enqueue into the pool
	pool, key := setupTxPool()
J
Jeffrey Wilcke 已提交
1092
	account, _ := deriveSender(transaction(0, big.NewInt(0), key))
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))

	batches := make([]types.Transactions, b.N)
	for i := 0; i < b.N; i++ {
		batches[i] = make(types.Transactions, size)
		for j := 0; j < size; j++ {
			batches[i][j] = transaction(uint64(size*i+j), big.NewInt(100000), key)
		}
	}
	// Benchmark importing the transactions into the queue
	b.ResetTimer()
	for _, batch := range batches {
		pool.AddBatch(batch)
1107 1108
	}
}