Skip to content

Commit 48ee7f9

Browse files
committed
core, eth, les: polish txpool API around local/remote txs
1 parent a633a2d commit 48ee7f9

9 files changed

Lines changed: 153 additions & 149 deletions

File tree

‎core/tx_list.go‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ func (l *txPricedList) Removed() {
420420
heap.Init(l.items)
421421
}
422422

423-
// Discard finds all the transactions below the given price threshold, drops them
423+
// Cap finds all the transactions below the given price threshold, drops them
424424
// from the priced list and returs them for further removal from the entire pool.
425425
func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transactions {
426426
drop := make(types.Transactions, 0, 128) // Remote underpriced transactions to drop
@@ -429,9 +429,7 @@ func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transact
429429
for len(*l.items) > 0 {
430430
// Discard stale transactions if found during cleanup
431431
tx := heap.Pop(l.items).(*types.Transaction)
432-
433-
hash := tx.Hash()
434-
if _, ok := (*l.all)[hash]; !ok {
432+
if _, ok := (*l.all)[tx.Hash()]; !ok {
435433
l.stales--
436434
continue
437435
}
@@ -440,7 +438,7 @@ func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transact
440438
break
441439
}
442440
// Non stale transaction found, discard unless local
443-
if local.contains(tx) {
441+
if local.containsTx(tx) {
444442
save = append(save, tx)
445443
} else {
446444
drop = append(drop, tx)
@@ -456,7 +454,7 @@ func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transact
456454
// lowest priced transaction currently being tracked.
457455
func (l *txPricedList) Underpriced(tx *types.Transaction, local *accountSet) bool {
458456
// Local transactions cannot be underpriced
459-
if local.contains(tx) {
457+
if local.containsTx(tx) {
460458
return false
461459
}
462460
// Discard stale price points if found at the heap start
@@ -487,14 +485,12 @@ func (l *txPricedList) Discard(count int, local *accountSet) types.Transactions
487485
for len(*l.items) > 0 && count > 0 {
488486
// Discard stale transactions if found during cleanup
489487
tx := heap.Pop(l.items).(*types.Transaction)
490-
491-
hash := tx.Hash()
492-
if _, ok := (*l.all)[hash]; !ok {
488+
if _, ok := (*l.all)[tx.Hash()]; !ok {
493489
l.stales--
494490
continue
495491
}
496492
// Non stale transaction found, discard unless local
497-
if local.contains(tx) {
493+
if local.containsTx(tx) {
498494
save = append(save, tx)
499495
} else {
500496
drop = append(drop, tx)

‎core/tx_pool.go‎

Lines changed: 86 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -176,12 +176,12 @@ type TxPool struct {
176176
func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
177177
// Sanitize the input to ensure no vulnerable gas prices are set
178178
config = (&config).sanitize()
179-
signer := types.NewEIP155Signer(chainconfig.ChainId)
179+
180180
// Create the transaction pool with its initial settings
181181
pool := &TxPool{
182182
config: config,
183183
chainconfig: chainconfig,
184-
signer: signer,
184+
signer: types.NewEIP155Signer(chainconfig.ChainId),
185185
pending: make(map[common.Address]*txList),
186186
queue: make(map[common.Address]*txList),
187187
beats: make(map[common.Address]time.Time),
@@ -191,10 +191,10 @@ func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, eventMux *e
191191
gasLimit: gasLimitFn,
192192
gasPrice: new(big.Int).SetUint64(config.PriceLimit),
193193
pendingState: nil,
194-
locals: newAccountSet(signer),
195194
events: eventMux.Subscribe(ChainHeadEvent{}, RemovedTransactionEvent{}),
196195
quit: make(chan struct{}),
197196
}
197+
pool.locals = newAccountSet(pool.signer)
198198
pool.priced = newTxPricedList(&pool.all)
199199
pool.resetState()
200200

@@ -237,7 +237,7 @@ func (pool *TxPool) eventLoop() {
237237
pool.mu.Unlock()
238238

239239
case RemovedTransactionEvent:
240-
pool.AddBatch(ev.Txs)
240+
pool.addTxs(ev.Txs, false)
241241
}
242242

243243
// Handle stats reporting ticks
@@ -371,52 +371,40 @@ func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
371371
return pending, nil
372372
}
373373

374-
// SetLocal marks a transaction as local, skipping gas price
375-
// check against local miner minimum in the future
376-
func (pool *TxPool) SetLocal(tx *types.Transaction) {
377-
pool.mu.Lock()
378-
defer pool.mu.Unlock()
379-
pool.locals.add(tx)
380-
}
381-
382-
// validateTx checks whether a transaction is valid according
383-
// to the consensus rules.
384-
func (pool *TxPool) validateTx(tx *types.Transaction) error {
385-
374+
// validateTx checks whether a transaction is valid according to the consensus
375+
// rules and adheres to some heuristic limits of the local node (price and size).
376+
func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
377+
// Heuristic limit, reject transactions over 32KB to prevent DOS attacks
378+
if tx.Size() > 32*1024 {
379+
return ErrOversizedData
380+
}
381+
// Transactions can't be negative. This may never happen using RLP decoded
382+
// transactions but may occur if you create a transaction using the RPC.
383+
if tx.Value().Sign() < 0 {
384+
return ErrNegativeValue
385+
}
386+
// Ensure the transaction doesn't exceed the current block limit gas.
387+
if pool.gasLimit().Cmp(tx.Gas()) < 0 {
388+
return ErrGasLimit
389+
}
390+
// Make sure the transaction is signed properly
386391
from, err := types.Sender(pool.signer, tx)
387392
if err != nil {
388393
return ErrInvalidSender
389394
}
390-
391-
local := pool.locals.containsAddress(from)
392-
// Drop transactions under our own minimal accepted gas price
395+
// Drop non-local transactions under our own minimal accepted gas price
396+
local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network
393397
if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 {
394398
return ErrUnderpriced
395399
}
396-
400+
// Ensure the transaction adheres to nonce ordering
397401
currentState, err := pool.currentState()
398402
if err != nil {
399403
return err
400404
}
401-
402-
// Last but not least check for nonce errors
403405
if currentState.GetNonce(from) > tx.Nonce() {
404406
return ErrNonceTooLow
405407
}
406-
407-
// Check the transaction doesn't exceed the current
408-
// block limit gas.
409-
if pool.gasLimit().Cmp(tx.Gas()) < 0 {
410-
return ErrGasLimit
411-
}
412-
413-
// Transactions can't be negative. This may never happen
414-
// using RLP decoded transactions but may occur if you create
415-
// a transaction using the RPC for example.
416-
if tx.Value().Sign() < 0 {
417-
return ErrNegativeValue
418-
}
419-
420408
// Transactor should have enough funds to cover the costs
421409
// cost == V + GP * GL
422410
if currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
@@ -426,27 +414,26 @@ func (pool *TxPool) validateTx(tx *types.Transaction) error {
426414
if tx.Gas().Cmp(intrGas) < 0 {
427415
return ErrIntrinsicGas
428416
}
429-
430-
// Heuristic limit, reject transactions over 32KB to prevent DOS attacks
431-
if tx.Size() > 32*1024 {
432-
return ErrOversizedData
433-
}
434417
return nil
435418
}
436419

437420
// add validates a transaction and inserts it into the non-executable queue for
438421
// later pending promotion and execution. If the transaction is a replacement for
439422
// an already pending or queued one, it overwrites the previous and returns this
440423
// so outer code doesn't uselessly call promote.
441-
func (pool *TxPool) add(tx *types.Transaction) (bool, error) {
424+
//
425+
// If a newly added transaction is marked as local, its sending account will be
426+
// whitelisted, preventing any associated transaction from being dropped out of
427+
// the pool due to pricing constraints.
428+
func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
442429
// If the transaction is already known, discard it
443430
hash := tx.Hash()
444431
if pool.all[hash] != nil {
445432
log.Trace("Discarding already known transaction", "hash", hash)
446433
return false, fmt.Errorf("known transaction: %x", hash)
447434
}
448435
// If the transaction fails basic validation, discard it
449-
if err := pool.validateTx(tx); err != nil {
436+
if err := pool.validateTx(tx, local); err != nil {
450437
log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
451438
invalidTxCounter.Inc(1)
452439
return false, err
@@ -488,11 +475,14 @@ func (pool *TxPool) add(tx *types.Transaction) (bool, error) {
488475
log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
489476
return old != nil, nil
490477
}
491-
// New transaction isn't replacing a pending one, push into queue
478+
// New transaction isn't replacing a pending one, push into queue and potentially mark local
492479
replace, err := pool.enqueueTx(hash, tx)
493480
if err != nil {
494481
return false, err
495482
}
483+
if local {
484+
pool.locals.add(from)
485+
}
496486
log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
497487
return replace, nil
498488
}
@@ -560,13 +550,41 @@ func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.T
560550
go pool.eventMux.Post(TxPreEvent{tx})
561551
}
562552

563-
// Add queues a single transaction in the pool if it is valid.
564-
func (pool *TxPool) Add(tx *types.Transaction) error {
553+
// AddLocal enqueues a single transaction into the pool if it is valid, marking
554+
// the sender as a local one in the mean time, ensuring it goes around the local
555+
// pricing constraints.
556+
func (pool *TxPool) AddLocal(tx *types.Transaction) error {
557+
return pool.addTx(tx, true)
558+
}
559+
560+
// AddRemote enqueues a single transaction into the pool if it is valid. If the
561+
// sender is not among the locally tracked ones, full pricing constraints will
562+
// apply.
563+
func (pool *TxPool) AddRemote(tx *types.Transaction) error {
564+
return pool.addTx(tx, false)
565+
}
566+
567+
// AddLocals enqueues a batch of transactions into the pool if they are valid,
568+
// marking the senders as a local ones in the mean time, ensuring they go around
569+
// the local pricing constraints.
570+
func (pool *TxPool) AddLocals(txs []*types.Transaction) error {
571+
return pool.addTxs(txs, true)
572+
}
573+
574+
// AddRemotes enqueues a batch of transactions into the pool if they are valid.
575+
// If the senders are not among the locally tracked ones, full pricing constraints
576+
// will apply.
577+
func (pool *TxPool) AddRemotes(txs []*types.Transaction) error {
578+
return pool.addTxs(txs, false)
579+
}
580+
581+
// addTx enqueues a single transaction into the pool if it is valid.
582+
func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
565583
pool.mu.Lock()
566584
defer pool.mu.Unlock()
567585

568586
// Try to inject the transaction and update any state
569-
replace, err := pool.add(tx)
587+
replace, err := pool.add(tx, local)
570588
if err != nil {
571589
return err
572590
}
@@ -582,15 +600,15 @@ func (pool *TxPool) Add(tx *types.Transaction) error {
582600
return nil
583601
}
584602

585-
// AddBatch attempts to queue a batch of transactions.
586-
func (pool *TxPool) AddBatch(txs []*types.Transaction) error {
603+
// addTxs attempts to queue a batch of transactions if they are valid.
604+
func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) error {
587605
pool.mu.Lock()
588606
defer pool.mu.Unlock()
589607

590608
// Add the batch of transaction, tracking the accepted ones
591609
dirty := make(map[common.Address]struct{})
592610
for _, tx := range txs {
593-
if replace, err := pool.add(tx); err == nil {
611+
if replace, err := pool.add(tx, local); err == nil {
594612
if !replace {
595613
from, _ := types.Sender(pool.signer, tx) // already validated
596614
dirty[from] = struct{}{}
@@ -725,7 +743,7 @@ func (pool *TxPool) promoteExecutables(state *state.StateDB, accounts []common.A
725743
pool.promoteTx(addr, hash, tx)
726744
}
727745
// Drop all transactions over the allowed limit
728-
if !pool.locals.containsAddress(addr) {
746+
if !pool.locals.contains(addr) {
729747
for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
730748
hash := tx.Hash()
731749
delete(pool.all, hash)
@@ -752,7 +770,7 @@ func (pool *TxPool) promoteExecutables(state *state.StateDB, accounts []common.A
752770
spammers := prque.New()
753771
for addr, list := range pool.pending {
754772
// Only evict transactions from high rollers
755-
if !pool.locals.containsAddress(addr) && uint64(list.Len()) > pool.config.AccountSlots {
773+
if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
756774
spammers.Push(addr, float32(list.Len()))
757775
}
758776
}
@@ -818,7 +836,7 @@ func (pool *TxPool) promoteExecutables(state *state.StateDB, accounts []common.A
818836
addresses := make(addresssByHeartbeat, 0, len(pool.queue))
819837
for addr := range pool.queue {
820838
// Don't drop locals
821-
if !pool.locals.containsAddress(addr) {
839+
if !pool.locals.contains(addr) {
822840
addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
823841
}
824842
}
@@ -930,41 +948,38 @@ func (a addresssByHeartbeat) Len() int { return len(a) }
930948
func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
931949
func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
932950

933-
// accountSet is simply a map of addresses, and a signer, to be able
934-
// to determine the address from a tx
951+
// accountSet is simply a set of addresses to check for existance, and a signer
952+
// capable of deriving addresses from transactions.
935953
type accountSet struct {
936954
accounts map[common.Address]struct{}
937955
signer types.Signer
938956
}
939957

958+
// newAccountSet creates a new address set with an associated signer for sender
959+
// derivations.
940960
func newAccountSet(signer types.Signer) *accountSet {
941961
return &accountSet{
942962
accounts: make(map[common.Address]struct{}),
943963
signer: signer,
944964
}
945965
}
946966

947-
// containsAddress checks if a given address is within the set
948-
func (as *accountSet) containsAddress(address common.Address) bool {
949-
_, exist := as.accounts[address]
967+
// contains checks if a given address is contained within the set.
968+
func (as *accountSet) contains(addr common.Address) bool {
969+
_, exist := as.accounts[addr]
950970
return exist
951971
}
952972

953-
// contains checks if the sender of a given tx is within the set
954-
func (as *accountSet) contains(tx *types.Transaction) bool {
955-
if address, err := types.Sender(as.signer, tx); err == nil {
956-
return as.containsAddress(address)
973+
// containsTx checks if the sender of a given tx is within the set. If the sender
974+
// cannot be derived, this method returns false.
975+
func (as *accountSet) containsTx(tx *types.Transaction) bool {
976+
if addr, err := types.Sender(as.signer, tx); err == nil {
977+
return as.contains(addr)
957978
}
958979
return false
959980
}
960981

961-
// add a transaction sender to the set
962-
// if sender can't be derived, this is a no-op (no errors returned)
963-
func (as *accountSet) add(tx *types.Transaction) {
964-
if address, err := types.Sender(as.signer, tx); err == nil {
965-
if _, exist := as.accounts[address]; !exist {
966-
as.accounts[address] = struct{}{}
967-
}
968-
}
969-
982+
// add inserts a new address into the set to track.
983+
func (as *accountSet) add(addr common.Address) {
984+
as.accounts[addr] = struct{}{}
970985
}

0 commit comments

Comments
 (0)