aboutsummaryrefslogtreecommitdiffstats
path: root/core/tx_pool_test.go
blob: 70d4a351ab0ef92042c66d2b3041fa428a66e1bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
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
764
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
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// 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.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package core

import (
    "crypto/ecdsa"
    "fmt"
    "io/ioutil"
    "math/big"
    "math/rand"
    "os"
    "testing"
    "time"

    "github.com/dexon-foundation/dexon/common"
    "github.com/dexon-foundation/dexon/core/state"
    "github.com/dexon-foundation/dexon/core/types"
    "github.com/dexon-foundation/dexon/crypto"
    "github.com/dexon-foundation/dexon/ethdb"
    "github.com/dexon-foundation/dexon/event"
    "github.com/dexon-foundation/dexon/params"
)

// testTxPoolConfig is a transaction pool configuration without stateful disk
// sideeffects used during testing.
var testTxPoolConfig TxPoolConfig

func init() {
    testTxPoolConfig = DefaultTxPoolConfig
    testTxPoolConfig.Journal = ""
}

type testBlockChain struct {
    statedb            *state.StateDB
    gasLimit           uint64
    chainHeadFeed      *event.Feed
    blockConfirmedFeed *event.Feed
}

func (bc *testBlockChain) CurrentBlock() *types.Block {
    return types.NewBlock(&types.Header{
        GasLimit: bc.gasLimit,
    }, nil, nil, nil)
}

func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
    return bc.CurrentBlock()
}

func (bc *testBlockChain) GetBlockByNumber(uint64) *types.Block {
    return bc.CurrentBlock()
}

func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) {
    return bc.statedb, nil
}

func (bc *testBlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
    return bc.chainHeadFeed.Subscribe(ch)
}

func transaction(nonce uint64, gaslimit uint64, key *ecdsa.PrivateKey) *types.Transaction {
    return pricedTransaction(nonce, gaslimit, big.NewInt(1), key)
}

func pricedTransaction(nonce uint64, gaslimit uint64, 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)
    return tx
}

func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    key, _ := crypto.GenerateKey()
    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)

    return pool, key
}

// validateTxPoolInternals checks various consistency invariants within the pool.
func validateTxPoolInternals(pool *TxPool) error {
    pool.mu.RLock()
    defer pool.mu.RUnlock()

    // Ensure the total transaction set is consistent with pending + queued
    pending, queued := pool.stats()
    if total := pool.all.Count(); total != pending+queued {
        return fmt.Errorf("total transaction count %d != %d pending + %d queued", total, pending, queued)
    }
    if priced := pool.priced.items.Len() - pool.priced.stales; priced != pending+queued {
        return fmt.Errorf("total priced transaction count %d != %d pending + %d queued", priced, pending, queued)
    }
    // Ensure the next nonce to assign is the correct one
    for addr, txs := range pool.pending {
        // Find the last transaction
        var last uint64
        for nonce := range txs.txs.items {
            if last < nonce {
                last = nonce
            }
        }
        if nonce := pool.pendingState.GetNonce(addr); nonce != last+1 {
            return fmt.Errorf("pending nonce mismatch: have %v, want %v", nonce, last+1)
        }
    }
    return nil
}

// validateEvents checks that the correct number of transaction addition events
// were fired on the pool's event feed.
func validateEvents(events chan NewTxsEvent, count int) error {
    var received []*types.Transaction

    for len(received) < count {
        select {
        case ev := <-events:
            received = append(received, ev.Txs...)
        case <-time.After(time.Second):
            return fmt.Errorf("event #%d not fired", received)
        }
    }
    if len(received) > count {
        return fmt.Errorf("more than %d events fired: %v", count, received[count:])
    }
    select {
    case ev := <-events:
        return fmt.Errorf("more than %d events fired: %v", count, ev.Txs)

    case <-time.After(50 * time.Millisecond):
        // This branch should be "default", but it's a data race between goroutines,
        // reading the event channel and pushing into it, so better wait a bit ensuring
        // really nothing gets injected.
    }
    return nil
}

func deriveSender(tx *types.Transaction) (common.Address, error) {
    return types.Sender(types.HomesteadSigner{}, tx)
}

type testChain struct {
    *testBlockChain
    address common.Address
    trigger *bool
}

// testChain.State() 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.
func (c *testChain) State() (*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 := c.statedb
    if *c.trigger {
        c.statedb, _ = state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
        // simulate that the new head block included tx0 and tx1
        c.statedb.SetNonce(c.address, 2)
        c.statedb.SetBalance(c.address, new(big.Int).SetUint64(params.Ether))
        *c.trigger = false
    }
    return stdb, nil
}

// 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 TestStateChangeDuringTransactionPoolReset(t *testing.T) {
    t.Parallel()

    var (
        key, _     = crypto.GenerateKey()
        address    = crypto.PubkeyToAddress(key.PublicKey)
        statedb, _ = state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
        trigger    = false
    )

    // setup pool with 2 transaction in it
    statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether))
    blockchain := &testChain{&testBlockChain{statedb, 1000000000, new(event.Feed), new(event.Feed)}, address, &trigger}

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

    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    defer pool.Stop()

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

    pool.AddRemotes(types.Transactions{tx0, tx1})

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

    // trigger state change in the background
    trigger = true

    pool.lockedReset(nil, nil)

    _, err := pool.Pending()
    if err != nil {
        t.Fatalf("Could not fetch pending transactions: %v", err)
    }
    nonce = pool.State().GetNonce(address)
    if nonce != 2 {
        t.Fatalf("Invalid nonce, want 2, got %d", nonce)
    }
}

