github.com/unitedwallet/go-unitedcoin@v0.0.0-20210523075635-0ea21ffcca48/core/tx_pool.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package core 18 19 import ( 20 "errors" 21 "fmt" 22 "math" 23 "math/big" 24 "sort" 25 "sync" 26 "time" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/common/prque" 30 "github.com/ethereum/go-ethereum/core/state" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/event" 33 "github.com/ethereum/go-ethereum/log" 34 "github.com/ethereum/go-ethereum/metrics" 35 "github.com/ethereum/go-ethereum/params" 36 ) 37 38 const ( 39 // chainHeadChanSize is the size of channel listening to ChainHeadEvent. 40 chainHeadChanSize = 10 41 ) 42 43 var ( 44 // ErrInvalidSender is returned if the transaction contains an invalid signature. 45 ErrInvalidSender = errors.New("invalid sender") 46 47 // ErrNonceTooLow is returned if the nonce of a transaction is lower than the 48 // one present in the local chain. 49 ErrNonceTooLow = errors.New("nonce too low") 50 51 // ErrUnderpriced is returned if a transaction's gas price is below the minimum 52 // configured for the transaction pool. 53 ErrUnderpriced = errors.New("transaction underpriced") 54 55 // ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced 56 // with a different one without the required price bump. 57 ErrReplaceUnderpriced = errors.New("replacement transaction underpriced") 58 59 // ErrInsufficientFunds is returned if the total cost of executing a transaction 60 // is higher than the balance of the user's account. 61 ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value") 62 63 // ErrIntrinsicGas is returned if the transaction is specified to use less gas 64 // than required to start the invocation. 65 ErrIntrinsicGas = errors.New("intrinsic gas too low") 66 67 // ErrGasLimit is returned if a transaction's requested gas limit exceeds the 68 // maximum allowance of the current block. 69 ErrGasLimit = errors.New("exceeds block gas limit") 70 71 // ErrNegativeValue is a sanity error to ensure noone is able to specify a 72 // transaction with a negative value. 73 ErrNegativeValue = errors.New("negative value") 74 75 // ErrOversizedData is returned if the input data of a transaction is greater 76 // than some meaningful limit a user might use. This is not a consensus error 77 // making the transaction invalid, rather a DOS protection. 78 ErrOversizedData = errors.New("oversized data") 79 ) 80 81 var ( 82 evictionInterval = time.Minute // Time interval to check for evictable transactions 83 statsReportInterval = 8 * time.Second // Time interval to report transaction pool stats 84 ) 85 86 var ( 87 // Metrics for the pending pool 88 pendingDiscardMeter = metrics.NewRegisteredMeter("txpool/pending/discard", nil) 89 pendingReplaceMeter = metrics.NewRegisteredMeter("txpool/pending/replace", nil) 90 pendingRateLimitMeter = metrics.NewRegisteredMeter("txpool/pending/ratelimit", nil) // Dropped due to rate limiting 91 pendingNofundsMeter = metrics.NewRegisteredMeter("txpool/pending/nofunds", nil) // Dropped due to out-of-funds 92 93 // Metrics for the queued pool 94 queuedDiscardMeter = metrics.NewRegisteredMeter("txpool/queued/discard", nil) 95 queuedReplaceMeter = metrics.NewRegisteredMeter("txpool/queued/replace", nil) 96 queuedRateLimitMeter = metrics.NewRegisteredMeter("txpool/queued/ratelimit", nil) // Dropped due to rate limiting 97 queuedNofundsMeter = metrics.NewRegisteredMeter("txpool/queued/nofunds", nil) // Dropped due to out-of-funds 98 99 // General tx metrics 100 knownTxMeter = metrics.NewRegisteredMeter("txpool/known", nil) 101 validTxMeter = metrics.NewRegisteredMeter("txpool/valid", nil) 102 invalidTxMeter = metrics.NewRegisteredMeter("txpool/invalid", nil) 103 underpricedTxMeter = metrics.NewRegisteredMeter("txpool/underpriced", nil) 104 105 pendingGauge = metrics.NewRegisteredGauge("txpool/pending", nil) 106 queuedGauge = metrics.NewRegisteredGauge("txpool/queued", nil) 107 localGauge = metrics.NewRegisteredGauge("txpool/local", nil) 108 ) 109 110 // TxStatus is the current status of a transaction as seen by the pool. 111 type TxStatus uint 112 113 const ( 114 TxStatusUnknown TxStatus = iota 115 TxStatusQueued 116 TxStatusPending 117 TxStatusIncluded 118 ) 119 120 // blockChain provides the state of blockchain and current gas limit to do 121 // some pre checks in tx pool and event subscribers. 122 type blockChain interface { 123 CurrentBlock() *types.Block 124 GetBlock(hash common.Hash, number uint64) *types.Block 125 StateAt(root common.Hash) (*state.StateDB, error) 126 127 SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription 128 } 129 130 // TxPoolConfig are the configuration parameters of the transaction pool. 131 type TxPoolConfig struct { 132 Locals []common.Address // Addresses that should be treated by default as local 133 NoLocals bool // Whether local transaction handling should be disabled 134 Journal string // Journal of local transactions to survive node restarts 135 Rejournal time.Duration // Time interval to regenerate the local transaction journal 136 137 PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool 138 PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce) 139 140 AccountSlots uint64 // Number of executable transaction slots guaranteed per account 141 GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts 142 AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account 143 GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts 144 145 Lifetime time.Duration // Maximum amount of time non-executable transaction are queued 146 } 147 148 // DefaultTxPoolConfig contains the default configurations for the transaction 149 // pool. 150 var DefaultTxPoolConfig = TxPoolConfig{ 151 Journal: "transactions.rlp", 152 Rejournal: time.Hour, 153 154 PriceLimit: 1, 155 PriceBump: 10, 156 157 AccountSlots: 16, 158 GlobalSlots: 4096, 159 AccountQueue: 64, 160 GlobalQueue: 1024, 161 162 Lifetime: 3 * time.Hour, 163 } 164 165 // sanitize checks the provided user configurations and changes anything that's 166 // unreasonable or unworkable. 167 func (config *TxPoolConfig) sanitize() TxPoolConfig { 168 conf := *config 169 if conf.Rejournal < time.Second { 170 log.Warn("Sanitizing invalid txpool journal time", "provided", conf.Rejournal, "updated", time.Second) 171 conf.Rejournal = time.Second 172 } 173 if conf.PriceLimit < 1 { 174 log.Warn("Sanitizing invalid txpool price limit", "provided", conf.PriceLimit, "updated", DefaultTxPoolConfig.PriceLimit) 175 conf.PriceLimit = DefaultTxPoolConfig.PriceLimit 176 } 177 if conf.PriceBump < 1 { 178 log.Warn("Sanitizing invalid txpool price bump", "provided", conf.PriceBump, "updated", DefaultTxPoolConfig.PriceBump) 179 conf.PriceBump = DefaultTxPoolConfig.PriceBump 180 } 181 if conf.AccountSlots < 1 { 182 log.Warn("Sanitizing invalid txpool account slots", "provided", conf.AccountSlots, "updated", DefaultTxPoolConfig.AccountSlots) 183 conf.AccountSlots = DefaultTxPoolConfig.AccountSlots 184 } 185 if conf.GlobalSlots < 1 { 186 log.Warn("Sanitizing invalid txpool global slots", "provided", conf.GlobalSlots, "updated", DefaultTxPoolConfig.GlobalSlots) 187 conf.GlobalSlots = DefaultTxPoolConfig.GlobalSlots 188 } 189 if conf.AccountQueue < 1 { 190 log.Warn("Sanitizing invalid txpool account queue", "provided", conf.AccountQueue, "updated", DefaultTxPoolConfig.AccountQueue) 191 conf.AccountQueue = DefaultTxPoolConfig.AccountQueue 192 } 193 if conf.GlobalQueue < 1 { 194 log.Warn("Sanitizing invalid txpool global queue", "provided", conf.GlobalQueue, "updated", DefaultTxPoolConfig.GlobalQueue) 195 conf.GlobalQueue = DefaultTxPoolConfig.GlobalQueue 196 } 197 if conf.Lifetime < 1 { 198 log.Warn("Sanitizing invalid txpool lifetime", "provided", conf.Lifetime, "updated", DefaultTxPoolConfig.Lifetime) 199 conf.Lifetime = DefaultTxPoolConfig.Lifetime 200 } 201 return conf 202 } 203 204 // TxPool contains all currently known transactions. Transactions 205 // enter the pool when they are received from the network or submitted 206 // locally. They exit the pool when they are included in the blockchain. 207 // 208 // The pool separates processable transactions (which can be applied to the 209 // current state) and future transactions. Transactions move between those 210 // two states over time as they are received and processed. 211 type TxPool struct { 212 config TxPoolConfig 213 chainconfig *params.ChainConfig 214 chain blockChain 215 gasPrice *big.Int 216 txFeed event.Feed 217 scope event.SubscriptionScope 218 signer types.Signer 219 mu sync.RWMutex 220 221 istanbul bool // Fork indicator whether we are in the istanbul stage. 222 223 currentState *state.StateDB // Current state in the blockchain head 224 pendingNonces *txNoncer // Pending state tracking virtual nonces 225 currentMaxGas uint64 // Current gas limit for transaction caps 226 227 locals *accountSet // Set of local transaction to exempt from eviction rules 228 journal *txJournal // Journal of local transaction to back up to disk 229 230 pending map[common.Address]*txList // All currently processable transactions 231 queue map[common.Address]*txList // Queued but non-processable transactions 232 beats map[common.Address]time.Time // Last heartbeat from each known account 233 all *txLookup // All transactions to allow lookups 234 priced *txPricedList // All transactions sorted by price 235 236 chainHeadCh chan ChainHeadEvent 237 chainHeadSub event.Subscription 238 reqResetCh chan *txpoolResetRequest 239 reqPromoteCh chan *accountSet 240 queueTxEventCh chan *types.Transaction 241 reorgDoneCh chan chan struct{} 242 reorgShutdownCh chan struct{} // requests shutdown of scheduleReorgLoop 243 wg sync.WaitGroup // tracks loop, scheduleReorgLoop 244 } 245 246 type txpoolResetRequest struct { 247 oldHead, newHead *types.Header 248 } 249 250 // NewTxPool creates a new transaction pool to gather, sort and filter inbound 251 // transactions from the network. 252 func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool { 253 // Sanitize the input to ensure no vulnerable gas prices are set 254 config = (&config).sanitize() 255 256 // Create the transaction pool with its initial settings 257 pool := &TxPool{ 258 config: config, 259 chainconfig: chainconfig, 260 chain: chain, 261 signer: types.NewEIP155Signer(chainconfig.ChainID), 262 pending: make(map[common.Address]*txList), 263 queue: make(map[common.Address]*txList), 264 beats: make(map[common.Address]time.Time), 265 all: newTxLookup(), 266 chainHeadCh: make(chan ChainHeadEvent, chainHeadChanSize), 267 reqResetCh: make(chan *txpoolResetRequest), 268 reqPromoteCh: make(chan *accountSet), 269 queueTxEventCh: make(chan *types.Transaction), 270 reorgDoneCh: make(chan chan struct{}), 271 reorgShutdownCh: make(chan struct{}), 272 gasPrice: new(big.Int).SetUint64(config.PriceLimit), 273 } 274 pool.locals = newAccountSet(pool.signer) 275 for _, addr := range config.Locals { 276 log.Info("Setting new local account", "address", addr) 277 pool.locals.add(addr) 278 } 279 pool.priced = newTxPricedList(pool.all) 280 pool.reset(nil, chain.CurrentBlock().Header()) 281 282 // Start the reorg loop early so it can handle requests generated during journal loading. 283 pool.wg.Add(1) 284 go pool.scheduleReorgLoop() 285 286 // If local transactions and journaling is enabled, load from disk 287 if !config.NoLocals && config.Journal != "" { 288 pool.journal = newTxJournal(config.Journal) 289 290 if err := pool.journal.load(pool.AddLocals); err != nil { 291 log.Warn("Failed to load transaction journal", "err", err) 292 } 293 if err := pool.journal.rotate(pool.local()); err != nil { 294 log.Warn("Failed to rotate transaction journal", "err", err) 295 } 296 } 297 298 // Subscribe events from blockchain and start the main event loop. 299 pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh) 300 pool.wg.Add(1) 301 go pool.loop() 302 303 return pool 304 } 305 306 // loop is the transaction pool's main event loop, waiting for and reacting to 307 // outside blockchain events as well as for various reporting and transaction 308 // eviction events. 309 func (pool *TxPool) loop() { 310 defer pool.wg.Done() 311 312 var ( 313 prevPending, prevQueued, prevStales int 314 // Start the stats reporting and transaction eviction tickers 315 report = time.NewTicker(statsReportInterval) 316 evict = time.NewTicker(evictionInterval) 317 journal = time.NewTicker(pool.config.Rejournal) 318 // Track the previous head headers for transaction reorgs 319 head = pool.chain.CurrentBlock() 320 ) 321 defer report.Stop() 322 defer evict.Stop() 323 defer journal.Stop() 324 325 for { 326 select { 327 // Handle ChainHeadEvent 328 case ev := <-pool.chainHeadCh: 329 if ev.Block != nil { 330 pool.requestReset(head.Header(), ev.Block.Header()) 331 head = ev.Block 332 } 333 334 // System shutdown. 335 case <-pool.chainHeadSub.Err(): 336 close(pool.reorgShutdownCh) 337 return 338 339 // Handle stats reporting ticks 340 case <-report.C: 341 pool.mu.RLock() 342 pending, queued := pool.stats() 343 stales := pool.priced.stales 344 pool.mu.RUnlock() 345 346 if pending != prevPending || queued != prevQueued || stales != prevStales { 347 log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales) 348 prevPending, prevQueued, prevStales = pending, queued, stales 349 } 350 351 // Handle inactive account transaction eviction 352 case <-evict.C: 353 pool.mu.Lock() 354 for addr := range pool.queue { 355 // Skip local transactions from the eviction mechanism 356 if pool.locals.contains(addr) { 357 continue 358 } 359 // Any non-locals old enough should be removed 360 if time.Since(pool.beats[addr]) > pool.config.Lifetime { 361 for _, tx := range pool.queue[addr].Flatten() { 362 pool.removeTx(tx.Hash(), true) 363 } 364 } 365 } 366 pool.mu.Unlock() 367 368 // Handle local transaction journal rotation 369 case <-journal.C: 370 if pool.journal != nil { 371 pool.mu.Lock() 372 if err := pool.journal.rotate(pool.local()); err != nil { 373 log.Warn("Failed to rotate local tx journal", "err", err) 374 } 375 pool.mu.Unlock() 376 } 377 } 378 } 379 } 380 381 // Stop terminates the transaction pool. 382 func (pool *TxPool) Stop() { 383 // Unsubscribe all subscriptions registered from txpool 384 pool.scope.Close() 385 386 // Unsubscribe subscriptions registered from blockchain 387 pool.chainHeadSub.Unsubscribe() 388 pool.wg.Wait() 389 390 if pool.journal != nil { 391 pool.journal.close() 392 } 393 log.Info("Transaction pool stopped") 394 } 395 396 // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and 397 // starts sending event to the given channel. 398 func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription { 399 return pool.scope.Track(pool.txFeed.Subscribe(ch)) 400 } 401 402 // GasPrice returns the current gas price enforced by the transaction pool. 403 func (pool *TxPool) GasPrice() *big.Int { 404 pool.mu.RLock() 405 defer pool.mu.RUnlock() 406 407 return new(big.Int).Set(pool.gasPrice) 408 } 409 410 // SetGasPrice updates the minimum price required by the transaction pool for a 411 // new transaction, and drops all transactions below this threshold. 412 func (pool *TxPool) SetGasPrice(price *big.Int) { 413 pool.mu.Lock() 414 defer pool.mu.Unlock() 415 416 pool.gasPrice = price 417 for _, tx := range pool.priced.Cap(price, pool.locals) { 418 pool.removeTx(tx.Hash(), false) 419 } 420 log.Info("Transaction pool price threshold updated", "price", price) 421 } 422 423 // Nonce returns the next nonce of an account, with all transactions executable 424 // by the pool already applied on top. 425 func (pool *TxPool) Nonce(addr common.Address) uint64 { 426 pool.mu.RLock() 427 defer pool.mu.RUnlock() 428 429 return pool.pendingNonces.get(addr) 430 } 431 432 // Stats retrieves the current pool stats, namely the number of pending and the 433 // number of queued (non-executable) transactions. 434 func (pool *TxPool) Stats() (int, int) { 435 pool.mu.RLock() 436 defer pool.mu.RUnlock() 437 438 return pool.stats() 439 } 440 441 // stats retrieves the current pool stats, namely the number of pending and the 442 // number of queued (non-executable) transactions. 443 func (pool *TxPool) stats() (int, int) { 444 pending := 0 445 for _, list := range pool.pending { 446 pending += list.Len() 447 } 448 queued := 0 449 for _, list := range pool.queue { 450 queued += list.Len() 451 } 452 return pending, queued 453 } 454 455 // Content retrieves the data content of the transaction pool, returning all the 456 // pending as well as queued transactions, grouped by account and sorted by nonce. 457 func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) { 458 pool.mu.Lock() 459 defer pool.mu.Unlock() 460 461 pending := make(map[common.Address]types.Transactions) 462 for addr, list := range pool.pending { 463 pending[addr] = list.Flatten() 464 } 465 queued := make(map[common.Address]types.Transactions) 466 for addr, list := range pool.queue { 467 queued[addr] = list.Flatten() 468 } 469 return pending, queued 470 } 471 472 // Pending retrieves all currently processable transactions, grouped by origin 473 // account and sorted by nonce. The returned transaction set is a copy and can be 474 // freely modified by calling code. 475 func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) { 476 pool.mu.Lock() 477 defer pool.mu.Unlock() 478 479 pending := make(map[common.Address]types.Transactions) 480 for addr, list := range pool.pending { 481 pending[addr] = list.Flatten() 482 } 483 return pending, nil 484 } 485 486 // Locals retrieves the accounts currently considered local by the pool. 487 func (pool *TxPool) Locals() []common.Address { 488 pool.mu.Lock() 489 defer pool.mu.Unlock() 490 491 return pool.locals.flatten() 492 } 493 494 // local retrieves all currently known local transactions, grouped by origin 495 // account and sorted by nonce. The returned transaction set is a copy and can be 496 // freely modified by calling code. 497 func (pool *TxPool) local() map[common.Address]types.Transactions { 498 txs := make(map[common.Address]types.Transactions) 499 for addr := range pool.locals.accounts { 500 if pending := pool.pending[addr]; pending != nil { 501 txs[addr] = append(txs[addr], pending.Flatten()...) 502 } 503 if queued := pool.queue[addr]; queued != nil { 504 txs[addr] = append(txs[addr], queued.Flatten()...) 505 } 506 } 507 return txs 508 } 509 510 // validateTx checks whether a transaction is valid according to the consensus 511 // rules and adheres to some heuristic limits of the local node (price and size). 512 func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error { 513 // Heuristic limit, reject transactions over 32KB to prevent DOS attacks 514 //UnitedCoin To supported ten thousand tx for some high performance mining machine 515 //if tx.Size() > 32*1024 { 516 if tx.Size() > 32*1024*10 { 517 return ErrOversizedData 518 } 519 // Transactions can't be negative. This may never happen using RLP decoded 520 // transactions but may occur if you create a transaction using the RPC. 521 if tx.Value().Sign() < 0 { 522 return ErrNegativeValue 523 } 524 // Ensure the transaction doesn't exceed the current block limit gas. 525 if pool.currentMaxGas < tx.Gas() { 526 return ErrGasLimit 527 } 528 // Make sure the transaction is signed properly 529 from, err := types.Sender(pool.signer, tx) 530 if err != nil { 531 return ErrInvalidSender 532 } 533 // Drop non-local transactions under our own minimal accepted gas price 534 local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network 535 if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 { 536 return ErrUnderpriced 537 } 538 // Ensure the transaction adheres to nonce ordering 539 if pool.currentState.GetNonce(from) > tx.Nonce() { 540 return ErrNonceTooLow 541 } 542 // Transactor should have enough funds to cover the costs 543 // cost == V + GP * GL 544 if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 { 545 return ErrInsufficientFunds 546 } 547 // Ensure the transaction has more gas than the basic tx fee. 548 intrGas, err := IntrinsicGas(tx.Data(), tx.To() == nil, true, pool.istanbul) 549 if err != nil { 550 return err 551 } 552 if tx.Gas() < intrGas { 553 return ErrIntrinsicGas 554 } 555 return nil 556 } 557 558 // add validates a transaction and inserts it into the non-executable queue for later 559 // pending promotion and execution. If the transaction is a replacement for an already 560 // pending or queued one, it overwrites the previous transaction if its price is higher. 561 // 562 // If a newly added transaction is marked as local, its sending account will be 563 // whitelisted, preventing any associated transaction from being dropped out of the pool 564 // due to pricing constraints. 565 func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err error) { 566 // If the transaction is already known, discard it 567 hash := tx.Hash() 568 if pool.all.Get(hash) != nil { 569 log.Trace("Discarding already known transaction", "hash", hash) 570 knownTxMeter.Mark(1) 571 return false, fmt.Errorf("known transaction: %x", hash) 572 } 573 // If the transaction fails basic validation, discard it 574 if err := pool.validateTx(tx, local); err != nil { 575 log.Trace("Discarding invalid transaction", "hash", hash, "err", err) 576 invalidTxMeter.Mark(1) 577 return false, err 578 } 579 // If the transaction pool is full, discard underpriced transactions 580 if uint64(pool.all.Count()) >= pool.config.GlobalSlots+pool.config.GlobalQueue { 581 // If the new transaction is underpriced, don't accept it 582 if !local && pool.priced.Underpriced(tx, pool.locals) { 583 log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice()) 584 underpricedTxMeter.Mark(1) 585 return false, ErrUnderpriced 586 } 587 // New transaction is better than our worse ones, make room for it 588 drop := pool.priced.Discard(pool.all.Count()-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals) 589 for _, tx := range drop { 590 log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice()) 591 underpricedTxMeter.Mark(1) 592 pool.removeTx(tx.Hash(), false) 593 } 594 } 595 // Try to replace an existing transaction in the pending pool 596 from, _ := types.Sender(pool.signer, tx) // already validated 597 if list := pool.pending[from]; list != nil && list.Overlaps(tx) { 598 // Nonce already pending, check if required price bump is met 599 inserted, old := list.Add(tx, pool.config.PriceBump) 600 if !inserted { 601 pendingDiscardMeter.Mark(1) 602 return false, ErrReplaceUnderpriced 603 } 604 // New transaction is better, replace old one 605 if old != nil { 606 pool.all.Remove(old.Hash()) 607 pool.priced.Removed(1) 608 pendingReplaceMeter.Mark(1) 609 } 610 pool.all.Add(tx) 611 pool.priced.Put(tx) 612 pool.journalTx(from, tx) 613 pool.queueTxEvent(tx) 614 log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To()) 615 return old != nil, nil 616 } 617 // New transaction isn't replacing a pending one, push into queue 618 replaced, err = pool.enqueueTx(hash, tx) 619 if err != nil { 620 return false, err 621 } 622 // Mark local addresses and journal local transactions 623 if local { 624 if !pool.locals.contains(from) { 625 log.Info("Setting new local account", "address", from) 626 pool.locals.add(from) 627 } 628 } 629 if local || pool.locals.contains(from) { 630 localGauge.Inc(1) 631 } 632 pool.journalTx(from, tx) 633 634 log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To()) 635 return replaced, nil 636 } 637 638 // enqueueTx inserts a new transaction into the non-executable transaction queue. 639 // 640 // Note, this method assumes the pool lock is held! 641 func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) { 642 // Try to insert the transaction into the future queue 643 from, _ := types.Sender(pool.signer, tx) // already validated 644 if pool.queue[from] == nil { 645 pool.queue[from] = newTxList(false) 646 } 647 inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump) 648 if !inserted { 649 // An older transaction was better, discard this 650 queuedDiscardMeter.Mark(1) 651 return false, ErrReplaceUnderpriced 652 } 653 // Discard any previous transaction and mark this 654 if old != nil { 655 pool.all.Remove(old.Hash()) 656 pool.priced.Removed(1) 657 queuedReplaceMeter.Mark(1) 658 } else { 659 // Nothing was replaced, bump the queued counter 660 queuedGauge.Inc(1) 661 } 662 if pool.all.Get(hash) == nil { 663 pool.all.Add(tx) 664 pool.priced.Put(tx) 665 } 666 return old != nil, nil 667 } 668 669 // journalTx adds the specified transaction to the local disk journal if it is 670 // deemed to have been sent from a local account. 671 func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) { 672 // Only journal if it's enabled and the transaction is local 673 if pool.journal == nil || !pool.locals.contains(from) { 674 return 675 } 676 if err := pool.journal.insert(tx); err != nil { 677 log.Warn("Failed to journal local transaction", "err", err) 678 } 679 } 680 681 // promoteTx adds a transaction to the pending (processable) list of transactions 682 // and returns whether it was inserted or an older was better. 683 // 684 // Note, this method assumes the pool lock is held! 685 func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool { 686 // Try to insert the transaction into the pending queue 687 if pool.pending[addr] == nil { 688 pool.pending[addr] = newTxList(true) 689 } 690 list := pool.pending[addr] 691 692 inserted, old := list.Add(tx, pool.config.PriceBump) 693 if !inserted { 694 // An older transaction was better, discard this 695 pool.all.Remove(hash) 696 pool.priced.Removed(1) 697 698 pendingDiscardMeter.Mark(1) 699 return false 700 } 701 // Otherwise discard any previous transaction and mark this 702 if old != nil { 703 pool.all.Remove(old.Hash()) 704 pool.priced.Removed(1) 705 706 pendingReplaceMeter.Mark(1) 707 } else { 708 // Nothing was replaced, bump the pending counter 709 pendingGauge.Inc(1) 710 } 711 // Failsafe to work around direct pending inserts (tests) 712 if pool.all.Get(hash) == nil { 713 pool.all.Add(tx) 714 pool.priced.Put(tx) 715 } 716 // Set the potentially new pending nonce and notify any subsystems of the new tx 717 pool.beats[addr] = time.Now() 718 pool.pendingNonces.set(addr, tx.Nonce()+1) 719 720 return true 721 } 722 723 // AddLocals enqueues a batch of transactions into the pool if they are valid, marking the 724 // senders as a local ones, ensuring they go around the local pricing constraints. 725 // 726 // This method is used to add transactions from the RPC API and performs synchronous pool 727 // reorganization and event propagation. 728 func (pool *TxPool) AddLocals(txs []*types.Transaction) []error { 729 return pool.addTxs(txs, !pool.config.NoLocals, true) 730 } 731 732 // AddLocal enqueues a single local transaction into the pool if it is valid. This is 733 // a convenience wrapper aroundd AddLocals. 734 func (pool *TxPool) AddLocal(tx *types.Transaction) error { 735 errs := pool.AddLocals([]*types.Transaction{tx}) 736 return errs[0] 737 } 738 739 // AddRemotes enqueues a batch of transactions into the pool if they are valid. If the 740 // senders are not among the locally tracked ones, full pricing constraints will apply. 741 // 742 // This method is used to add transactions from the p2p network and does not wait for pool 743 // reorganization and internal event propagation. 744 func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error { 745 return pool.addTxs(txs, false, false) 746 } 747 748 // This is like AddRemotes, but waits for pool reorganization. Tests use this method. 749 func (pool *TxPool) AddRemotesSync(txs []*types.Transaction) []error { 750 return pool.addTxs(txs, false, true) 751 } 752 753 // This is like AddRemotes with a single transaction, but waits for pool reorganization. Tests use this method. 754 func (pool *TxPool) addRemoteSync(tx *types.Transaction) error { 755 errs := pool.AddRemotesSync([]*types.Transaction{tx}) 756 return errs[0] 757 } 758 759 // AddRemote enqueues a single transaction into the pool if it is valid. This is a convenience 760 // wrapper around AddRemotes. 761 // 762 // Deprecated: use AddRemotes 763 func (pool *TxPool) AddRemote(tx *types.Transaction) error { 764 errs := pool.AddRemotes([]*types.Transaction{tx}) 765 return errs[0] 766 } 767 768 // addTxs attempts to queue a batch of transactions if they are valid. 769 func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error { 770 // Filter out known ones without obtaining the pool lock or recovering signatures 771 var ( 772 errs = make([]error, len(txs)) 773 news = make([]*types.Transaction, 0, len(txs)) 774 ) 775 for i, tx := range txs { 776 // If the transaction is known, pre-set the error slot 777 if pool.all.Get(tx.Hash()) != nil { 778 errs[i] = fmt.Errorf("known transaction: %x", tx.Hash()) 779 knownTxMeter.Mark(1) 780 continue 781 } 782 // Accumulate all unknown transactions for deeper processing 783 news = append(news, tx) 784 } 785 if len(news) == 0 { 786 return errs 787 } 788 // Cache senders in transactions before obtaining lock (pool.signer is immutable) 789 for _, tx := range news { 790 types.Sender(pool.signer, tx) 791 } 792 // Process all the new transaction and merge any errors into the original slice 793 pool.mu.Lock() 794 newErrs, dirtyAddrs := pool.addTxsLocked(news, local) 795 pool.mu.Unlock() 796 797 var nilSlot = 0 798 for _, err := range newErrs { 799 for errs[nilSlot] != nil { 800 nilSlot++ 801 } 802 errs[nilSlot] = err 803 } 804 // Reorg the pool internals if needed and return 805 done := pool.requestPromoteExecutables(dirtyAddrs) 806 if sync { 807 <-done 808 } 809 return errs 810 } 811 812 // addTxsLocked attempts to queue a batch of transactions if they are valid. 813 // The transaction pool lock must be held. 814 func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) ([]error, *accountSet) { 815 dirty := newAccountSet(pool.signer) 816 errs := make([]error, len(txs)) 817 for i, tx := range txs { 818 replaced, err := pool.add(tx, local) 819 errs[i] = err 820 if err == nil && !replaced { 821 dirty.addTx(tx) 822 } 823 } 824 validTxMeter.Mark(int64(len(dirty.accounts))) 825 return errs, dirty 826 } 827 828 // Status returns the status (unknown/pending/queued) of a batch of transactions 829 // identified by their hashes. 830 func (pool *TxPool) Status(hashes []common.Hash) []TxStatus { 831 status := make([]TxStatus, len(hashes)) 832 for i, hash := range hashes { 833 tx := pool.Get(hash) 834 if tx == nil { 835 continue 836 } 837 from, _ := types.Sender(pool.signer, tx) // already validated 838 pool.mu.RLock() 839 if txList := pool.pending[from]; txList != nil && txList.txs.items[tx.Nonce()] != nil { 840 status[i] = TxStatusPending 841 } else if txList := pool.queue[from]; txList != nil && txList.txs.items[tx.Nonce()] != nil { 842 status[i] = TxStatusQueued 843 } 844 // implicit else: the tx may have been included into a block between 845 // checking pool.Get and obtaining the lock. In that case, TxStatusUnknown is correct 846 pool.mu.RUnlock() 847 } 848 return status 849 } 850 851 // Get returns a transaction if it is contained in the pool and nil otherwise. 852 func (pool *TxPool) Get(hash common.Hash) *types.Transaction { 853 return pool.all.Get(hash) 854 } 855 856 // removeTx removes a single transaction from the queue, moving all subsequent 857 // transactions back to the future queue. 858 func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) { 859 // Fetch the transaction we wish to delete 860 tx := pool.all.Get(hash) 861 if tx == nil { 862 return 863 } 864 addr, _ := types.Sender(pool.signer, tx) // already validated during insertion 865 866 // Remove it from the list of known transactions 867 pool.all.Remove(hash) 868 if outofbound { 869 pool.priced.Removed(1) 870 } 871 if pool.locals.contains(addr) { 872 localGauge.Dec(1) 873 } 874 // Remove the transaction from the pending lists and reset the account nonce 875 if pending := pool.pending[addr]; pending != nil { 876 if removed, invalids := pending.Remove(tx); removed { 877 // If no more pending transactions are left, remove the list 878 if pending.Empty() { 879 delete(pool.pending, addr) 880 delete(pool.beats, addr) 881 } 882 // Postpone any invalidated transactions 883 for _, tx := range invalids { 884 pool.enqueueTx(tx.Hash(), tx) 885 } 886 // Update the account nonce if needed 887 pool.pendingNonces.setIfLower(addr, tx.Nonce()) 888 // Reduce the pending counter 889 pendingGauge.Dec(int64(1 + len(invalids))) 890 return 891 } 892 } 893 // Transaction is in the future queue 894 if future := pool.queue[addr]; future != nil { 895 if removed, _ := future.Remove(tx); removed { 896 // Reduce the queued counter 897 queuedGauge.Dec(1) 898 } 899 if future.Empty() { 900 delete(pool.queue, addr) 901 } 902 } 903 } 904 905 // requestPromoteExecutables requests a pool reset to the new head block. 906 // The returned channel is closed when the reset has occurred. 907 func (pool *TxPool) requestReset(oldHead *types.Header, newHead *types.Header) chan struct{} { 908 select { 909 case pool.reqResetCh <- &txpoolResetRequest{oldHead, newHead}: 910 return <-pool.reorgDoneCh 911 case <-pool.reorgShutdownCh: 912 return pool.reorgShutdownCh 913 } 914 } 915 916 // requestPromoteExecutables requests transaction promotion checks for the given addresses. 917 // The returned channel is closed when the promotion checks have occurred. 918 func (pool *TxPool) requestPromoteExecutables(set *accountSet) chan struct{} { 919 select { 920 case pool.reqPromoteCh <- set: 921 return <-pool.reorgDoneCh 922 case <-pool.reorgShutdownCh: 923 return pool.reorgShutdownCh 924 } 925 } 926 927 // queueTxEvent enqueues a transaction event to be sent in the next reorg run. 928 func (pool *TxPool) queueTxEvent(tx *types.Transaction) { 929 select { 930 case pool.queueTxEventCh <- tx: 931 case <-pool.reorgShutdownCh: 932 } 933 } 934 935 // scheduleReorgLoop schedules runs of reset and promoteExecutables. Code above should not 936 // call those methods directly, but request them being run using requestReset and 937 // requestPromoteExecutables instead. 938 func (pool *TxPool) scheduleReorgLoop() { 939 defer pool.wg.Done() 940 941 var ( 942 curDone chan struct{} // non-nil while runReorg is active 943 nextDone = make(chan struct{}) 944 launchNextRun bool 945 reset *txpoolResetRequest 946 dirtyAccounts *accountSet 947 queuedEvents = make(map[common.Address]*txSortedMap) 948 ) 949 for { 950 // Launch next background reorg if needed 951 if curDone == nil && launchNextRun { 952 // Run the background reorg and announcements 953 go pool.runReorg(nextDone, reset, dirtyAccounts, queuedEvents) 954 955 // Prepare everything for the next round of reorg 956 curDone, nextDone = nextDone, make(chan struct{}) 957 launchNextRun = false 958 959 reset, dirtyAccounts = nil, nil 960 queuedEvents = make(map[common.Address]*txSortedMap) 961 } 962 963 select { 964 case req := <-pool.reqResetCh: 965 // Reset request: update head if request is already pending. 966 if reset == nil { 967 reset = req 968 } else { 969 reset.newHead = req.newHead 970 } 971 launchNextRun = true 972 pool.reorgDoneCh <- nextDone 973 974 case req := <-pool.reqPromoteCh: 975 // Promote request: update address set if request is already pending. 976 if dirtyAccounts == nil { 977 dirtyAccounts = req 978 } else { 979 dirtyAccounts.merge(req) 980 } 981 launchNextRun = true 982 pool.reorgDoneCh <- nextDone 983 984 case tx := <-pool.queueTxEventCh: 985 // Queue up the event, but don't schedule a reorg. It's up to the caller to 986 // request one later if they want the events sent. 987 addr, _ := types.Sender(pool.signer, tx) 988 if _, ok := queuedEvents[addr]; !ok { 989 queuedEvents[addr] = newTxSortedMap() 990 } 991 queuedEvents[addr].Put(tx) 992 993 case <-curDone: 994 curDone = nil 995 996 case <-pool.reorgShutdownCh: 997 // Wait for current run to finish. 998 if curDone != nil { 999 <-curDone 1000 } 1001 close(nextDone) 1002 return 1003 } 1004 } 1005 } 1006 1007 // runReorg runs reset and promoteExecutables on behalf of scheduleReorgLoop. 1008 func (pool *TxPool) runReorg(done chan struct{}, reset *txpoolResetRequest, dirtyAccounts *accountSet, events map[common.Address]*txSortedMap) { 1009 defer close(done) 1010 1011 var promoteAddrs []common.Address 1012 if dirtyAccounts != nil { 1013 promoteAddrs = dirtyAccounts.flatten() 1014 } 1015 pool.mu.Lock() 1016 if reset != nil { 1017 // Reset from the old head to the new, rescheduling any reorged transactions 1018 pool.reset(reset.oldHead, reset.newHead) 1019 1020 // Nonces were reset, discard any events that became stale 1021 for addr := range events { 1022 events[addr].Forward(pool.pendingNonces.get(addr)) 1023 if events[addr].Len() == 0 { 1024 delete(events, addr) 1025 } 1026 } 1027 // Reset needs promote for all addresses 1028 promoteAddrs = promoteAddrs[:0] 1029 for addr := range pool.queue { 1030 promoteAddrs = append(promoteAddrs, addr) 1031 } 1032 } 1033 // Check for pending transactions for every account that sent new ones 1034 promoted := pool.promoteExecutables(promoteAddrs) 1035 for _, tx := range promoted { 1036 addr, _ := types.Sender(pool.signer, tx) 1037 if _, ok := events[addr]; !ok { 1038 events[addr] = newTxSortedMap() 1039 } 1040 events[addr].Put(tx) 1041 } 1042 // If a new block appeared, validate the pool of pending transactions. This will 1043 // remove any transaction that has been included in the block or was invalidated 1044 // because of another transaction (e.g. higher gas price). 1045 if reset != nil { 1046 pool.demoteUnexecutables() 1047 } 1048 // Ensure pool.queue and pool.pending sizes stay within the configured limits. 1049 pool.truncatePending() 1050 pool.truncateQueue() 1051 1052 // Update all accounts to the latest known pending nonce 1053 for addr, list := range pool.pending { 1054 txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway 1055 pool.pendingNonces.set(addr, txs[len(txs)-1].Nonce()+1) 1056 } 1057 pool.mu.Unlock() 1058 1059 // Notify subsystems for newly added transactions 1060 if len(events) > 0 { 1061 var txs []*types.Transaction 1062 for _, set := range events { 1063 txs = append(txs, set.Flatten()...) 1064 } 1065 pool.txFeed.Send(NewTxsEvent{txs}) 1066 } 1067 } 1068 1069 // reset retrieves the current state of the blockchain and ensures the content 1070 // of the transaction pool is valid with regard to the chain state. 1071 func (pool *TxPool) reset(oldHead, newHead *types.Header) { 1072 // If we're reorging an old state, reinject all dropped transactions 1073 var reinject types.Transactions 1074 1075 if oldHead != nil && oldHead.Hash() != newHead.ParentHash { 1076 // If the reorg is too deep, avoid doing it (will happen during fast sync) 1077 oldNum := oldHead.Number.Uint64() 1078 newNum := newHead.Number.Uint64() 1079 1080 if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 { 1081 log.Debug("Skipping deep transaction reorg", "depth", depth) 1082 } else { 1083 // Reorg seems shallow enough to pull in all transactions into memory 1084 var discarded, included types.Transactions 1085 var ( 1086 rem = pool.chain.GetBlock(oldHead.Hash(), oldHead.Number.Uint64()) 1087 add = pool.chain.GetBlock(newHead.Hash(), newHead.Number.Uint64()) 1088 ) 1089 if rem == nil { 1090 // This can happen if a setHead is performed, where we simply discard the old 1091 // head from the chain. 1092 // If that is the case, we don't have the lost transactions any more, and 1093 // there's nothing to add 1094 if newNum < oldNum { 1095 // If the reorg ended up on a lower number, it's indicative of setHead being the cause 1096 log.Debug("Skipping transaction reset caused by setHead", 1097 "old", oldHead.Hash(), "oldnum", oldNum, "new", newHead.Hash(), "newnum", newNum) 1098 } else { 1099 // If we reorged to a same or higher number, then it's not a case of setHead 1100 log.Warn("Transaction pool reset with missing oldhead", 1101 "old", oldHead.Hash(), "oldnum", oldNum, "new", newHead.Hash(), "newnum", newNum) 1102 } 1103 return 1104 } 1105 for rem.NumberU64() > add.NumberU64() { 1106 discarded = append(discarded, rem.Transactions()...) 1107 if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil { 1108 log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash()) 1109 return 1110 } 1111 } 1112 for add.NumberU64() > rem.NumberU64() { 1113 included = append(included, add.Transactions()...) 1114 if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil { 1115 log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash()) 1116 return 1117 } 1118 } 1119 for rem.Hash() != add.Hash() { 1120 discarded = append(discarded, rem.Transactions()...) 1121 if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil { 1122 log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash()) 1123 return 1124 } 1125 included = append(included, add.Transactions()...) 1126 if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil { 1127 log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash()) 1128 return 1129 } 1130 } 1131 reinject = types.TxDifference(discarded, included) 1132 } 1133 } 1134 // Initialize the internal state to the current head 1135 if newHead == nil { 1136 newHead = pool.chain.CurrentBlock().Header() // Special case during testing 1137 } 1138 statedb, err := pool.chain.StateAt(newHead.Root) 1139 if err != nil { 1140 log.Error("Failed to reset txpool state", "err", err) 1141 return 1142 } 1143 pool.currentState = statedb 1144 pool.pendingNonces = newTxNoncer(statedb) 1145 pool.currentMaxGas = newHead.GasLimit 1146 1147 // Inject any transactions discarded due to reorgs 1148 log.Debug("Reinjecting stale transactions", "count", len(reinject)) 1149 senderCacher.recover(pool.signer, reinject) 1150 pool.addTxsLocked(reinject, false) 1151 1152 // Update all fork indicator by next pending block number. 1153 next := new(big.Int).Add(newHead.Number, big.NewInt(1)) 1154 pool.istanbul = pool.chainconfig.IsIstanbul(next) 1155 } 1156 1157 // promoteExecutables moves transactions that have become processable from the 1158 // future queue to the set of pending transactions. During this process, all 1159 // invalidated transactions (low nonce, low balance) are deleted. 1160 func (pool *TxPool) promoteExecutables(accounts []common.Address) []*types.Transaction { 1161 // Track the promoted transactions to broadcast them at once 1162 var promoted []*types.Transaction 1163 1164 // Iterate over all accounts and promote any executable transactions 1165 for _, addr := range accounts { 1166 list := pool.queue[addr] 1167 if list == nil { 1168 continue // Just in case someone calls with a non existing account 1169 } 1170 // Drop all transactions that are deemed too old (low nonce) 1171 forwards := list.Forward(pool.currentState.GetNonce(addr)) 1172 for _, tx := range forwards { 1173 hash := tx.Hash() 1174 pool.all.Remove(hash) 1175 log.Trace("Removed old queued transaction", "hash", hash) 1176 } 1177 // Drop all transactions that are too costly (low balance or out of gas) 1178 drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas) 1179 for _, tx := range drops { 1180 hash := tx.Hash() 1181 pool.all.Remove(hash) 1182 log.Trace("Removed unpayable queued transaction", "hash", hash) 1183 } 1184 queuedNofundsMeter.Mark(int64(len(drops))) 1185 1186 // Gather all executable transactions and promote them 1187 readies := list.Ready(pool.pendingNonces.get(addr)) 1188 for _, tx := range readies { 1189 hash := tx.Hash() 1190 if pool.promoteTx(addr, hash, tx) { 1191 log.Trace("Promoting queued transaction", "hash", hash) 1192 promoted = append(promoted, tx) 1193 } 1194 } 1195 queuedGauge.Dec(int64(len(readies))) 1196 1197 // Drop all transactions over the allowed limit 1198 var caps types.Transactions 1199 if !pool.locals.contains(addr) { 1200 caps = list.Cap(int(pool.config.AccountQueue)) 1201 for _, tx := range caps { 1202 hash := tx.Hash() 1203 pool.all.Remove(hash) 1204 log.Trace("Removed cap-exceeding queued transaction", "hash", hash) 1205 } 1206 queuedRateLimitMeter.Mark(int64(len(caps))) 1207 } 1208 // Mark all the items dropped as removed 1209 pool.priced.Removed(len(forwards) + len(drops) + len(caps)) 1210 queuedGauge.Dec(int64(len(forwards) + len(drops) + len(caps))) 1211 if pool.locals.contains(addr) { 1212 localGauge.Dec(int64(len(forwards) + len(drops) + len(caps))) 1213 } 1214 // Delete the entire queue entry if it became empty. 1215 if list.Empty() { 1216 delete(pool.queue, addr) 1217 } 1218 } 1219 return promoted 1220 } 1221 1222 // truncatePending removes transactions from the pending queue if the pool is above the 1223 // pending limit. The algorithm tries to reduce transaction counts by an approximately 1224 // equal number for all for accounts with many pending transactions. 1225 func (pool *TxPool) truncatePending() { 1226 pending := uint64(0) 1227 for _, list := range pool.pending { 1228 pending += uint64(list.Len()) 1229 } 1230 if pending <= pool.config.GlobalSlots { 1231 return 1232 } 1233 1234 pendingBeforeCap := pending 1235 // Assemble a spam order to penalize large transactors first 1236 spammers := prque.New(nil) 1237 for addr, list := range pool.pending { 1238 // Only evict transactions from high rollers 1239 if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots { 1240 spammers.Push(addr, int64(list.Len())) 1241 } 1242 } 1243 // Gradually drop transactions from offenders 1244 offenders := []common.Address{} 1245 for pending > pool.config.GlobalSlots && !spammers.Empty() { 1246 // Retrieve the next offender if not local address 1247 offender, _ := spammers.Pop() 1248 offenders = append(offenders, offender.(common.Address)) 1249 1250 // Equalize balances until all the same or below threshold 1251 if len(offenders) > 1 { 1252 // Calculate the equalization threshold for all current offenders 1253 threshold := pool.pending[offender.(common.Address)].Len() 1254 1255 // Iteratively reduce all offenders until below limit or threshold reached 1256 for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold { 1257 for i := 0; i < len(offenders)-1; i++ { 1258 list := pool.pending[offenders[i]] 1259 1260 caps := list.Cap(list.Len() - 1) 1261 for _, tx := range caps { 1262 // Drop the transaction from the global pools too 1263 hash := tx.Hash() 1264 pool.all.Remove(hash) 1265 1266 // Update the account nonce to the dropped transaction 1267 pool.pendingNonces.setIfLower(offenders[i], tx.Nonce()) 1268 log.Trace("Removed fairness-exceeding pending transaction", "hash", hash) 1269 } 1270 pool.priced.Removed(len(caps)) 1271 pendingGauge.Dec(int64(len(caps))) 1272 if pool.locals.contains(offenders[i]) { 1273 localGauge.Dec(int64(len(caps))) 1274 } 1275 pending-- 1276 } 1277 } 1278 } 1279 } 1280 1281 // If still above threshold, reduce to limit or min allowance 1282 if pending > pool.config.GlobalSlots && len(offenders) > 0 { 1283 for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots { 1284 for _, addr := range offenders { 1285 list := pool.pending[addr] 1286 1287 caps := list.Cap(list.Len() - 1) 1288 for _, tx := range caps { 1289 // Drop the transaction from the global pools too 1290 hash := tx.Hash() 1291 pool.all.Remove(hash) 1292 1293 // Update the account nonce to the dropped transaction 1294 pool.pendingNonces.setIfLower(addr, tx.Nonce()) 1295 log.Trace("Removed fairness-exceeding pending transaction", "hash", hash) 1296 } 1297 pool.priced.Removed(len(caps)) 1298 pendingGauge.Dec(int64(len(caps))) 1299 if pool.locals.contains(addr) { 1300 localGauge.Dec(int64(len(caps))) 1301 } 1302 pending-- 1303 } 1304 } 1305 } 1306 pendingRateLimitMeter.Mark(int64(pendingBeforeCap - pending)) 1307 } 1308 1309 // truncateQueue drops the oldes transactions in the queue if the pool is above the global queue limit. 1310 func (pool *TxPool) truncateQueue() { 1311 queued := uint64(0) 1312 for _, list := range pool.queue { 1313 queued += uint64(list.Len()) 1314 } 1315 if queued <= pool.config.GlobalQueue { 1316 return 1317 } 1318 1319 // Sort all accounts with queued transactions by heartbeat 1320 addresses := make(addressesByHeartbeat, 0, len(pool.queue)) 1321 for addr := range pool.queue { 1322 if !pool.locals.contains(addr) { // don't drop locals 1323 addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]}) 1324 } 1325 } 1326 sort.Sort(addresses) 1327 1328 // Drop transactions until the total is below the limit or only locals remain 1329 for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; { 1330 addr := addresses[len(addresses)-1] 1331 list := pool.queue[addr.address] 1332 1333 addresses = addresses[:len(addresses)-1] 1334 1335 // Drop all transactions if they are less than the overflow 1336 if size := uint64(list.Len()); size <= drop { 1337 for _, tx := range list.Flatten() { 1338 pool.removeTx(tx.Hash(), true) 1339 } 1340 drop -= size 1341 queuedRateLimitMeter.Mark(int64(size)) 1342 continue 1343 } 1344 // Otherwise drop only last few transactions 1345 txs := list.Flatten() 1346 for i := len(txs) - 1; i >= 0 && drop > 0; i-- { 1347 pool.removeTx(txs[i].Hash(), true) 1348 drop-- 1349 queuedRateLimitMeter.Mark(1) 1350 } 1351 } 1352 } 1353 1354 // demoteUnexecutables removes invalid and processed transactions from the pools 1355 // executable/pending queue and any subsequent transactions that become unexecutable 1356 // are moved back into the future queue. 1357 func (pool *TxPool) demoteUnexecutables() { 1358 // Iterate over all accounts and demote any non-executable transactions 1359 for addr, list := range pool.pending { 1360 nonce := pool.currentState.GetNonce(addr) 1361 1362 // Drop all transactions that are deemed too old (low nonce) 1363 olds := list.Forward(nonce) 1364 for _, tx := range olds { 1365 hash := tx.Hash() 1366 pool.all.Remove(hash) 1367 log.Trace("Removed old pending transaction", "hash", hash) 1368 } 1369 // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later 1370 drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas) 1371 for _, tx := range drops { 1372 hash := tx.Hash() 1373 log.Trace("Removed unpayable pending transaction", "hash", hash) 1374 pool.all.Remove(hash) 1375 } 1376 pool.priced.Removed(len(olds) + len(drops)) 1377 pendingNofundsMeter.Mark(int64(len(drops))) 1378 1379 for _, tx := range invalids { 1380 hash := tx.Hash() 1381 log.Trace("Demoting pending transaction", "hash", hash) 1382 pool.enqueueTx(hash, tx) 1383 } 1384 pendingGauge.Dec(int64(len(olds) + len(drops) + len(invalids))) 1385 if pool.locals.contains(addr) { 1386 localGauge.Dec(int64(len(olds) + len(drops) + len(invalids))) 1387 } 1388 // If there's a gap in front, alert (should never happen) and postpone all transactions 1389 if list.Len() > 0 && list.txs.Get(nonce) == nil { 1390 gapped := list.Cap(0) 1391 for _, tx := range gapped { 1392 hash := tx.Hash() 1393 log.Error("Demoting invalidated transaction", "hash", hash) 1394 pool.enqueueTx(hash, tx) 1395 } 1396 pendingGauge.Dec(int64(len(gapped))) 1397 } 1398 // Delete the entire queue entry if it became empty. 1399 if list.Empty() { 1400 delete(pool.pending, addr) 1401 delete(pool.beats, addr) 1402 } 1403 } 1404 } 1405 1406 // addressByHeartbeat is an account address tagged with its last activity timestamp. 1407 type addressByHeartbeat struct { 1408 address common.Address 1409 heartbeat time.Time 1410 } 1411 1412 type addressesByHeartbeat []addressByHeartbeat 1413 1414 func (a addressesByHeartbeat) Len() int { return len(a) } 1415 func (a addressesByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) } 1416 func (a addressesByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 1417 1418 // accountSet is simply a set of addresses to check for existence, and a signer 1419 // capable of deriving addresses from transactions. 1420 type accountSet struct { 1421 accounts map[common.Address]struct{} 1422 signer types.Signer 1423 cache *[]common.Address 1424 } 1425 1426 // newAccountSet creates a new address set with an associated signer for sender 1427 // derivations. 1428 func newAccountSet(signer types.Signer, addrs ...common.Address) *accountSet { 1429 as := &accountSet{ 1430 accounts: make(map[common.Address]struct{}), 1431 signer: signer, 1432 } 1433 for _, addr := range addrs { 1434 as.add(addr) 1435 } 1436 return as 1437 } 1438 1439 // contains checks if a given address is contained within the set. 1440 func (as *accountSet) contains(addr common.Address) bool { 1441 _, exist := as.accounts[addr] 1442 return exist 1443 } 1444 1445 // containsTx checks if the sender of a given tx is within the set. If the sender 1446 // cannot be derived, this method returns false. 1447 func (as *accountSet) containsTx(tx *types.Transaction) bool { 1448 if addr, err := types.Sender(as.signer, tx); err == nil { 1449 return as.contains(addr) 1450 } 1451 return false 1452 } 1453 1454 // add inserts a new address into the set to track. 1455 func (as *accountSet) add(addr common.Address) { 1456 as.accounts[addr] = struct{}{} 1457 as.cache = nil 1458 } 1459 1460 // addTx adds the sender of tx into the set. 1461 func (as *accountSet) addTx(tx *types.Transaction) { 1462 if addr, err := types.Sender(as.signer, tx); err == nil { 1463 as.add(addr) 1464 } 1465 } 1466 1467 // flatten returns the list of addresses within this set, also caching it for later 1468 // reuse. The returned slice should not be changed! 1469 func (as *accountSet) flatten() []common.Address { 1470 if as.cache == nil { 1471 accounts := make([]common.Address, 0, len(as.accounts)) 1472 for account := range as.accounts { 1473 accounts = append(accounts, account) 1474 } 1475 as.cache = &accounts 1476 } 1477 return *as.cache 1478 } 1479 1480 // merge adds all addresses from the 'other' set into 'as'. 1481 func (as *accountSet) merge(other *accountSet) { 1482 for addr := range other.accounts { 1483 as.accounts[addr] = struct{}{} 1484 } 1485 as.cache = nil 1486 } 1487 1488 // txLookup is used internally by TxPool to track transactions while allowing lookup without 1489 // mutex contention. 1490 // 1491 // Note, although this type is properly protected against concurrent access, it 1492 // is **not** a type that should ever be mutated or even exposed outside of the 1493 // transaction pool, since its internal state is tightly coupled with the pools 1494 // internal mechanisms. The sole purpose of the type is to permit out-of-bound 1495 // peeking into the pool in TxPool.Get without having to acquire the widely scoped 1496 // TxPool.mu mutex. 1497 type txLookup struct { 1498 all map[common.Hash]*types.Transaction 1499 lock sync.RWMutex 1500 } 1501 1502 // newTxLookup returns a new txLookup structure. 1503 func newTxLookup() *txLookup { 1504 return &txLookup{ 1505 all: make(map[common.Hash]*types.Transaction), 1506 } 1507 } 1508 1509 // Range calls f on each key and value present in the map. 1510 func (t *txLookup) Range(f func(hash common.Hash, tx *types.Transaction) bool) { 1511 t.lock.RLock() 1512 defer t.lock.RUnlock() 1513 1514 for key, value := range t.all { 1515 if !f(key, value) { 1516 break 1517 } 1518 } 1519 } 1520 1521 // Get returns a transaction if it exists in the lookup, or nil if not found. 1522 func (t *txLookup) Get(hash common.Hash) *types.Transaction { 1523 t.lock.RLock() 1524 defer t.lock.RUnlock() 1525 1526 return t.all[hash] 1527 } 1528 1529 // Count returns the current number of items in the lookup. 1530 func (t *txLookup) Count() int { 1531 t.lock.RLock() 1532 defer t.lock.RUnlock() 1533 1534 return len(t.all) 1535 } 1536 1537 // Add adds a transaction to the lookup. 1538 func (t *txLookup) Add(tx *types.Transaction) { 1539 t.lock.Lock() 1540 defer t.lock.Unlock() 1541 1542 t.all[tx.Hash()] = tx 1543 } 1544 1545 // Remove removes a transaction from the lookup. 1546 func (t *txLookup) Remove(hash common.Hash) { 1547 t.lock.Lock() 1548 defer t.lock.Unlock() 1549 1550 delete(t.all, hash) 1551 }