-
Notifications
You must be signed in to change notification settings - Fork 466
/
tx_pool.go
2505 lines (2293 loc) · 82 KB
/
tx_pool.go
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
// Copyright 2014 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 (
"errors"
"fmt"
"math"
"math/big"
"runtime/debug"
"sort"
"sync"
"time"
"github.com/dominant-strategies/go-quai/common"
"github.com/dominant-strategies/go-quai/common/prque"
"github.com/dominant-strategies/go-quai/consensus"
"github.com/dominant-strategies/go-quai/consensus/misc"
"github.com/dominant-strategies/go-quai/core/state"
"github.com/dominant-strategies/go-quai/core/types"
"github.com/dominant-strategies/go-quai/event"
"github.com/dominant-strategies/go-quai/log"
"github.com/dominant-strategies/go-quai/metrics_config"
"github.com/dominant-strategies/go-quai/params"
lru "github.com/hashicorp/golang-lru"
"github.com/sirupsen/logrus"
)
const (
// chainHeadChanSize is the size of channel listening to ChainHeadEvent.
chainHeadChanSize = 10
// txSlotSize is used to calculate how many data slots a single transaction
// takes up based on its size. The slots are used as DoS protection, ensuring
// that validating a new transaction remains a constant operation (in reality
// O(maxslots), where max slots are 4 currently).
txSlotSize = 32 * 1024
// txMaxSize is the maximum size a single transaction can have. This field has
// non-trivial consequences: larger transactions are significantly harder and
// more expensive to propagate; larger transactions also take more resources
// to validate whether they fit into the pool or not.
txMaxSize = 4 * txSlotSize // 128KB
// c_reorgCounterThreshold determines the frequency of the timing prints
// around important functions in txpool
c_reorgCounterThreshold = 200
)
var (
// ErrAlreadyKnown is returned if the transactions is already contained
// within the pool.
ErrAlreadyKnown = errors.New("already known")
// ErrInvalidSender is returned if the transaction contains an invalid signature.
ErrInvalidSender = errors.New("invalid sender")
// ErrUnderpriced is returned if a transaction's gas price is below the minimum
// configured for the transaction pool.
ErrUnderpriced = errors.New("transaction underpriced")
// ErrTxPoolOverflow is returned if the transaction pool is full and can't accpet
// another remote transaction.
ErrTxPoolOverflow = errors.New("txpool is full")
// ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
// with a different one without the required price bump.
ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")
// ErrGasLimit is returned if a transaction's requested gas limit exceeds the
// maximum allowance of the current block.
errGasLimit = errors.New("exceeds block gas limit")
// ErrNegativeValue is a sanity error to ensure no one is able to specify a
// transaction with a negative value.
ErrNegativeValue = errors.New("negative value")
// ErrOversizedData is returned if the input data of a transaction is greater
// than some meaningful limit a user might use. This is not a consensus error
// making the transaction invalid, rather a DOS protection.
ErrOversizedData = errors.New("oversized data")
)
var (
evictionInterval = time.Minute // Time interval to check for evictable transactions
statsReportInterval = 1 * time.Minute // Time interval to report transaction pool stats
)
var (
txpoolMetrics = metrics_config.NewGaugeVec("TxpoolGauges", "Txpool gauges")
// Pending pool metrics
pendingDiscardMeter = txpoolMetrics.WithLabelValues("pending:discard")
pendingReplaceMeter = txpoolMetrics.WithLabelValues("pending:replace")
pendingRateLimitMeter = txpoolMetrics.WithLabelValues("pending:rateLimit") // Dropped due to rate limiting
pendingNofundsMeter = txpoolMetrics.WithLabelValues("pending:noFunds") // Dropped due to out-of-funds
// Metrics for the queued pool
queuedDiscardMeter = txpoolMetrics.WithLabelValues("queued:discard")
queuedReplaceMeter = txpoolMetrics.WithLabelValues("queued:replace")
queuedRateLimitMeter = txpoolMetrics.WithLabelValues("queued:ratelimit") // Dropped due to rate limiting
queuedNofundsMeter = txpoolMetrics.WithLabelValues("queued:nofund") // Dropped due to out-of-funds
queuedEvictionMeter = txpoolMetrics.WithLabelValues("queued:eviction") // Dropped due to lifetime
// General tx metrics
knownTxMeter = txpoolMetrics.WithLabelValues("known") // Known transaction
validTxMeter = txpoolMetrics.WithLabelValues("valid") // Valid transaction
invalidTxMeter = txpoolMetrics.WithLabelValues("invalid") // Invalid transaction
underpricedTxMeter = txpoolMetrics.WithLabelValues("underpriced") // Underpriced transaction
overflowedTxMeter = txpoolMetrics.WithLabelValues("overflowed") // Overflowed transaction
pendingTxGauge = txpoolMetrics.WithLabelValues("pending")
queuedGauge = txpoolMetrics.WithLabelValues("queued")
localTxGauge = txpoolMetrics.WithLabelValues("local")
slotsGauge = txpoolMetrics.WithLabelValues("slots")
qiTxGauge = txpoolMetrics.WithLabelValues("qi")
reheapTimer = metrics_config.NewTimer("Reheap", "Reheap timer")
)
// TxStatus is the current status of a transaction as seen by the pool.
type TxStatus uint
const (
TxStatusUnknown TxStatus = iota
TxStatusQueued
TxStatusPending
TxStatusIncluded
)
// blockChain provides the state of blockchain and current gas limit to do
// some pre checks in tx pool and event subscribers.
type blockChain interface {
CurrentBlock() *types.WorkObject
GetBlock(hash common.Hash, number uint64) *types.WorkObject
StateAt(root, utxoRoot, etxRoot common.Hash) (*state.StateDB, error)
SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
IsGenesisHash(hash common.Hash) bool
CheckIfEtxIsEligible(hash common.Hash, location common.Location) bool
Engine() consensus.Engine
GetHeaderOrCandidate(common.Hash, uint64) *types.WorkObject
GetHeader(common.Hash, uint64) *types.WorkObject
NodeCtx() int
GetHeaderByHash(common.Hash) *types.WorkObject
}
// TxPoolConfig are the configuration parameters of the transaction pool.
type TxPoolConfig struct {
Locals []common.InternalAddress // Addresses that should be treated by default as local
NoLocals bool // Whether local transaction handling should be disabled
Journal string // Journal of local transactions to survive node restarts
Rejournal time.Duration // Time interval to regenerate the local transaction journal
PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)
AccountSlots uint64 // Number of executable transaction slots guaranteed per account
GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts
MaxSenders uint64 // Maximum number of senders in the senders cache
SendersChBuffer uint64 // Senders cache channel buffer size
AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts
QiPoolSize uint64 // Maximum number of Qi transactions to store
Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
}
// DefaultTxPoolConfig contains the default configurations for the transaction
// pool.
var DefaultTxPoolConfig = TxPoolConfig{
Journal: "transactions.rlp",
Rejournal: time.Hour,
PriceLimit: 0,
PriceBump: 5,
AccountSlots: 10,
GlobalSlots: 9000 + 1024, // urgent + floating queue capacity with 4:1 ratio
MaxSenders: 100000, // 5 MB - at least 10 blocks worth of transactions in case of reorg or high production rate
SendersChBuffer: 1024, // at 500 TPS in zone, 2s buffer
AccountQueue: 1,
GlobalQueue: 2048,
QiPoolSize: 10024,
Lifetime: 3 * time.Hour,
}
// sanitize checks the provided user configurations and changes anything that's
// unreasonable or unworkable.
func (config *TxPoolConfig) sanitize(logger *log.Logger) TxPoolConfig {
conf := *config
if conf.Rejournal < time.Second {
logger.WithFields(log.Fields{
"provided": conf.Rejournal,
"updated": time.Second,
}).Warn("Sanitizing invalid txpool journal time")
conf.Rejournal = time.Second
}
if conf.PriceLimit < 1 {
logger.WithFields(log.Fields{
"provided": conf.PriceLimit,
"updated": DefaultTxPoolConfig.PriceLimit,
}).Warn("Sanitizing invalid txpool price limit")
conf.PriceLimit = DefaultTxPoolConfig.PriceLimit
}
if conf.PriceBump < 1 {
logger.WithFields(log.Fields{
"provided": conf.PriceBump,
"updated": DefaultTxPoolConfig.PriceBump,
}).Warn("Sanitizing invalid txpool price bump")
conf.PriceBump = DefaultTxPoolConfig.PriceBump
}
if conf.AccountSlots < 1 {
logger.WithFields(log.Fields{
"provided": conf.AccountSlots,
"updated": DefaultTxPoolConfig.AccountSlots,
}).Warn("Sanitizing invalid txpool account slots")
conf.AccountSlots = DefaultTxPoolConfig.AccountSlots
}
if conf.GlobalSlots < 1 {
logger.WithFields(log.Fields{
"provided": conf.GlobalSlots,
"updated": DefaultTxPoolConfig.GlobalSlots,
}).Warn("Sanitizing invalid txpool global slots")
conf.GlobalSlots = DefaultTxPoolConfig.GlobalSlots
}
if conf.AccountQueue < 1 {
logger.WithFields(log.Fields{
"provided": conf.AccountQueue,
"updated": DefaultTxPoolConfig.AccountQueue,
}).Warn("Sanitizing invalid txpool account queue")
conf.AccountQueue = DefaultTxPoolConfig.AccountQueue
}
if conf.GlobalQueue < 1 {
logger.WithFields(log.Fields{
"provided": conf.GlobalQueue,
"updated": DefaultTxPoolConfig.GlobalQueue,
}).Warn("Sanitizing invalid txpool global queue")
conf.GlobalQueue = DefaultTxPoolConfig.GlobalQueue
}
if conf.QiPoolSize < 1 {
logger.WithFields(log.Fields{
"provided": conf.QiPoolSize,
"updated": DefaultTxPoolConfig.QiPoolSize,
}).Warn("Sanitizing invalid txpool Qi pool size")
conf.QiPoolSize = DefaultTxPoolConfig.QiPoolSize
}
if conf.Lifetime < 1 {
logger.WithFields(log.Fields{
"provided": conf.Lifetime,
"updated": DefaultTxPoolConfig.Lifetime,
}).Warn("Sanitizing invalid txpool lifetime")
conf.Lifetime = DefaultTxPoolConfig.Lifetime
}
return conf
}
// TxPool contains all currently known transactions. Transactions
// enter the pool when they are received from the network or submitted
// locally. They exit the pool when they are included in the blockchain.
//
// The pool separates processable transactions (which can be applied to the
// current state) and future transactions. Transactions move between those
// two states over time as they are received and processed.
type TxPool struct {
config TxPoolConfig
chainconfig *params.ChainConfig
chain blockChain
gasPrice *big.Int
txFeed event.Feed
scope event.SubscriptionScope
signer types.Signer
mu sync.RWMutex
qiMu sync.RWMutex
currentState *state.StateDB // Current state in the blockchain head
pendingNonces *txNoncer // Pending state tracking virtual nonces
currentMaxGas uint64 // Current gas limit for transaction caps
locals *accountSet // Set of local transaction to exempt from eviction rules
journal *txJournal // Journal of local transaction to back up to disk
qiPool map[common.Hash]*types.TxWithMinerFee // Qi pool to store Qi transactions
pending map[common.InternalAddress]*txList // All currently processable transactions
queue map[common.InternalAddress]*txList // Queued but non-processable transactions
beats map[common.InternalAddress]time.Time // Last heartbeat from each known account
all *txLookup // All transactions to allow lookups
priced *txPricedList // All transactions sorted by price
senders *lru.Cache // Tx hash to sender lookup cache (async populated)
sendersCh chan newSender // Channel for async senders cache goroutine
SendersMu sync.RWMutex // Mutex for priority access of senders cache
localTxsCount int // count of txs in last 1 min. Purely for logging purpose
remoteTxsCount int // count of txs in last 1 min. Purely for logging purpose
reOrgCounter int // keeps track of the number of times the runReorg is called, it is reset every c_reorgCounterThreshold times
chainHeadCh chan ChainHeadEvent
chainHeadSub event.Subscription
reqResetCh chan *txpoolResetRequest
reqPromoteCh chan *accountSet
queueTxEventCh chan *types.Transaction
reorgDoneCh chan chan struct{}
reorgShutdownCh chan struct{} // requests shutdown of scheduleReorgLoop
wg sync.WaitGroup // tracks loop, scheduleReorgLoop
logger *log.Logger
}
type txpoolResetRequest struct {
oldHead, newHead *types.WorkObject
}
type newSender struct {
hash common.Hash
sender common.InternalAddress
}
// NewTxPool creates a new transaction pool to gather, sort and filter inbound
// transactions from the network.
func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain, logger *log.Logger) *TxPool {
// Pending pool metrics
pendingDiscardMeter.Set(0)
pendingReplaceMeter.Set(0)
pendingRateLimitMeter.Set(0)
pendingNofundsMeter.Set(0)
// Metrics for the queued pool
queuedDiscardMeter.Set(0)
queuedReplaceMeter.Set(0)
queuedRateLimitMeter.Set(0)
queuedNofundsMeter.Set(0)
queuedEvictionMeter.Set(0)
// General tx metrics
knownTxMeter.Set(0)
validTxMeter.Set(0)
invalidTxMeter.Set(0)
underpricedTxMeter.Set(0)
overflowedTxMeter.Set(0)
pendingTxGauge.Set(0)
queuedGauge.Set(0)
localTxGauge.Set(0)
// Sanitize the input to ensure no vulnerable gas prices are set
config = (&config).sanitize(logger)
// Create the transaction pool with its initial settings
pool := &TxPool{
config: config,
chainconfig: chainconfig,
chain: chain,
signer: types.LatestSigner(chainconfig),
pending: make(map[common.InternalAddress]*txList),
qiPool: make(map[common.Hash]*types.TxWithMinerFee),
queue: make(map[common.InternalAddress]*txList),
beats: make(map[common.InternalAddress]time.Time),
sendersCh: make(chan newSender, config.SendersChBuffer),
all: newTxLookup(),
chainHeadCh: make(chan ChainHeadEvent, chainHeadChanSize),
reqResetCh: make(chan *txpoolResetRequest),
reqPromoteCh: make(chan *accountSet),
queueTxEventCh: make(chan *types.Transaction),
reorgDoneCh: make(chan chan struct{}),
reorgShutdownCh: make(chan struct{}),
gasPrice: new(big.Int).SetUint64(config.PriceLimit),
localTxsCount: 0,
remoteTxsCount: 0,
reOrgCounter: 0,
logger: logger,
}
pool.senders, _ = lru.New(int(config.MaxSenders))
pool.locals = newAccountSet(pool.signer)
for _, addr := range config.Locals {
logger.WithField("address", addr).Debug("Setting new local account")
pool.locals.add(addr)
}
pool.priced = newTxPricedList(pool.all)
pool.mu.Lock()
pool.reset(nil, chain.CurrentBlock())
pool.mu.Unlock()
// Start the reorg loop early so it can handle requests generated during journal loading.
pool.wg.Add(1)
go pool.scheduleReorgLoop()
// If local transactions and journaling is enabled, load from disk
if !config.NoLocals && config.Journal != "" {
pool.journal = newTxJournal(config.Journal, logger)
if err := pool.journal.load(pool.AddLocals); err != nil {
logger.WithField("err", err).Warn("Failed to load transaction journal")
}
if err := pool.journal.rotate(pool.local()); err != nil {
logger.WithField("err", err).Warn("Failed to rotate transaction journal")
}
}
// Subscribe events from blockchain and start the main event loop.
pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh)
pool.wg.Add(1)
go pool.loop()
go pool.sendersGoroutine()
go pool.poolLimiterGoroutine()
return pool
}
// loop is the transaction pool's main event loop, waiting for and reacting to
// outside blockchain events as well as for various reporting and transaction
// eviction events.
func (pool *TxPool) loop() {
defer pool.wg.Done()
defer func() {
if r := recover(); r != nil {
pool.logger.WithFields(log.Fields{
"error": r,
"stacktrace": string(debug.Stack()),
}).Error("Go-Quai Panicked")
}
}()
var (
// Start the stats reporting and transaction eviction tickers
report = time.NewTicker(statsReportInterval)
evict = time.NewTicker(evictionInterval)
journal = time.NewTicker(pool.config.Rejournal)
// Track the previous head headers for transaction reorgs
head = pool.chain.CurrentBlock()
)
defer report.Stop()
defer evict.Stop()
defer journal.Stop()
for {
select {
// Handle ChainHeadEvent
case ev := <-pool.chainHeadCh:
if ev.Block != nil {
pool.requestReset(head, ev.Block)
head = ev.Block
}
// System shutdown.
case <-pool.chainHeadSub.Err():
close(pool.reorgShutdownCh)
return
// Handle stats reporting ticks
case <-report.C:
pool.mu.RLock()
pending, queued := pool.stats()
stales := pool.priced.stales
pool.logger.WithFields(log.Fields{
"Local Txs": pool.localTxsCount,
"Remote Txs": pool.remoteTxsCount,
}).Info("Added Transactions in last Min", "Local Txs", pool.localTxsCount, "Remote Txs", pool.remoteTxsCount)
pool.localTxsCount = 0
pool.remoteTxsCount = 0
pool.mu.RUnlock()
pool.logger.WithFields(log.Fields{
"pending": pending,
"queued": queued,
"stales": stales,
}).Info("Transaction pool status report")
// Handle inactive account transaction eviction
case <-evict.C:
pool.mu.Lock()
for addr := range pool.queue {
// Any transactions old enough should be removed
if time.Since(pool.beats[addr]) > pool.config.Lifetime {
list := pool.queue[addr].Flatten()
for _, tx := range list {
pool.removeTx(tx.Hash(), true)
}
queuedEvictionMeter.Add(float64(len(list)))
}
}
pool.mu.Unlock()
// Handle local transaction journal rotation
case <-journal.C:
if pool.journal != nil {
pool.mu.Lock()
if err := pool.journal.rotate(pool.local()); err != nil {
pool.logger.WithField("err", err).Warn("Failed to rotate local tx journal")
}
pool.mu.Unlock()
}
}
}
}
// Stop terminates the transaction pool.
func (pool *TxPool) Stop() {
// Unsubscribe all subscriptions registered from txpool
pool.scope.Close()
// Unsubscribe subscriptions registered from blockchain
pool.chainHeadSub.Unsubscribe()
pool.wg.Wait()
if pool.journal != nil {
pool.journal.close()
}
pool.logger.Info("Transaction pool stopped")
}
// SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
// starts sending event to the given channel.
func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
return pool.scope.Track(pool.txFeed.Subscribe(ch))
}
// GasPrice returns the current gas price enforced by the transaction pool.
func (pool *TxPool) GasPrice() *big.Int {
pool.mu.RLock()
defer pool.mu.RUnlock()
return new(big.Int).Set(pool.gasPrice)
}
// SetGasPrice updates the minimum price required by the transaction pool for a
// new transaction, and drops all transactions below this threshold.
func (pool *TxPool) SetGasPrice(price *big.Int) {
pool.mu.Lock()
defer pool.mu.Unlock()
old := pool.gasPrice
pool.gasPrice = price
// if the min miner fee increased, remove transactions below the new threshold
if price.Cmp(old) > 0 {
// pool.priced is sorted by GasFeeCap, so we have to iterate through pool.all instead
drop := pool.all.RemotesBelowTip(price)
for _, tx := range drop {
pool.removeTx(tx.Hash(), false)
}
pool.priced.Removed(len(drop))
}
pool.logger.WithField("price", price).Info("Transaction pool price threshold updated")
}
// Nonce returns the next nonce of an account, with all transactions executable
// by the pool already applied on top.
func (pool *TxPool) Nonce(addr common.InternalAddress) uint64 {
pool.mu.RLock()
defer pool.mu.RUnlock()
return pool.pendingNonces.get(addr)
}
// Stats retrieves the current pool stats, namely the number of pending and the
// number of queued (non-executable) transactions.
func (pool *TxPool) Stats() (int, int) {
pool.mu.RLock()
defer pool.mu.RUnlock()
return pool.stats()
}
// stats retrieves the current pool stats, namely the number of pending and the
// number of queued (non-executable) transactions.
func (pool *TxPool) stats() (int, int) {
pending := 0
for _, list := range pool.pending {
pending += list.Len()
}
queued := 0
for _, list := range pool.queue {
queued += list.Len()
}
return pending, queued
}
// Content retrieves the data content of the transaction pool, returning all the
// pending as well as queued transactions, grouped by account and sorted by nonce.
func (pool *TxPool) Content() (map[common.InternalAddress]types.Transactions, map[common.InternalAddress]types.Transactions) {
pool.mu.Lock()
defer pool.mu.Unlock()
pending := make(map[common.InternalAddress]types.Transactions)
for addr, list := range pool.pending {
pending[addr] = list.Flatten()
}
queued := make(map[common.InternalAddress]types.Transactions)
for addr, list := range pool.queue {
queued[addr] = list.Flatten()
}
return pending, queued
}
// ContentFrom retrieves the data content of the transaction pool, returning the
// pending as well as queued transactions of this address, grouped by nonce.
func (pool *TxPool) ContentFrom(addr common.InternalAddress) (types.Transactions, types.Transactions) {
pool.mu.RLock()
defer pool.mu.RUnlock()
var pending types.Transactions
if list, ok := pool.pending[addr]; ok {
pending = list.Flatten()
}
var queued types.Transactions
if list, ok := pool.queue[addr]; ok {
queued = list.Flatten()
}
return pending, queued
}
func (pool *TxPool) QiPoolPending() map[common.Hash]*types.TxWithMinerFee {
pool.qiMu.RLock()
defer pool.qiMu.RUnlock()
// Return a copy of the pool because it is not safe to access the pool pointer directly
qiTxs := make(map[common.Hash]*types.TxWithMinerFee)
for hash, qiTx := range pool.qiPool {
qiTxs[hash] = qiTx
}
return qiTxs
}
// Pending retrieves all currently processable transactions, grouped by origin
// account and sorted by nonce. The returned transaction set is a copy and can be
// freely modified by calling code.
//
// The enforceTips parameter can be used to do an extra filtering on the pending
// transactions and only return those whose **effective** tip is large enough in
// the next pending execution environment.
func (pool *TxPool) TxPoolPending(enforceTips bool) (map[common.AddressBytes]types.Transactions, error) {
pool.mu.RLock()
defer pool.mu.RUnlock()
pending := make(map[common.AddressBytes]types.Transactions)
for addr, list := range pool.pending {
txs := list.Flatten()
// If the miner requests tip enforcement, cap the lists now
if enforceTips && !pool.locals.contains(addr) {
for i, tx := range txs {
if tx.EffectiveGasTipIntCmp(pool.gasPrice, pool.priced.urgent.baseFee) < 0 {
pool.logger.WithFields(log.Fields{
"tx": tx.Hash().String(),
"gasTipCap": tx.GasTipCap().String(),
"poolGasPrice": pool.gasPrice.String(),
"baseFee": pool.priced.urgent.baseFee.String(),
}).Debug("TX has incorrect or low miner tip")
txs = txs[:i]
break
}
}
}
if len(txs) > 0 {
pending[addr.Bytes20()] = txs
}
}
return pending, nil
}
// Locals retrieves the accounts currently considered local by the pool.
func (pool *TxPool) Locals() []common.InternalAddress {
pool.mu.Lock()
defer pool.mu.Unlock()
return pool.locals.flatten()
}
// local retrieves all currently known local transactions, grouped by origin
// account and sorted by nonce. The returned transaction set is a copy and can be
// freely modified by calling code.
func (pool *TxPool) local() map[common.InternalAddress]types.Transactions {
txs := make(map[common.InternalAddress]types.Transactions)
for addr := range pool.locals.accounts {
if pending := pool.pending[addr]; pending != nil {
txs[addr] = append(txs[addr], pending.Flatten()...)
}
if queued := pool.queue[addr]; queued != nil {
txs[addr] = append(txs[addr], queued.Flatten()...)
}
}
return txs
}
// validateTx checks whether a transaction is valid according to the consensus
// rules and adheres to some heuristic limits of the local node (price and size).
func (pool *TxPool) validateTx(tx *types.Transaction) error {
// Reject transactions over defined size to prevent DOS attacks
if uint64(tx.Size()) > txMaxSize {
return ErrOversizedData
}
// Transactions can't be negative. This may never happen using RLP decoded
// transactions but may occur if you create a transaction using the RPC.
if tx.Value().Sign() < 0 {
return ErrNegativeValue
}
// Ensure the transaction doesn't exceed the current block limit gas.
if pool.currentMaxGas < tx.Gas() {
return ErrGasLimit(tx.Gas(), pool.currentMaxGas)
}
// Sanity check for extremely large numbers
if tx.GasFeeCap().BitLen() > 256 {
return ErrFeeCapVeryHigh
}
if tx.GasTipCap().BitLen() > 256 {
return ErrTipVeryHigh
}
// Ensure gasFeeCap is greater than or equal to gasTipCap.
if tx.GasFeeCapIntCmp(tx.GasTipCap()) < 0 {
return ErrTipAboveFeeCap
}
var internal common.InternalAddress
addToCache := true
if sender := tx.From(pool.chainconfig.Location); sender != nil { // Check tx cache first
var err error
internal, err = sender.InternalAndQuaiAddress()
if err != nil {
return err
}
} else if sender, found := pool.PeekSender(tx.Hash()); found {
internal = sender
addToCache = false
} else {
// Make sure the transaction is signed properly.
from, err := types.Sender(pool.signer, tx)
if err != nil {
return ErrInvalidSender
}
internal, err = from.InternalAndQuaiAddress()
if err != nil {
return err
}
}
// Drop non-local transactions under our own minimal accepted gas price or tip
if tx.GasTipCapIntCmp(pool.gasPrice) < 0 {
return ErrUnderpriced
}
// Ensure the transaction adheres to nonce ordering
if pool.currentState.GetNonce(internal) > tx.Nonce() {
return ErrNonceTooLow
}
// Transactor should have enough funds to cover the costs
// cost == V + GP * GL
if pool.currentState.GetBalance(internal).Cmp(tx.Cost()) < 0 {
return ErrInsufficientFunds
}
// Ensure the transaction has more gas than the basic tx fee.
intrGas, err := IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil)
if err != nil {
return err
}
if tx.Gas() < intrGas {
pool.logger.WithFields(log.Fields{
"gasSupplied": tx.Gas(),
"gasNeeded": intrGas,
"tx": tx,
}).Warn("tx has insufficient gas")
return ErrIntrinsicGas
}
if addToCache {
select {
case pool.sendersCh <- newSender{tx.Hash(), internal}: // Non-blocking
default:
pool.logger.Error("sendersCh is full, skipping until there is room")
}
}
return nil
}
// add validates a transaction and inserts it into the non-executable queue for later
// pending promotion and execution. If the transaction is a replacement for an already
// pending or queued one, it overwrites the previous transaction if its price is higher.
//
// If a newly added transaction is marked as local, its sending account will be
// be added to the allowlist, preventing any associated transaction from being dropped
// out of the pool due to pricing constraints.
func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err error) {
// If the transaction is already known, discard it
hash := tx.Hash()
if pool.all.Get(hash) != nil {
pool.logger.WithField("hash", hash).Trace("Discarding already known transaction")
knownTxMeter.Add(1)
return false, ErrAlreadyKnown
}
// Make the local flag. If it's from local source or it's from the network but
// the sender is marked as local previously, treat it as the local transaction.
isLocal := local || pool.locals.containsTx(tx)
// If the transaction fails basic validation, discard it
if err := pool.validateTx(tx); err != nil {
pool.logger.WithFields(log.Fields{
"hash": hash,
"err": err,
}).Trace("Discarding invalid transaction")
invalidTxMeter.Add(1)
return false, err
}
// If the transaction pool is full, discard underpriced transactions
if uint64(pool.all.Slots()+numSlots(tx)) > pool.config.GlobalSlots+pool.config.GlobalQueue {
// If the new transaction is underpriced, don't accept it
if pool.priced.Underpriced(tx) {
pool.logger.WithFields(log.Fields{
"hash": hash,
"gasTipCap": tx.GasTipCap(),
"gasFeeCap": tx.GasFeeCap(),
}).Trace("Discarding underpriced transaction")
underpricedTxMeter.Add(1)
return false, ErrUnderpriced
}
// New transaction is better than our worse ones, make room for it.
// If it's a local transaction, forcibly discard all available transactions.
// Otherwise if we can't make enough room for new one, abort the operation.
drop, success := pool.priced.Discard(pool.all.Slots()-int(pool.config.GlobalSlots+pool.config.GlobalQueue)+numSlots(tx), false)
// Special case, we still can't make the room for the new remote one.
if !success {
pool.logger.WithField("hash", hash).Trace("Discarding overflown transaction")
overflowedTxMeter.Add(1)
return false, ErrTxPoolOverflow
}
// Kick out the underpriced remote transactions.
for _, tx := range drop {
pool.logger.WithFields(log.Fields{
"hash": tx.Hash(),
"gasTipCap": tx.GasTipCap(),
"gasFeeCap": tx.GasFeeCap(),
}).Trace("Discarding freshly underpriced transaction")
pendingDiscardMeter.Add(1)
pool.removeTx(tx.Hash(), false)
}
}
// Try to replace an existing transaction in the pending pool
from, err := types.Sender(pool.signer, tx) // already validated
if err != nil {
return false, err
}
internal, err := from.InternalAndQuaiAddress()
if err != nil {
return false, err
}
if list := pool.pending[internal]; list != nil && list.Overlaps(tx) {
// Nonce already pending, check if required price bump is met
inserted, old := list.Add(tx, pool.config.PriceBump)
if !inserted {
pendingDiscardMeter.Add(1)
return false, ErrReplaceUnderpriced
}
// New transaction is better, replace old one
if old != nil {
pool.all.Remove(old.Hash(), pool.logger)
pool.priced.Removed(1)
pendingReplaceMeter.Add(1)
}
pool.all.Add(tx, isLocal)
pool.priced.Put(tx, isLocal)
pool.journalTx(internal, tx)
pool.queueTxEvent(tx)
pool.logger.WithFields(log.Fields{
"hash": hash,
"from": from,
"to": tx.To(),
}).Trace("Pooled new executable transaction")
// Successful promotion, bump the heartbeat
pool.beats[internal] = time.Now()
return old != nil, nil
}
// New transaction isn't replacing a pending one, push into queue
replaced, err = pool.enqueueTx(hash, tx, isLocal, true)
if err != nil {
return false, err
}
// Mark local addresses and journal local transactions
if local && !pool.locals.contains(internal) {
pool.logger.WithField("address", from).Info("Setting new local account")
pool.locals.add(internal)
pool.priced.Removed(pool.all.RemoteToLocals(pool.locals)) // Migrate the remotes if it's marked as local first time.
}
if isLocal {
localTxGauge.Add(1)
}
pool.journalTx(internal, tx)
pool.queueTxEvent(tx)
pool.logger.WithFields(log.Fields{
"hash": hash,
"from": from,
"to": tx.To(),
}).Trace("Pooled new future transaction")
return replaced, nil
}
// enqueueTx inserts a new transaction into the non-executable transaction queue.
//
// Note, this method assumes the pool lock is held!
func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction, local bool, addAll bool) (bool, error) {
// Try to insert the transaction into the future queue
from, err := types.Sender(pool.signer, tx) // already validated
if err != nil {
return false, err
}
internal, err := from.InternalAndQuaiAddress()
if err != nil {
return false, err
}
if pool.queue[internal] == nil {
pool.queue[internal] = newTxList(false)
}
inserted, old := pool.queue[internal].Add(tx, pool.config.PriceBump)
if !inserted {
// An older transaction was better, discard this
queuedDiscardMeter.Add(1)
return false, ErrReplaceUnderpriced
}
// Discard any previous transaction and mark this
if old != nil {
pool.all.Remove(old.Hash(), pool.logger)
pool.priced.Removed(1)
queuedReplaceMeter.Add(1)
} else {
// Nothing was replaced, bump the queued counter
queuedGauge.Add(1)
}
// If the transaction isn't in lookup set but it's expected to be there,
// show the error pool.logger.
if pool.all.Get(hash) == nil && !addAll {
pool.logger.WithField("hash", hash).Error("Missing transaction in lookup set, please report the issue")
}
if addAll {
pool.all.Add(tx, local)
pool.priced.Put(tx, local)
}
// If we never record the heartbeat, do it right now.
if _, exist := pool.beats[internal]; !exist {
pool.beats[internal] = time.Now()
}
return old != nil, nil
}
// journalTx adds the specified transaction to the local disk journal if it is
// deemed to have been sent from a local account.
func (pool *TxPool) journalTx(from common.InternalAddress, tx *types.Transaction) {
// Only journal if it's enabled and the transaction is local
if pool.journal == nil || !pool.locals.contains(from) {
return
}
if err := pool.journal.insert(tx); err != nil {
pool.logger.WithField("err", err).Warn("Failed to journal local transaction")
}
}
// promoteTx adds a transaction to the pending (processable) list of transactions
// and returns whether it was inserted or an older was better.
//
// Note, this method assumes the pool lock is held!
func (pool *TxPool) promoteTx(addr common.InternalAddress, hash common.Hash, tx *types.Transaction) bool {
// Try to insert the transaction into the pending queue
if pool.pending[addr] == nil {
pool.pending[addr] = newTxList(true)
}
list := pool.pending[addr]
inserted, old := list.Add(tx, pool.config.PriceBump)
if !inserted {
// An older transaction was better, discard this
pool.all.Remove(hash, pool.logger)
pool.priced.Removed(1)
pendingDiscardMeter.Add(1)
return false
}
// Otherwise discard any previous transaction and mark this
if old != nil {
pool.all.Remove(old.Hash(), pool.logger)
pool.priced.Removed(1)
pendingReplaceMeter.Add(1)
} else {
// Nothing was replaced, bump the pending counter
pendingTxGauge.Add(1)
}
// Set the potentially new pending nonce and notify any subsystems of the new tx
pool.pendingNonces.set(addr, tx.Nonce()+1)
// Successful promotion, bump the heartbeat
pool.beats[addr] = time.Now()
if list.Len()%100 == 0 {
pool.logger.WithFields(log.Fields{
"addr": addr,
"len": list.Len(),
}).Info("Another 100 txs added to list")
}
return true
}