func TestInvalidTransactions(t *testing.T) {
    t.Parallel()

    pool, key := setupTxPool()
    defer pool.Stop()

    tx := transaction(0, 100, key)
    from, _ := deriveSender(tx)

    pool.currentState.AddBalance(from, big.NewInt(1))
    if err := pool.AddRemote(tx); err != ErrInsufficientFunds {
        t.Error("expected", ErrInsufficientFunds)
    }

    balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(new(big.Int).SetUint64(tx.Gas()), tx.GasPrice()))
    pool.currentState.AddBalance(from, balance)
    if err := pool.AddRemote(tx); err != ErrIntrinsicGas {
        t.Error("expected", ErrIntrinsicGas, "got", err)
    }

    pool.currentState.SetNonce(from, 1)
    pool.currentState.AddBalance(from, big.NewInt(0xffffffffffffff))
    tx = transaction(0, 100000, key)
    if err := pool.AddRemote(tx); err != ErrNonceTooLow {
        t.Error("expected", ErrNonceTooLow)
    }

    tx = transaction(1, 100000, key)
    pool.gasPrice = big.NewInt(1000)
    if err := pool.AddRemote(tx); err != ErrUnderpriced {
        t.Error("expected", ErrUnderpriced, "got", err)
    }
    if err := pool.AddLocal(tx); err != nil {
        t.Error("expected", nil, "got", err)
    }
}

func TestTransactionQueue(t *testing.T) {
    t.Parallel()

    pool, key := setupTxPool()
    defer pool.Stop()

    tx := transaction(0, 100, key)
    from, _ := deriveSender(tx)
    pool.currentState.AddBalance(from, big.NewInt(1000))
    pool.lockedReset(nil, nil)
    pool.enqueueTx(tx.Hash(), tx)

    pool.promoteExecutables([]common.Address{from})
    if len(pool.pending) != 1 {
        t.Error("expected valid txs to be 1 is", len(pool.pending))
    }

    tx = transaction(1, 100, key)
    from, _ = deriveSender(tx)
    pool.currentState.SetNonce(from, 2)
    pool.enqueueTx(tx.Hash(), tx)
    pool.promoteExecutables([]common.Address{from})
    if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok {
        t.Error("expected transaction to be in tx pool")
    }

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

    pool, key = setupTxPool()
    defer pool.Stop()

    tx1 := transaction(0, 100, key)
    tx2 := transaction(10, 100, key)
    tx3 := transaction(11, 100, key)
    from, _ = deriveSender(tx1)
    pool.currentState.AddBalance(from, big.NewInt(1000))
    pool.lockedReset(nil, nil)

    pool.enqueueTx(tx1.Hash(), tx1)
    pool.enqueueTx(tx2.Hash(), tx2)
    pool.enqueueTx(tx3.Hash(), tx3)

    pool.promoteExecutables([]common.Address{from})

    if len(pool.pending) != 1 {
        t.Error("expected tx pool to be 1, got", len(pool.pending))
    }
    if pool.queue[from].Len() != 2 {
        t.Error("expected len(queue) == 2, got", pool.queue[from].Len())
    }
}

func TestTransactionNegativeValue(t *testing.T) {
    t.Parallel()

    pool, key := setupTxPool()
    defer pool.Stop()

    tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(-1), 100, big.NewInt(1), nil), types.HomesteadSigner{}, key)
    from, _ := deriveSender(tx)
    pool.currentState.AddBalance(from, big.NewInt(1))
    if err := pool.AddRemote(tx); err != ErrNegativeValue {
        t.Error("expected", ErrNegativeValue, "got", err)
    }
}

func TestTransactionChainFork(t *testing.T) {
    t.Parallel()

    pool, key := setupTxPool()
    defer pool.Stop()

    addr := crypto.PubkeyToAddress(key.PublicKey)
    resetState := func() {
        statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
        statedb.AddBalance(addr, big.NewInt(100000000000000))

        pool.chain = &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}
        pool.lockedReset(nil, nil)
    }
    resetState()

    tx := transaction(0, 100000, key)
    if _, err := pool.add(tx, false); err != nil {
        t.Error("didn't expect error", err)
    }
    pool.removeTx(tx.Hash(), true)

    // reset the pool's internal state
    resetState()
    if _, err := pool.add(tx, false); err != nil {
        t.Error("didn't expect error", err)
    }
}

func TestTransactionDoubleNonce(t *testing.T) {
    t.Parallel()

    pool, key := setupTxPool()
    defer pool.Stop()

    addr := crypto.PubkeyToAddress(key.PublicKey)
    resetState := func() {
        statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
        statedb.AddBalance(addr, big.NewInt(100000000000000))

        pool.chain = &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}
        pool.lockedReset(nil, nil)
    }
    resetState()

    signer := types.HomesteadSigner{}
    tx1, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100000, big.NewInt(1), nil), signer, key)
    tx2, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(2), nil), signer, key)
    tx3, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(1), nil), signer, key)

    // Add the first two transaction, ensure higher priced stays only
    if replace, err := pool.add(tx1, false); err != nil || replace {
        t.Errorf("first transaction insert failed (%v) or reported replacement (%v)", err, replace)
    }
    if replace, err := pool.add(tx2, false); err != nil || !replace {
        t.Errorf("second transaction insert failed (%v) or not reported replacement (%v)", err, replace)
    }
    pool.promoteExecutables([]common.Address{addr})
    if pool.pending[addr].Len() != 1 {
        t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
    }
    if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
        t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
    }
    // Add the third transaction and ensure it's not saved (smaller price)
    pool.add(tx3, false)
    pool.promoteExecutables([]common.Address{addr})
    if pool.pending[addr].Len() != 1 {
        t.Error("expected 1 pending transactions, got", pool.pending[addr].Len())
    }
    if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() {
        t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash())
    }
    // Ensure the total transaction count is correct
    if pool.all.Count() != 1 {
        t.Error("expected 1 total transactions, got", pool.all.Count())
    }
}

func TestTransactionMissingNonce(t *testing.T) {
    t.Parallel()

    pool, key := setupTxPool()
    defer pool.Stop()

    addr := crypto.PubkeyToAddress(key.PublicKey)
    pool.currentState.AddBalance(addr, big.NewInt(100000000000000))
    tx := transaction(1, 100000, key)
    if _, err := pool.add(tx, false); err != nil {
        t.Error("didn't expect error", err)
    }
    if len(pool.pending) != 0 {
        t.Error("expected 0 pending transactions, got", len(pool.pending))
    }
    if pool.queue[addr].Len() != 1 {
        t.Error("expected 1 queued transaction, got", pool.queue[addr].Len())
    }
    if pool.all.Count() != 1 {
        t.Error("expected 1 total transactions, got", pool.all.Count())
    }
}

func TestTransactionNonceRecovery(t *testing.T) {
    t.Parallel()

    const n = 10
    pool, key := setupTxPool()
    defer pool.Stop()

    addr := crypto.PubkeyToAddress(key.PublicKey)
    pool.currentState.SetNonce(addr, n)
    pool.currentState.AddBalance(addr, big.NewInt(100000000000000))
    pool.lockedReset(nil, nil)

    tx := transaction(n, 100000, key)
    if err := pool.AddRemote(tx); err != nil {
        t.Error(err)
    }
    // simulate some weird re-order of transactions and missing nonce(s)
    pool.currentState.SetNonce(addr, n-1)
    pool.lockedReset(nil, nil)
    if fn := pool.pendingState.GetNonce(addr); fn != n-1 {
        t.Errorf("expected nonce to be %d, got %d", n-1, fn)
    }
}

// Tests that if an account runs out of funds, any pending and queued transactions
// are dropped.
func TestTransactionDropping(t *testing.T) {
    t.Parallel()

    // Create a test account and fund it
    pool, key := setupTxPool()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000))

    // Add some pending and some queued transactions
    var (
        tx0  = transaction(0, 100, key)
        tx1  = transaction(1, 200, key)
        tx2  = transaction(2, 300, key)
        tx10 = transaction(10, 100, key)
        tx11 = transaction(11, 200, key)
        tx12 = transaction(12, 300, key)
    )
    pool.promoteTx(account, tx0.Hash(), tx0)
    pool.promoteTx(account, tx1.Hash(), tx1)
    pool.promoteTx(account, tx2.Hash(), tx2)
    pool.enqueueTx(tx10.Hash(), tx10)
    pool.enqueueTx(tx11.Hash(), tx11)
    pool.enqueueTx(tx12.Hash(), tx12)

    // Check that pre and post validations leave the pool as is
    if pool.pending[account].Len() != 3 {
        t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3)
    }
    if pool.queue[account].Len() != 3 {
        t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3)
    }
    if pool.all.Count() != 6 {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6)
    }
    pool.lockedReset(nil, nil)
    if pool.pending[account].Len() != 3 {
        t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3)
    }
    if pool.queue[account].Len() != 3 {
        t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3)
    }
    if pool.all.Count() != 6 {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6)
    }
    // Reduce the balance of the account, and check that invalidated transactions are dropped
    pool.currentState.AddBalance(account, big.NewInt(-650))
    pool.lockedReset(nil, nil)

    if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
        t.Errorf("funded pending transaction missing: %v", tx0)
    }
    if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; !ok {
        t.Errorf("funded pending transaction missing: %v", tx0)
    }
    if _, ok := pool.pending[account].txs.items[tx2.Nonce()]; ok {
        t.Errorf("out-of-fund pending transaction present: %v", tx1)
    }
    if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
        t.Errorf("funded queued transaction missing: %v", tx10)
    }
    if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; !ok {
        t.Errorf("funded queued transaction missing: %v", tx10)
    }
    if _, ok := pool.queue[account].txs.items[tx12.Nonce()]; ok {
        t.Errorf("out-of-fund queued transaction present: %v", tx11)
    }
    if pool.all.Count() != 4 {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 4)
    }
    // Reduce the block gas limit, check that invalidated transactions are dropped
    pool.chain.(*testBlockChain).gasLimit = 100
    pool.lockedReset(nil, nil)

    if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok {
        t.Errorf("funded pending transaction missing: %v", tx0)
    }
    if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok {
        t.Errorf("over-gased pending transaction present: %v", tx1)
    }
    if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok {
        t.Errorf("funded queued transaction missing: %v", tx10)
    }
    if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok {
        t.Errorf("over-gased queued transaction present: %v", tx11)
    }
    if pool.all.Count() != 2 {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 2)
    }
}

// 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
// postponed back into the future queue to prevent broadcasting them.
func TestTransactionPostponing(t *testing.T) {
    t.Parallel()

    // Create the pool to test the postponing with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create two test accounts to produce different gap profiles with
    keys := make([]*ecdsa.PrivateKey, 2)
    accs := make([]common.Address, len(keys))

    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        accs[i] = crypto.PubkeyToAddress(keys[i].PublicKey)

        pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(50100))
    }
    // Add a batch consecutive pending transactions for validation
    txs := []*types.Transaction{}
    for i, key := range keys {

        for j := 0; j < 100; j++ {
            var tx *types.Transaction
            if (i+j)%2 == 0 {
                tx = transaction(uint64(j), 25000, key)
            } else {
                tx = transaction(uint64(j), 50000, key)
            }
            txs = append(txs, tx)
        }
    }
    for i, err := range pool.AddRemotes(txs) {
        if err != nil {
            t.Fatalf("tx %d: failed to add transactions: %v", i, err)
        }
    }
    // Check that pre and post validations leave the pool as is
    if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) {
        t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs))
    }
    if len(pool.queue) != 0 {
        t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0)
    }
    if pool.all.Count() != len(txs) {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs))
    }
    pool.lockedReset(nil, nil)
    if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) {
        t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs))
    }
    if len(pool.queue) != 0 {
        t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0)
    }
    if pool.all.Count() != len(txs) {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs))
    }
    // Reduce the balance of the account, and check that transactions are reorganised
    for _, addr := range accs {
        pool.currentState.AddBalance(addr, big.NewInt(-1))
    }
    pool.lockedReset(nil, nil)

    // The first account's first transaction remains valid, check that subsequent
    // ones are either filtered out, or queued up for later.
    if _, ok := pool.pending[accs[0]].txs.items[txs[0].Nonce()]; !ok {
        t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txs[0])
    }
    if _, ok := pool.queue[accs[0]].txs.items[txs[0].Nonce()]; ok {
        t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txs[0])
    }
    for i, tx := range txs[1:100] {
        if i%2 == 1 {
            if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok {
                t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx)
            }
            if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; !ok {
                t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx)
            }
        } else {
            if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok {
                t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx)
            }
            if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; ok {
                t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx)
            }
        }
    }
    // The second account's first transaction got invalid, check that all transactions
    // are either filtered out, or queued up for later.
    if pool.pending[accs[1]] != nil {
        t.Errorf("invalidated account still has pending transactions")
    }
    for i, tx := range txs[100:] {
        if i%2 == 1 {
            if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; !ok {
                t.Errorf("tx %d: valid but future transaction missing from future queue: %v", 100+i, tx)
            }
        } else {
            if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; ok {
                t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", 100+i, tx)
            }
        }
    }
    if pool.all.Count() != len(txs)/2 {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs)/2)
    }
}

// Tests that if the transaction pool has both executable and non-executable
// transactions from an origin account, filling the nonce gap moves all queued
// ones into the pending pool.
func TestTransactionGapFilling(t *testing.T) {
    t.Parallel()

    // Create a test account and fund it
    pool, key := setupTxPool()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000000))

    // Keep track of transaction events to ensure all executables get announced
    events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
    sub := pool.txFeed.Subscribe(events)
    defer sub.Unsubscribe()

    // Create a pending and a queued transaction with a nonce-gap in between
    if err := pool.AddRemote(transaction(0, 100000, key)); err != nil {
        t.Fatalf("failed to add pending transaction: %v", err)
    }
    if err := pool.AddRemote(transaction(2, 100000, key)); err != nil {
        t.Fatalf("failed to add queued transaction: %v", err)
    }
    pending, queued := pool.Stats()
    if pending != 1 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1)
    }
    if queued != 1 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
    }
    if err := validateEvents(events, 1); err != nil {
        t.Fatalf("original event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Fill the nonce gap and ensure all transactions become pending
    if err := pool.AddRemote(transaction(1, 100000, key)); err != nil {
        t.Fatalf("failed to add gapped transaction: %v", err)
    }
    pending, queued = pool.Stats()
    if pending != 3 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3)
    }
    if queued != 0 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
    }
    if err := validateEvents(events, 2); err != nil {
        t.Fatalf("gap-filling event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// Tests that if the transaction count belonging to a single account goes above
// some threshold, the higher transactions are dropped to prevent DOS attacks.
func TestTransactionQueueAccountLimiting(t *testing.T) {
    t.Parallel()

    // Create a test account and fund it
    pool, key := setupTxPool()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000000))

    // Keep queuing up transactions and make sure all above a limit are dropped
    for i := uint64(1); i <= testTxPoolConfig.AccountQueue+5; i++ {
        if err := pool.AddRemote(transaction(i, 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)
        }
        if i <= testTxPoolConfig.AccountQueue {
            if pool.queue[account].Len() != int(i) {
                t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i)
            }
        } else {
            if pool.queue[account].Len() != int(testTxPoolConfig.AccountQueue) {
                t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), testTxPoolConfig.AccountQueue)
            }
        }
    }
    if pool.all.Count() != int(testTxPoolConfig.AccountQueue) {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue)
    }
}

// Tests that if the transaction count belonging to multiple accounts go above
// some threshold, the higher transactions are dropped to prevent DOS attacks.
//
// This logic should not hold for local transactions, unless the local tracking
// mechanism is disabled.
func TestTransactionQueueGlobalLimiting(t *testing.T) {
    testTransactionQueueGlobalLimiting(t, false)
}
func TestTransactionQueueGlobalLimitingNoLocals(t *testing.T) {
    testTransactionQueueGlobalLimiting(t, true)
}

func testTransactionQueueGlobalLimiting(t *testing.T, nolocals bool) {
    t.Parallel()

    // Create the pool to test the limit enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.NoLocals = nolocals
    config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible)

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create a number of test accounts and fund them (last one will be the local)
    keys := make([]*ecdsa.PrivateKey, 5)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
    }
    local := keys[len(keys)-1]

    // Generate and queue a batch of transactions
    nonces := make(map[common.Address]uint64)

    txs := make(types.Transactions, 0, 3*config.GlobalQueue)
    for len(txs) < cap(txs) {
        key := keys[rand.Intn(len(keys)-1)] // skip adding transactions with the local account
        addr := crypto.PubkeyToAddress(key.PublicKey)

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

    queued := 0
    for addr, list := range pool.queue {
        if list.Len() > int(config.AccountQueue) {
            t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue)
        }
        queued += list.Len()
    }
    if queued > int(config.GlobalQueue) {
        t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue)
    }
    // Generate a batch of transactions from the local account and import them
    txs = txs[:0]
    for i := uint64(0); i < 3*config.GlobalQueue; i++ {
        txs = append(txs, transaction(i+1, 100000, local))
    }
    pool.AddLocals(txs)

    // If locals are disabled, the previous eviction algorithm should apply here too
    if nolocals {
        queued := 0
        for addr, list := range pool.queue {
            if list.Len() > int(config.AccountQueue) {
                t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue)
            }
            queued += list.Len()
        }
        if queued > int(config.GlobalQueue) {
            t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue)
        }
    } else {
        // Local exemptions are enabled, make sure the local account owned the queue
        if len(pool.queue) != 1 {
            t.Errorf("multiple accounts in queue: have %v, want %v", len(pool.queue), 1)
        }
        // Also ensure no local transactions are ever dropped, even if above global limits
        if queued := pool.queue[crypto.PubkeyToAddress(local.PublicKey)].Len(); uint64(queued) != 3*config.GlobalQueue {
            t.Fatalf("local account queued transaction count mismatch: have %v, want %v", queued, 3*config.GlobalQueue)
        }
    }
}

// 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.
//
// This logic should not hold for local transactions, unless the local tracking
// mechanism is disabled.
func TestTransactionQueueTimeLimiting(t *testing.T)         { testTransactionQueueTimeLimiting(t, false) }
func TestTransactionQueueTimeLimitingNoLocals(t *testing.T) { testTransactionQueueTimeLimiting(t, true) }

func testTransactionQueueTimeLimiting(t *testing.T, nolocals bool) {
    // Reduce the eviction interval to a testable amount
    defer func(old time.Duration) { evictionInterval = old }(evictionInterval)
    evictionInterval = time.Second

    // Create the pool to test the non-expiration enforcement
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.Lifetime = time.Second
    config.NoLocals = nolocals

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create two test accounts to ensure remotes expire but locals do not
    local, _ := crypto.GenerateKey()
    remote, _ := crypto.GenerateKey()

    pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
    pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))

    // Add the two transactions and ensure they both are queued up
    if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
        t.Fatalf("failed to add local transaction: %v", err)
    }
    if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), remote)); err != nil {
        t.Fatalf("failed to add remote transaction: %v", err)
    }
    pending, queued := pool.Stats()
    if pending != 0 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
    }
    if queued != 2 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Wait a bit for eviction to run and clean up any leftovers, and ensure only the local remains
    time.Sleep(2 * config.Lifetime)

    pending, queued = pool.Stats()
    if pending != 0 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
    }
    if nolocals {
        if queued != 0 {
            t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
        }
    } else {
        if queued != 1 {
            t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
        }
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// 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) {
    t.Parallel()

    // Create a test account and fund it
    pool, key := setupTxPool()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000000))

    // Keep track of transaction events to ensure all executables get announced
    events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
    sub := pool.txFeed.Subscribe(events)
    defer sub.Unsubscribe()

    // Keep queuing up transactions and make sure all above a limit are dropped
    for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ {
        if err := pool.AddRemote(transaction(i, 100000, key)); err != nil {
            t.Fatalf("tx %d: failed to add transaction: %v", i, err)
        }
        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)
        }
        if len(pool.queue) != 0 {
            t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0)
        }
    }
    if pool.all.Count() != int(testTxPoolConfig.AccountQueue+5) {
        t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue+5)
    }
    if err := validateEvents(events, int(testTxPoolConfig.AccountQueue+5)); err != nil {
        t.Fatalf("event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// 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) {
    t.Parallel()

    // Add a batch of transactions to a pool one by one
    pool1, key1 := setupTxPool()
    defer pool1.Stop()

    account1, _ := deriveSender(transaction(0, 0, key1))
    pool1.currentState.AddBalance(account1, big.NewInt(1000000))

    for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ {
        if err := pool1.AddRemote(transaction(origin+i, 100000, key1)); err != nil {
            t.Fatalf("tx %d: failed to add transaction: %v", i, err)
        }
    }
    // Add a batch of transactions to a pool in one big batch
    pool2, key2 := setupTxPool()
    defer pool2.Stop()

    account2, _ := deriveSender(transaction(0, 0, key2))
    pool2.currentState.AddBalance(account2, big.NewInt(1000000))

    txs := []*types.Transaction{}
    for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ {
        txs = append(txs, transaction(origin+i, 100000, key2))
    }
    pool2.AddRemotes(txs)

    // 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))
    }
    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))
    }
    if pool1.all.Count() != pool2.all.Count() {
        t.Errorf("total transaction count mismatch: one-by-one algo %d, batch algo %d", pool1.all.Count(), pool2.all.Count())
    }
    if err := validateTxPoolInternals(pool1); err != nil {
        t.Errorf("pool 1 internal state corrupted: %v", err)
    }
    if err := validateTxPoolInternals(pool2); err != nil {
        t.Errorf("pool 2 internal state corrupted: %v", err)
    }
}

// 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) {
    t.Parallel()

    // Create the pool to test the limit enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.GlobalSlots = config.AccountSlots * 10

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create a number of test accounts and fund them
    keys := make([]*ecdsa.PrivateKey, 5)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.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(config.GlobalSlots)/len(keys)*2; j++ {
            txs = append(txs, transaction(nonces[addr], 100000, key))
            nonces[addr]++
        }
    }
    // Import the batch and verify that limits have been enforced
    pool.AddRemotes(txs)

    pending := 0
    for _, list := range pool.pending {
        pending += list.Len()
    }
    if pending > int(config.GlobalSlots) {
        t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, config.GlobalSlots)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// Tests that if transactions start being capped, transactions are also removed from 'all'
func TestTransactionCapClearsFromAll(t *testing.T) {
    t.Parallel()

    // Create the pool to test the limit enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.AccountSlots = 2
    config.AccountQueue = 2
    config.GlobalSlots = 8

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create a number of test accounts and fund them
    key, _ := crypto.GenerateKey()
    addr := crypto.PubkeyToAddress(key.PublicKey)
    pool.currentState.AddBalance(addr, big.NewInt(1000000))

    txs := types.Transactions{}
    for j := 0; j < int(config.GlobalSlots)*2; j++ {
        txs = append(txs, transaction(uint64(j), 100000, key))
    }
    // Import the batch and verify that limits have been enforced
    pool.AddRemotes(txs)
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// 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) {
    t.Parallel()

    // Create the pool to test the limit enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.GlobalSlots = 1

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create a number of test accounts and fund them
    keys := make([]*ecdsa.PrivateKey, 5)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.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(config.AccountSlots)*2; j++ {
            txs = append(txs, transaction(nonces[addr], 100000, key))
            nonces[addr]++
        }
    }
    // Import the batch and verify that limits have been enforced
    pool.AddRemotes(txs)

    for addr, list := range pool.pending {
        if list.Len() != int(config.AccountSlots) {
            t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), config.AccountSlots)
        }
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// 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) {
    t.Parallel()

    // Create the pool to test the pricing enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Keep track of transaction events to ensure all executables get announced
    events := make(chan NewTxsEvent, 32)
    sub := pool.txFeed.Subscribe(events)
    defer sub.Unsubscribe()

    // Create a number of test accounts and fund them
    keys := make([]*ecdsa.PrivateKey, 4)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.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, 100000, big.NewInt(2), keys[0]))
    txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[0]))
    txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[0]))

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

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

    ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[3])

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

    pending, queued := pool.Stats()
    if pending != 7 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 7)
    }
    if queued != 3 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3)
    }
    if err := validateEvents(events, 7); err != nil {
        t.Fatalf("original event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // 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 != 5 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 5)
    }
    if err := validateEvents(events, 0); err != nil {
        t.Fatalf("reprice event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Check that we can't add the old transactions back
    if err := pool.AddRemote(pricedTransaction(1, 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.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced {
        t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
    }
    if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), keys[2])); err != ErrUnderpriced {
        t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced)
    }
    if err := validateEvents(events, 0); err != nil {
        t.Fatalf("post-reprice event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // However we can add local underpriced transactions
    tx := pricedTransaction(1, 100000, big.NewInt(1), keys[3])
    if err := pool.AddLocal(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)
    }
    if err := validateEvents(events, 1); err != nil {
        t.Fatalf("post-reprice local event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // And we can fill gaps with properly priced transactions
    if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(2), keys[0])); err != nil {
        t.Fatalf("failed to add pending transaction: %v", err)
    }
    if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), keys[1])); err != nil {
        t.Fatalf("failed to add pending transaction: %v", err)
    }
    if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), keys[2])); err != nil {
        t.Fatalf("failed to add queued transaction: %v", err)
    }
    if err := validateEvents(events, 5); err != nil {
        t.Fatalf("post-reprice event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// Tests that setting the transaction pool gas price to a higher value does not
// remove local transactions.
func TestTransactionPoolRepricingKeepsLocals(t *testing.T) {
    t.Parallel()

    // Create the pool to test the pricing enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create a number of test accounts and fund them
    keys := make([]*ecdsa.PrivateKey, 3)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000*1000000))
    }
    // Create transaction (both pending and queued) with a linearly growing gasprice
    for i := uint64(0); i < 500; i++ {
        // Add pending
        p_tx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2])
        if err := pool.AddLocal(p_tx); err != nil {
            t.Fatal(err)
        }
        // Add queued
        q_tx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2])
        if err := pool.AddLocal(q_tx); err != nil {
            t.Fatal(err)
        }
    }
    pending, queued := pool.Stats()
    expPending, expQueued := 500, 500
    validate := func() {
        pending, queued = pool.Stats()
        if pending != expPending {
            t.Fatalf("pending transactions mismatched: have %d, want %d", pending, expPending)
        }
        if queued != expQueued {
            t.Fatalf("queued transactions mismatched: have %d, want %d", queued, expQueued)
        }

        if err := validateTxPoolInternals(pool); err != nil {
            t.Fatalf("pool internal state corrupted: %v", err)
        }
    }
    validate()

    // Reprice the pool and check that nothing is dropped
    pool.SetGasPrice(big.NewInt(2))
    validate()

    pool.SetGasPrice(big.NewInt(2))
    pool.SetGasPrice(big.NewInt(4))
    pool.SetGasPrice(big.NewInt(8))
    pool.SetGasPrice(big.NewInt(100))
    validate()
}

// 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 the queue.
//
// Note, local transactions are never allowed to be dropped.
func TestTransactionPoolUnderpricing(t *testing.T) {
    t.Parallel()

    // Create the pool to test the pricing enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.GlobalSlots = 2
    config.GlobalQueue = 2

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Keep track of transaction events to ensure all executables get announced
    events := make(chan NewTxsEvent, 32)
    sub := pool.txFeed.Subscribe(events)
    defer sub.Unsubscribe()

    // Create a number of test accounts and fund them
    keys := make([]*ecdsa.PrivateKey, 4)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.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, 100000, big.NewInt(1), keys[0]))
    txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[0]))

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

    ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[2])

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

    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)
    }
    if err := validateEvents(events, 3); err != nil {
        t.Fatalf("original event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Ensure that adding an underpriced transaction on block limit fails
    if err := pool.AddRemote(pricedTransaction(0, 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.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 -
        t.Fatalf("failed to add well priced transaction: %v", err)
    }
    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
        t.Fatalf("failed to add well priced transaction: %v", err)
    }
    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
        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)
    }
    if err := validateEvents(events, 1); err != nil {
        t.Fatalf("additional event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Ensure that adding local transactions can push out even higher priced ones
    ltx = pricedTransaction(1, 100000, big.NewInt(0), keys[2])
    if err := pool.AddLocal(ltx); err != nil {
        t.Fatalf("failed to append underpriced local transaction: %v", err)
    }
    ltx = pricedTransaction(0, 100000, big.NewInt(0), keys[3])
    if err := pool.AddLocal(ltx); err != nil {
        t.Fatalf("failed to add new underpriced local transaction: %v", err)
    }
    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)
    }
    if err := validateEvents(events, 2); err != nil {
        t.Fatalf("local event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// Tests that more expensive transactions push out cheap ones from the pool, but
// without producing instability by creating gaps that start jumping transactions
// back and forth between queued/pending.
func TestTransactionPoolStableUnderpricing(t *testing.T) {
    t.Parallel()

    // Create the pool to test the pricing enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.AccountSlots = 16
    config.GlobalSlots = 128
    config.AccountQueue = 1024
    config.GlobalQueue = 0

    pool := NewTxPool(config, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Keep track of transaction events to ensure all executables get announced
    events := make(chan NewTxsEvent, 32)
    sub := pool.txFeed.Subscribe(events)
    defer sub.Unsubscribe()

    // Create a number of test accounts and fund them
    keys := make([]*ecdsa.PrivateKey, 2)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000))
    }
    // Fill up the entire queue with the same transaction price points
    txs := types.Transactions{}
    for i := uint64(0); i < config.GlobalSlots; i++ {
        txs = append(txs, pricedTransaction(i, 100000, big.NewInt(1), keys[0]))
    }
    pool.AddRemotes(txs)

    pending, queued := pool.Stats()
    if pending != int(config.GlobalSlots) {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
    }
    if queued != 0 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
    }
    if err := validateEvents(events, int(config.GlobalSlots)); err != nil {
        t.Fatalf("original event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Ensure that adding high priced transactions drops a cheap, but doesn't produce a gap
    if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil {
        t.Fatalf("failed to add well priced transaction: %v", err)
    }
    pending, queued = pool.Stats()
    if pending != int(config.GlobalSlots) {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots)
    }
    if queued != 0 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
    }
    if err := validateEvents(events, 1); err != nil {
        t.Fatalf("additional event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// Tests that the pool rejects replacement transactions that don't meet the minimum
// price bump required.
func TestTransactionReplacement(t *testing.T) {
    t.Parallel()

    // Create the pool to test the pricing enforcement with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Keep track of transaction events to ensure all executables get announced
    events := make(chan NewTxsEvent, 32)
    sub := pool.txFeed.Subscribe(events)
    defer sub.Unsubscribe()

    // Create a test account to add transactions with
    key, _ := crypto.GenerateKey()
    pool.currentState.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 + int64(testTxPoolConfig.PriceBump))) / 100

    if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), key)); err != nil {
        t.Fatalf("failed to add original cheap pending transaction: %v", err)
    }
    if err := pool.AddRemote(pricedTransaction(0, 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.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), key)); err != nil {
        t.Fatalf("failed to replace original cheap pending transaction: %v", err)
    }
    if err := validateEvents(events, 2); err != nil {
        t.Fatalf("cheap replacement event firing failed: %v", err)
    }

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

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

    if err := validateEvents(events, 0); err != nil {
        t.Fatalf("queued replacement event firing failed: %v", err)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
}

// Tests that local transactions are journaled to disk, but remote transactions
// get discarded between restarts.
func TestTransactionJournaling(t *testing.T)         { testTransactionJournaling(t, false) }
func TestTransactionJournalingNoLocals(t *testing.T) { testTransactionJournaling(t, true) }

func testTransactionJournaling(t *testing.T, nolocals bool) {
    t.Parallel()

    // Create a temporary file for the journal
    file, err := ioutil.TempFile("", "")
    if err != nil {
        t.Fatalf("failed to create temporary journal: %v", err)
    }
    journal := file.Name()
    defer os.Remove(journal)

    // Clean up the temporary file, we only need the path for now
    file.Close()
    os.Remove(journal)

    // Create the original pool to inject transaction into the journal
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    config := testTxPoolConfig
    config.NoLocals = nolocals
    config.Journal = journal
    config.Rejournal = time.Second

    pool := NewTxPool(config, params.TestChainConfig, blockchain)

    // Create two test accounts to ensure remotes expire but locals do not
    local, _ := crypto.GenerateKey()
    remote, _ := crypto.GenerateKey()

    pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000))
    pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000))

    // Add three local and a remote transactions and ensure they are queued up
    if err := pool.AddLocal(pricedTransaction(0, 100000, big.NewInt(1), local)); err != nil {
        t.Fatalf("failed to add local transaction: %v", err)
    }
    if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil {
        t.Fatalf("failed to add local transaction: %v", err)
    }
    if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil {
        t.Fatalf("failed to add local transaction: %v", err)
    }
    if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), remote)); err != nil {
        t.Fatalf("failed to add remote transaction: %v", err)
    }
    pending, queued := pool.Stats()
    if pending != 4 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4)
    }
    if queued != 0 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Terminate the old pool, bump the local nonce, create a new pool and ensure relevant transaction survive
    pool.Stop()
    statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
    blockchain = &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    pool = NewTxPool(config, params.TestChainConfig, blockchain)

    pending, queued = pool.Stats()
    if queued != 0 {
        t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
    }
    if nolocals {
        if pending != 0 {
            t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
        }
    } else {
        if pending != 2 {
            t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2)
        }
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Bump the nonce temporarily and ensure the newly invalidated transaction is removed
    statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2)
    pool.lockedReset(nil, nil)
    time.Sleep(2 * config.Rejournal)
    pool.Stop()

    statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1)
    blockchain = &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}
    pool = NewTxPool(config, params.TestChainConfig, blockchain)

    pending, queued = pool.Stats()
    if pending != 0 {
        t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0)
    }
    if nolocals {
        if queued != 0 {
            t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0)
        }
    } else {
        if queued != 1 {
            t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1)
        }
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    pool.Stop()
}

// TestTransactionStatusCheck tests that the pool can correctly retrieve the
// pending status of individual transactions.
func TestTransactionStatusCheck(t *testing.T) {
    t.Parallel()

    // Create the pool to test the status retrievals with
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))
    blockchain := &testBlockChain{statedb, 1000000, new(event.Feed), new(event.Feed)}

    pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain)
    defer pool.Stop()

    // Create the test accounts to check various transaction statuses with
    keys := make([]*ecdsa.PrivateKey, 3)
    for i := 0; i < len(keys); i++ {
        keys[i], _ = crypto.GenerateKey()
        pool.currentState.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, 100000, big.NewInt(1), keys[0])) // Pending only
    txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) // Pending and queued
    txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[1]))
    txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) // Queued only

    // Import the transaction and ensure they are correctly added
    pool.AddRemotes(txs)

    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)
    }
    if err := validateTxPoolInternals(pool); err != nil {
        t.Fatalf("pool internal state corrupted: %v", err)
    }
    // Retrieve the status of each transaction and validate them
    hashes := make([]common.Hash, len(txs))
    for i, tx := range txs {
        hashes[i] = tx.Hash()
    }
    hashes = append(hashes, common.Hash{})

    statuses := pool.Status(hashes)
    expect := []TxStatus{TxStatusPending, TxStatusPending, TxStatusQueued, TxStatusQueued, TxStatusUnknown}

    for i := 0; i < len(statuses); i++ {
        if statuses[i] != expect[i] {
            t.Errorf("transaction %d: status mismatch: have %v, want %v", i, statuses[i], expect[i])
        }
    }
}

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

func benchmarkPendingDemotion(b *testing.B, size int) {
    // Add a batch of transactions to a pool one by one
    pool, key := setupTxPool()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000000))

    for i := 0; i < size; i++ {
        tx := transaction(uint64(i), 100000, key)
        pool.promoteTx(account, tx.Hash(), tx)
    }
    // Benchmark the speed of pool validation
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        pool.demoteUnexecutables()
    }
}

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

func benchmarkFuturePromotion(b *testing.B, size int) {
    // Add a batch of transactions to a pool one by one
    pool, key := setupTxPool()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000000))

    for i := 0; i < size; i++ {
        tx := transaction(uint64(1+i), 100000, key)
        pool.enqueueTx(tx.Hash(), tx)
    }
    // Benchmark the speed of pool validation
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        pool.promoteExecutables(nil)
    }
}

// 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()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.AddBalance(account, big.NewInt(1000000))

    txs := make(types.Transactions, b.N)
    for i := 0; i < b.N; i++ {
        txs[i] = transaction(uint64(i), 100000, key)
    }
    // Benchmark importing the transactions into the queue
    b.ResetTimer()
    for _, tx := range txs {
        pool.AddRemote(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()
    defer pool.Stop()

    account, _ := deriveSender(transaction(0, 0, key))
    pool.currentState.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), 100000, key)
        }
    }
    // Benchmark importing the transactions into the queue
    b.ResetTimer()
    for _, batch := range batches {
        pool.AddRemotes(batch)
    }
}