github.com/nnlgsakib/mind-dpos@v0.0.0-20230606105614-f3c8ca06f808/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/TTCECO/gttc/common" 29 "github.com/TTCECO/gttc/core/state" 30 "github.com/TTCECO/gttc/core/types" 31 "github.com/TTCECO/gttc/event" 32 "github.com/TTCECO/gttc/log" 33 "github.com/TTCECO/gttc/metrics" 34 "github.com/TTCECO/gttc/params" 35 "gopkg.in/karalabe/cookiejar.v2/collections/prque" 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 pendingDiscardCounter = metrics.NewRegisteredCounter("txpool/pending/discard", nil) 89 pendingReplaceCounter = metrics.NewRegisteredCounter("txpool/pending/replace", nil) 90 pendingRateLimitCounter = metrics.NewRegisteredCounter("txpool/pending/ratelimit", nil) // Dropped due to rate limiting 91 pendingNofundsCounter = metrics.NewRegisteredCounter("txpool/pending/nofunds", nil) // Dropped due to out-of-funds 92 93 // Metrics for the queued pool 94 queuedDiscardCounter = metrics.NewRegisteredCounter("txpool/queued/discard", nil) 95 queuedReplaceCounter = metrics.NewRegisteredCounter("txpool/queued/replace", nil) 96 queuedRateLimitCounter = metrics.NewRegisteredCounter("txpool/queued/ratelimit", nil) // Dropped due to rate limiting 97 queuedNofundsCounter = metrics.NewRegisteredCounter("txpool/queued/nofunds", nil) // Dropped due to out-of-funds 98 99 // General tx metrics 100 invalidTxCounter = metrics.NewRegisteredCounter("txpool/invalid", nil) 101 underpricedTxCounter = metrics.NewRegisteredCounter("txpool/underpriced", nil) 102 ) 103 104 // TxStatus is the current status of a transaction as seen by the pool. 105 type TxStatus uint 106 107 const ( 108 TxStatusUnknown TxStatus = iota 109 TxStatusQueued 110 TxStatusPending 111 TxStatusIncluded 112 ) 113 114 // blockChain provides the state of blockchain and current gas limit to do 115 // some pre checks in tx pool and event subscribers. 116 type blockChain interface { 117 CurrentBlock() *types.Block 118 GetBlock(hash common.Hash, number uint64) *types.Block 119 StateAt(root common.Hash) (*state.StateDB, error) 120 121 SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription 122 } 123 124 // TxPoolConfig are the configuration parameters of the transaction pool. 125 type TxPoolConfig struct { 126 NoLocals bool // Whether local transaction handling should be disabled 127 Journal string // Journal of local transactions to survive node restarts 128 Rejournal time.Duration // Time interval to regenerate the local transaction journal 129 130 PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool 131 PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce) 132 133 AccountSlots uint64 // Minimum number of executable transaction slots guaranteed per account 134 GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts 135 AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account 136 GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts 137 138 Lifetime time.Duration // Maximum amount of time non-executable transaction are queued 139 } 140 141 // DefaultTxPoolConfig contains the default configurations for the transaction 142 // pool. 143 var DefaultTxPoolConfig = TxPoolConfig{ 144 Journal: "transactions.rlp", 145 Rejournal: time.Hour, 146 147 PriceLimit: 1, 148 PriceBump: 10, 149 150 AccountSlots: 16, 151 GlobalSlots: 4096, 152 AccountQueue: 64, 153 GlobalQueue: 1024, 154 155 Lifetime: 3 * time.Hour, 156 } 157 158 // sanitize checks the provided user configurations and changes anything that's 159 // unreasonable or unworkable. 160 func (config *TxPoolConfig) sanitize() TxPoolConfig { 161 conf := *config 162 if conf.Rejournal < time.Second { 163 log.Warn("Sanitizing invalid txpool journal time", "provided", conf.Rejournal, "updated", time.Second) 164 conf.Rejournal = time.Second 165 } 166 if conf.PriceLimit < 1 { 167 log.Warn("Sanitizing invalid txpool price limit", "provided", conf.PriceLimit, "updated", DefaultTxPoolConfig.PriceLimit) 168 conf.PriceLimit = DefaultTxPoolConfig.PriceLimit 169 } 170 if conf.PriceBump < 1 { 171 log.Warn("Sanitizing invalid txpool price bump", "provided", conf.PriceBump, "updated", DefaultTxPoolConfig.PriceBump) 172 conf.PriceBump = DefaultTxPoolConfig.PriceBump 173 } 174 return conf 175 } 176 177 // TxPool contains all currently known transactions. Transactions 178 // enter the pool when they are received from the network or submitted 179 // locally. They exit the pool when they are included in the blockchain. 180 // 181 // The pool separates processable transactions (which can be applied to the 182 // current state) and future transactions. Transactions move between those 183 // two states over time as they are received and processed. 184 type TxPool struct { 185 config TxPoolConfig 186 chainconfig *params.ChainConfig 187 chain blockChain 188 gasPrice *big.Int 189 txFeed event.Feed 190 scope event.SubscriptionScope 191 chainHeadCh chan ChainHeadEvent 192 chainHeadSub event.Subscription 193 signer types.Signer 194 mu sync.RWMutex 195 196 currentState *state.StateDB // Current state in the blockchain head 197 pendingState *state.ManagedState // Pending state tracking virtual nonces 198 currentMaxGas uint64 // Current gas limit for transaction caps 199 200 locals *accountSet // Set of local transaction to exempt from eviction rules 201 journal *txJournal // Journal of local transaction to back up to disk 202 203 pending map[common.Address]*txList // All currently processable transactions 204 queue map[common.Address]*txList // Queued but non-processable transactions 205 beats map[common.Address]time.Time // Last heartbeat from each known account 206 all *txLookup // All transactions to allow lookups 207 priced *txPricedList // All transactions sorted by price 208 209 wg sync.WaitGroup // for shutdown sync 210 211 homestead bool 212 } 213 214 // NewTxPool creates a new transaction pool to gather, sort and filter inbound 215 // transactions from the network. 216 func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool { 217 // Sanitize the input to ensure no vulnerable gas prices are set 218 config = (&config).sanitize() 219 220 // Create the transaction pool with its initial settings 221 pool := &TxPool{ 222 config: config, 223 chainconfig: chainconfig, 224 chain: chain, 225 signer: types.NewEIP155Signer(chainconfig.ChainId), 226 pending: make(map[common.Address]*txList), 227 queue: make(map[common.Address]*txList), 228 beats: make(map[common.Address]time.Time), 229 all: newTxLookup(), 230 chainHeadCh: make(chan ChainHeadEvent, chainHeadChanSize), 231 gasPrice: new(big.Int).SetUint64(config.PriceLimit), 232 } 233 pool.locals = newAccountSet(pool.signer) 234 pool.priced = newTxPricedList(pool.all) 235 pool.reset(nil, chain.CurrentBlock().Header()) 236 237 // If local transactions and journaling is enabled, load from disk 238 if !config.NoLocals && config.Journal != "" { 239 pool.journal = newTxJournal(config.Journal) 240 241 if err := pool.journal.load(pool.AddLocals); err != nil { 242 log.Warn("Failed to load transaction journal", "err", err) 243 } 244 if err := pool.journal.rotate(pool.local()); err != nil { 245 log.Warn("Failed to rotate transaction journal", "err", err) 246 } 247 } 248 // Subscribe events from blockchain 249 pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh) 250 251 // Start the event loop and return 252 pool.wg.Add(1) 253 go pool.loop() 254 255 return pool 256 } 257 258 // loop is the transaction pool's main event loop, waiting for and reacting to 259 // outside blockchain events as well as for various reporting and transaction 260 // eviction events. 261 func (pool *TxPool) loop() { 262 defer pool.wg.Done() 263 264 // Start the stats reporting and transaction eviction tickers 265 var prevPending, prevQueued, prevStales int 266 267 report := time.NewTicker(statsReportInterval) 268 defer report.Stop() 269 270 evict := time.NewTicker(evictionInterval) 271 defer evict.Stop() 272 273 journal := time.NewTicker(pool.config.Rejournal) 274 defer journal.Stop() 275 276 // Track the previous head headers for transaction reorgs 277 head := pool.chain.CurrentBlock() 278 279 // Keep waiting for and reacting to the various events 280 for { 281 select { 282 // Handle ChainHeadEvent 283 case ev := <-pool.chainHeadCh: 284 if ev.Block != nil { 285 pool.mu.Lock() 286 if pool.chainconfig.IsHomestead(ev.Block.Number()) { 287 pool.homestead = true 288 } 289 pool.reset(head.Header(), ev.Block.Header()) 290 head = ev.Block 291 292 pool.mu.Unlock() 293 } 294 // Be unsubscribed due to system stopped 295 case <-pool.chainHeadSub.Err(): 296 return 297 298 // Handle stats reporting ticks 299 case <-report.C: 300 pool.mu.RLock() 301 pending, queued := pool.stats() 302 stales := pool.priced.stales 303 pool.mu.RUnlock() 304 305 if pending != prevPending || queued != prevQueued || stales != prevStales { 306 log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales) 307 prevPending, prevQueued, prevStales = pending, queued, stales 308 } 309 310 // Handle inactive account transaction eviction 311 case <-evict.C: 312 pool.mu.Lock() 313 for addr := range pool.queue { 314 // Skip local transactions from the eviction mechanism 315 if pool.locals.contains(addr) { 316 continue 317 } 318 // Any non-locals old enough should be removed 319 if time.Since(pool.beats[addr]) > pool.config.Lifetime { 320 for _, tx := range pool.queue[addr].Flatten() { 321 pool.removeTx(tx.Hash(), true) 322 } 323 } 324 } 325 pool.mu.Unlock() 326 327 // Handle local transaction journal rotation 328 case <-journal.C: 329 if pool.journal != nil { 330 pool.mu.Lock() 331 if err := pool.journal.rotate(pool.local()); err != nil { 332 log.Warn("Failed to rotate local tx journal", "err", err) 333 } 334 pool.mu.Unlock() 335 } 336 } 337 } 338 } 339 340 // lockedReset is a wrapper around reset to allow calling it in a thread safe 341 // manner. This method is only ever used in the tester! 342 func (pool *TxPool) lockedReset(oldHead, newHead *types.Header) { 343 pool.mu.Lock() 344 defer pool.mu.Unlock() 345 346 pool.reset(oldHead, newHead) 347 } 348 349 // reset retrieves the current state of the blockchain and ensures the content 350 // of the transaction pool is valid with regard to the chain state. 351 func (pool *TxPool) reset(oldHead, newHead *types.Header) { 352 // If we're reorging an old state, reinject all dropped transactions 353 var reinject types.Transactions 354 355 if oldHead != nil && oldHead.Hash() != newHead.ParentHash { 356 // If the reorg is too deep, avoid doing it (will happen during fast sync) 357 oldNum := oldHead.Number.Uint64() 358 newNum := newHead.Number.Uint64() 359 360 if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 { 361 log.Debug("Skipping deep transaction reorg", "depth", depth) 362 } else { 363 // Reorg seems shallow enough to pull in all transactions into memory 364 var discarded, included types.Transactions 365 366 var ( 367 rem = pool.chain.GetBlock(oldHead.Hash(), oldHead.Number.Uint64()) 368 add = pool.chain.GetBlock(newHead.Hash(), newHead.Number.Uint64()) 369 ) 370 for rem.NumberU64() > add.NumberU64() { 371 discarded = append(discarded, rem.Transactions()...) 372 if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil { 373 log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash()) 374 return 375 } 376 } 377 for add.NumberU64() > rem.NumberU64() { 378 included = append(included, add.Transactions()...) 379 if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil { 380 log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash()) 381 return 382 } 383 } 384 for rem.Hash() != add.Hash() { 385 discarded = append(discarded, rem.Transactions()...) 386 if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil { 387 log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash()) 388 return 389 } 390 included = append(included, add.Transactions()...) 391 if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil { 392 log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash()) 393 return 394 } 395 } 396 reinject = types.TxDifference(discarded, included) 397 } 398 } 399 // Initialize the internal state to the current head 400 if newHead == nil { 401 newHead = pool.chain.CurrentBlock().Header() // Special case during testing 402 } 403 statedb, err := pool.chain.StateAt(newHead.Root) 404 if err != nil { 405 log.Error("Failed to reset txpool state", "err", err) 406 return 407 } 408 pool.currentState = statedb 409 pool.pendingState = state.ManageState(statedb) 410 pool.currentMaxGas = newHead.GasLimit 411 412 // Inject any transactions discarded due to reorgs 413 log.Debug("Reinjecting stale transactions", "count", len(reinject)) 414 pool.addTxsLocked(reinject, false) 415 416 // validate the pool of pending transactions, this will remove 417 // any transactions that have been included in the block or 418 // have been invalidated because of another transaction (e.g. 419 // higher gas price) 420 pool.demoteUnexecutables() 421 422 // Update all accounts to the latest known pending nonce 423 for addr, list := range pool.pending { 424 txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway 425 pool.pendingState.SetNonce(addr, txs[len(txs)-1].Nonce()+1) 426 } 427 // Check the queue and move transactions over to the pending if possible 428 // or remove those that have become invalid 429 pool.promoteExecutables(nil) 430 } 431 432 // Stop terminates the transaction pool. 433 func (pool *TxPool) Stop() { 434 // Unsubscribe all subscriptions registered from txpool 435 pool.scope.Close() 436 437 // Unsubscribe subscriptions registered from blockchain 438 pool.chainHeadSub.Unsubscribe() 439 pool.wg.Wait() 440 441 if pool.journal != nil { 442 pool.journal.close() 443 } 444 log.Info("Transaction pool stopped") 445 } 446 447 // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and 448 // starts sending event to the given channel. 449 func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription { 450 return pool.scope.Track(pool.txFeed.Subscribe(ch)) 451 } 452 453 // GasPrice returns the current gas price enforced by the transaction pool. 454 func (pool *TxPool) GasPrice() *big.Int { 455 pool.mu.RLock() 456 defer pool.mu.RUnlock() 457 458 return new(big.Int).Set(pool.gasPrice) 459 } 460 461 // SetGasPrice updates the minimum price required by the transaction pool for a 462 // new transaction, and drops all transactions below this threshold. 463 func (pool *TxPool) SetGasPrice(price *big.Int) { 464 pool.mu.Lock() 465 defer pool.mu.Unlock() 466 467 pool.gasPrice = price 468 for _, tx := range pool.priced.Cap(price, pool.locals) { 469 pool.removeTx(tx.Hash(), false) 470 } 471 log.Info("Transaction pool price threshold updated", "price", price) 472 } 473 474 // State returns the virtual managed state of the transaction pool. 475 func (pool *TxPool) State() *state.ManagedState { 476 pool.mu.RLock() 477 defer pool.mu.RUnlock() 478 479 return pool.pendingState 480 } 481 482 // Stats retrieves the current pool stats, namely the number of pending and the 483 // number of queued (non-executable) transactions. 484 func (pool *TxPool) Stats() (int, int) { 485 pool.mu.RLock() 486 defer pool.mu.RUnlock() 487 488 return pool.stats() 489 } 490 491 // stats retrieves the current pool stats, namely the number of pending and the 492 // number of queued (non-executable) transactions. 493 func (pool *TxPool) stats() (int, int) { 494 pending := 0 495 for _, list := range pool.pending { 496 pending += list.Len() 497 } 498 queued := 0 499 for _, list := range pool.queue { 500 queued += list.Len() 501 } 502 return pending, queued 503 } 504 505 // Content retrieves the data content of the transaction pool, returning all the 506 // pending as well as queued transactions, grouped by account and sorted by nonce. 507 func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) { 508 pool.mu.Lock() 509 defer pool.mu.Unlock() 510 511 pending := make(map[common.Address]types.Transactions) 512 for addr, list := range pool.pending { 513 pending[addr] = list.Flatten() 514 } 515 queued := make(map[common.Address]types.Transactions) 516 for addr, list := range pool.queue { 517 queued[addr] = list.Flatten() 518 } 519 return pending, queued 520 } 521 522 // Pending retrieves all currently processable transactions, groupped by origin 523 // account and sorted by nonce. The returned transaction set is a copy and can be 524 // freely modified by calling code. 525 func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) { 526 pool.mu.Lock() 527 defer pool.mu.Unlock() 528 529 pending := make(map[common.Address]types.Transactions) 530 for addr, list := range pool.pending { 531 pending[addr] = list.Flatten() 532 } 533 return pending, nil 534 } 535 536 // local retrieves all currently known local transactions, groupped by origin 537 // account and sorted by nonce. The returned transaction set is a copy and can be 538 // freely modified by calling code. 539 func (pool *TxPool) local() map[common.Address]types.Transactions { 540 txs := make(map[common.Address]types.Transactions) 541 for addr := range pool.locals.accounts { 542 if pending := pool.pending[addr]; pending != nil { 543 txs[addr] = append(txs[addr], pending.Flatten()...) 544 } 545 if queued := pool.queue[addr]; queued != nil { 546 txs[addr] = append(txs[addr], queued.Flatten()...) 547 } 548 } 549 return txs 550 } 551 552 // validateTx checks whether a transaction is valid according to the consensus 553 // rules and adheres to some heuristic limits of the local node (price and size). 554 func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error { 555 // Heuristic limit, reject transactions over 32KB to prevent DOS attacks 556 if tx.Size() > 32*1024 { 557 return ErrOversizedData 558 } 559 // Transactions can't be negative. This may never happen using RLP decoded 560 // transactions but may occur if you create a transaction using the RPC. 561 if tx.Value().Sign() < 0 { 562 return ErrNegativeValue 563 } 564 // Ensure the transaction doesn't exceed the current block limit gas. 565 if pool.currentMaxGas < tx.Gas() { 566 return ErrGasLimit 567 } 568 // Make sure the transaction is signed properly 569 from, err := types.Sender(pool.signer, tx) 570 if err != nil { 571 return ErrInvalidSender 572 } 573 // Drop non-local transactions under our own minimal accepted gas price 574 local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network 575 if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 { 576 return ErrUnderpriced 577 } 578 // Ensure the transaction adheres to nonce ordering 579 if pool.currentState.GetNonce(from) > tx.Nonce() { 580 return ErrNonceTooLow 581 } 582 // Transactor should have enough funds to cover the costs 583 // cost == V + GP * GL 584 if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 { 585 return ErrInsufficientFunds 586 } 587 intrGas, err := IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead) 588 if err != nil { 589 return err 590 } 591 if tx.Gas() < intrGas { 592 return ErrIntrinsicGas 593 } 594 return nil 595 } 596 597 // add validates a transaction and inserts it into the non-executable queue for 598 // later pending promotion and execution. If the transaction is a replacement for 599 // an already pending or queued one, it overwrites the previous and returns this 600 // so outer code doesn't uselessly call promote. 601 // 602 // If a newly added transaction is marked as local, its sending account will be 603 // whitelisted, preventing any associated transaction from being dropped out of 604 // the pool due to pricing constraints. 605 func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) { 606 // If the transaction is already known, discard it 607 hash := tx.Hash() 608 if pool.all.Get(hash) != nil { 609 log.Trace("Discarding already known transaction", "hash", hash) 610 return false, fmt.Errorf("known transaction: %x", hash) 611 } 612 // If the transaction fails basic validation, discard it 613 if err := pool.validateTx(tx, local); err != nil { 614 log.Trace("Discarding invalid transaction", "hash", hash, "err", err) 615 invalidTxCounter.Inc(1) 616 return false, err 617 } 618 // If the transaction pool is full, discard underpriced transactions 619 if uint64(pool.all.Count()) >= pool.config.GlobalSlots+pool.config.GlobalQueue { 620 // If the new transaction is underpriced, don't accept it 621 if !local && pool.priced.Underpriced(tx, pool.locals) { 622 log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice()) 623 underpricedTxCounter.Inc(1) 624 return false, ErrUnderpriced 625 } 626 // New transaction is better than our worse ones, make room for it 627 drop := pool.priced.Discard(pool.all.Count()-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals) 628 for _, tx := range drop { 629 log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice()) 630 underpricedTxCounter.Inc(1) 631 pool.removeTx(tx.Hash(), false) 632 } 633 } 634 // If the transaction is replacing an already pending one, do directly 635 from, _ := types.Sender(pool.signer, tx) // already validated 636 if list := pool.pending[from]; list != nil && list.Overlaps(tx) { 637 // Nonce already pending, check if required price bump is met 638 inserted, old := list.Add(tx, pool.config.PriceBump) 639 if !inserted { 640 pendingDiscardCounter.Inc(1) 641 return false, ErrReplaceUnderpriced 642 } 643 // New transaction is better, replace old one 644 if old != nil { 645 pool.all.Remove(old.Hash()) 646 pool.priced.Removed() 647 pendingReplaceCounter.Inc(1) 648 } 649 pool.all.Add(tx) 650 pool.priced.Put(tx) 651 pool.journalTx(from, tx) 652 653 log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To()) 654 655 // We've directly injected a replacement transaction, notify subsystems 656 go pool.txFeed.Send(NewTxsEvent{types.Transactions{tx}}) 657 658 return old != nil, nil 659 } 660 // New transaction isn't replacing a pending one, push into queue 661 replace, err := pool.enqueueTx(hash, tx) 662 if err != nil { 663 return false, err 664 } 665 // Mark local addresses and journal local transactions 666 if local { 667 pool.locals.add(from) 668 } 669 pool.journalTx(from, tx) 670 671 log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To()) 672 return replace, nil 673 } 674 675 // enqueueTx inserts a new transaction into the non-executable transaction queue. 676 // 677 // Note, this method assumes the pool lock is held! 678 func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) { 679 // Try to insert the transaction into the future queue 680 from, _ := types.Sender(pool.signer, tx) // already validated 681 if pool.queue[from] == nil { 682 pool.queue[from] = newTxList(false) 683 } 684 inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump) 685 if !inserted { 686 // An older transaction was better, discard this 687 queuedDiscardCounter.Inc(1) 688 return false, ErrReplaceUnderpriced 689 } 690 // Discard any previous transaction and mark this 691 if old != nil { 692 pool.all.Remove(old.Hash()) 693 pool.priced.Removed() 694 queuedReplaceCounter.Inc(1) 695 } 696 if pool.all.Get(hash) == nil { 697 pool.all.Add(tx) 698 pool.priced.Put(tx) 699 } 700 return old != nil, nil 701 } 702 703 // journalTx adds the specified transaction to the local disk journal if it is 704 // deemed to have been sent from a local account. 705 func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) { 706 // Only journal if it's enabled and the transaction is local 707 if pool.journal == nil || !pool.locals.contains(from) { 708 return 709 } 710 if err := pool.journal.insert(tx); err != nil { 711 log.Warn("Failed to journal local transaction", "err", err) 712 } 713 } 714 715 // promoteTx adds a transaction to the pending (processable) list of transactions 716 // and returns whether it was inserted or an older was better. 717 // 718 // Note, this method assumes the pool lock is held! 719 func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool { 720 // Try to insert the transaction into the pending queue 721 if pool.pending[addr] == nil { 722 pool.pending[addr] = newTxList(true) 723 } 724 list := pool.pending[addr] 725 726 inserted, old := list.Add(tx, pool.config.PriceBump) 727 if !inserted { 728 // An older transaction was better, discard this 729 pool.all.Remove(hash) 730 pool.priced.Removed() 731 732 pendingDiscardCounter.Inc(1) 733 return false 734 } 735 // Otherwise discard any previous transaction and mark this 736 if old != nil { 737 pool.all.Remove(old.Hash()) 738 pool.priced.Removed() 739 740 pendingReplaceCounter.Inc(1) 741 } 742 // Failsafe to work around direct pending inserts (tests) 743 if pool.all.Get(hash) == nil { 744 pool.all.Add(tx) 745 pool.priced.Put(tx) 746 } 747 // Set the potentially new pending nonce and notify any subsystems of the new tx 748 pool.beats[addr] = time.Now() 749 pool.pendingState.SetNonce(addr, tx.Nonce()+1) 750 751 return true 752 } 753 754 // AddLocal enqueues a single transaction into the pool if it is valid, marking 755 // the sender as a local one in the mean time, ensuring it goes around the local 756 // pricing constraints. 757 func (pool *TxPool) AddLocal(tx *types.Transaction) error { 758 return pool.addTx(tx, !pool.config.NoLocals) 759 } 760 761 // AddRemote enqueues a single transaction into the pool if it is valid. If the 762 // sender is not among the locally tracked ones, full pricing constraints will 763 // apply. 764 func (pool *TxPool) AddRemote(tx *types.Transaction) error { 765 return pool.addTx(tx, false) 766 } 767 768 // AddLocals enqueues a batch of transactions into the pool if they are valid, 769 // marking the senders as a local ones in the mean time, ensuring they go around 770 // the local pricing constraints. 771 func (pool *TxPool) AddLocals(txs []*types.Transaction) []error { 772 return pool.addTxs(txs, !pool.config.NoLocals) 773 } 774 775 // AddRemotes enqueues a batch of transactions into the pool if they are valid. 776 // If the senders are not among the locally tracked ones, full pricing constraints 777 // will apply. 778 func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error { 779 return pool.addTxs(txs, false) 780 } 781 782 // addTx enqueues a single transaction into the pool if it is valid. 783 func (pool *TxPool) addTx(tx *types.Transaction, local bool) error { 784 pool.mu.Lock() 785 defer pool.mu.Unlock() 786 787 // Try to inject the transaction and update any state 788 replace, err := pool.add(tx, local) 789 if err != nil { 790 return err 791 } 792 // If we added a new transaction, run promotion checks and return 793 if !replace { 794 from, _ := types.Sender(pool.signer, tx) // already validated 795 pool.promoteExecutables([]common.Address{from}) 796 } 797 return nil 798 } 799 800 // addTxs attempts to queue a batch of transactions if they are valid. 801 func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) []error { 802 pool.mu.Lock() 803 defer pool.mu.Unlock() 804 805 return pool.addTxsLocked(txs, local) 806 } 807 808 // addTxsLocked attempts to queue a batch of transactions if they are valid, 809 // whilst assuming the transaction pool lock is already held. 810 func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error { 811 // Add the batch of transaction, tracking the accepted ones 812 dirty := make(map[common.Address]struct{}) 813 errs := make([]error, len(txs)) 814 815 for i, tx := range txs { 816 var replace bool 817 if replace, errs[i] = pool.add(tx, local); errs[i] == nil { 818 if !replace { 819 from, _ := types.Sender(pool.signer, tx) // already validated 820 dirty[from] = struct{}{} 821 } 822 } 823 } 824 // Only reprocess the internal state if something was actually added 825 if len(dirty) > 0 { 826 addrs := make([]common.Address, 0, len(dirty)) 827 for addr := range dirty { 828 addrs = append(addrs, addr) 829 } 830 pool.promoteExecutables(addrs) 831 } 832 return errs 833 } 834 835 // Status returns the status (unknown/pending/queued) of a batch of transactions 836 // identified by their hashes. 837 func (pool *TxPool) Status(hashes []common.Hash) []TxStatus { 838 pool.mu.RLock() 839 defer pool.mu.RUnlock() 840 841 status := make([]TxStatus, len(hashes)) 842 for i, hash := range hashes { 843 if tx := pool.all.Get(hash); tx != nil { 844 from, _ := types.Sender(pool.signer, tx) // already validated 845 if pool.pending[from] != nil && pool.pending[from].txs.items[tx.Nonce()] != nil { 846 status[i] = TxStatusPending 847 } else { 848 status[i] = TxStatusQueued 849 } 850 } 851 } 852 return status 853 } 854 855 // Get returns a transaction if it is contained in the pool 856 // and nil otherwise. 857 func (pool *TxPool) Get(hash common.Hash) *types.Transaction { 858 return pool.all.Get(hash) 859 } 860 861 // removeTx removes a single transaction from the queue, moving all subsequent 862 // transactions back to the future queue. 863 func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) { 864 // Fetch the transaction we wish to delete 865 tx := pool.all.Get(hash) 866 if tx == nil { 867 return 868 } 869 addr, _ := types.Sender(pool.signer, tx) // already validated during insertion 870 871 // Remove it from the list of known transactions 872 pool.all.Remove(hash) 873 if outofbound { 874 pool.priced.Removed() 875 } 876 // Remove the transaction from the pending lists and reset the account nonce 877 if pending := pool.pending[addr]; pending != nil { 878 if removed, invalids := pending.Remove(tx); removed { 879 // If no more pending transactions are left, remove the list 880 if pending.Empty() { 881 delete(pool.pending, addr) 882 delete(pool.beats, addr) 883 } 884 // Postpone any invalidated transactions 885 for _, tx := range invalids { 886 pool.enqueueTx(tx.Hash(), tx) 887 } 888 // Update the account nonce if needed 889 if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce { 890 pool.pendingState.SetNonce(addr, nonce) 891 } 892 return 893 } 894 } 895 // Transaction is in the future queue 896 if future := pool.queue[addr]; future != nil { 897 future.Remove(tx) 898 if future.Empty() { 899 delete(pool.queue, addr) 900 } 901 } 902 } 903 904 // promoteExecutables moves transactions that have become processable from the 905 // future queue to the set of pending transactions. During this process, all 906 // invalidated transactions (low nonce, low balance) are deleted. 907 func (pool *TxPool) promoteExecutables(accounts []common.Address) { 908 // Track the promoted transactions to broadcast them at once 909 var promoted []*types.Transaction 910 911 // Gather all the accounts potentially needing updates 912 if accounts == nil { 913 accounts = make([]common.Address, 0, len(pool.queue)) 914 for addr := range pool.queue { 915 accounts = append(accounts, addr) 916 } 917 } 918 // Iterate over all accounts and promote any executable transactions 919 for _, addr := range accounts { 920 list := pool.queue[addr] 921 if list == nil { 922 continue // Just in case someone calls with a non existing account 923 } 924 // Drop all transactions that are deemed too old (low nonce) 925 for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) { 926 hash := tx.Hash() 927 log.Trace("Removed old queued transaction", "hash", hash) 928 pool.all.Remove(hash) 929 pool.priced.Removed() 930 } 931 // Drop all transactions that are too costly (low balance or out of gas) 932 drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas) 933 for _, tx := range drops { 934 hash := tx.Hash() 935 log.Trace("Removed unpayable queued transaction", "hash", hash) 936 pool.all.Remove(hash) 937 pool.priced.Removed() 938 queuedNofundsCounter.Inc(1) 939 } 940 // Gather all executable transactions and promote them 941 for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) { 942 hash := tx.Hash() 943 if pool.promoteTx(addr, hash, tx) { 944 log.Trace("Promoting queued transaction", "hash", hash) 945 promoted = append(promoted, tx) 946 } 947 } 948 // Drop all transactions over the allowed limit 949 if !pool.locals.contains(addr) { 950 for _, tx := range list.Cap(int(pool.config.AccountQueue)) { 951 hash := tx.Hash() 952 pool.all.Remove(hash) 953 pool.priced.Removed() 954 queuedRateLimitCounter.Inc(1) 955 log.Trace("Removed cap-exceeding queued transaction", "hash", hash) 956 } 957 } 958 // Delete the entire queue entry if it became empty. 959 if list.Empty() { 960 delete(pool.queue, addr) 961 } 962 } 963 // Notify subsystem for new promoted transactions. 964 if len(promoted) > 0 { 965 pool.txFeed.Send(NewTxsEvent{promoted}) 966 } 967 // If the pending limit is overflown, start equalizing allowances 968 pending := uint64(0) 969 for _, list := range pool.pending { 970 pending += uint64(list.Len()) 971 } 972 if pending > pool.config.GlobalSlots { 973 pendingBeforeCap := pending 974 // Assemble a spam order to penalize large transactors first 975 spammers := prque.New() 976 for addr, list := range pool.pending { 977 // Only evict transactions from high rollers 978 if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots { 979 spammers.Push(addr, float32(list.Len())) 980 } 981 } 982 // Gradually drop transactions from offenders 983 offenders := []common.Address{} 984 for pending > pool.config.GlobalSlots && !spammers.Empty() { 985 // Retrieve the next offender if not local address 986 offender, _ := spammers.Pop() 987 offenders = append(offenders, offender.(common.Address)) 988 989 // Equalize balances until all the same or below threshold 990 if len(offenders) > 1 { 991 // Calculate the equalization threshold for all current offenders 992 threshold := pool.pending[offender.(common.Address)].Len() 993 994 // Iteratively reduce all offenders until below limit or threshold reached 995 for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold { 996 for i := 0; i < len(offenders)-1; i++ { 997 list := pool.pending[offenders[i]] 998 for _, tx := range list.Cap(list.Len() - 1) { 999 // Drop the transaction from the global pools too 1000 hash := tx.Hash() 1001 pool.all.Remove(hash) 1002 pool.priced.Removed() 1003 1004 // Update the account nonce to the dropped transaction 1005 if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce { 1006 pool.pendingState.SetNonce(offenders[i], nonce) 1007 } 1008 log.Trace("Removed fairness-exceeding pending transaction", "hash", hash) 1009 } 1010 pending-- 1011 } 1012 } 1013 } 1014 } 1015 // If still above threshold, reduce to limit or min allowance 1016 if pending > pool.config.GlobalSlots && len(offenders) > 0 { 1017 for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots { 1018 for _, addr := range offenders { 1019 list := pool.pending[addr] 1020 for _, tx := range list.Cap(list.Len() - 1) { 1021 // Drop the transaction from the global pools too 1022 hash := tx.Hash() 1023 pool.all.Remove(hash) 1024 pool.priced.Removed() 1025 1026 // Update the account nonce to the dropped transaction 1027 if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce { 1028 pool.pendingState.SetNonce(addr, nonce) 1029 } 1030 log.Trace("Removed fairness-exceeding pending transaction", "hash", hash) 1031 } 1032 pending-- 1033 } 1034 } 1035 } 1036 pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending)) 1037 } 1038 // If we've queued more transactions than the hard limit, drop oldest ones 1039 queued := uint64(0) 1040 for _, list := range pool.queue { 1041 queued += uint64(list.Len()) 1042 } 1043 if queued > pool.config.GlobalQueue { 1044 // Sort all accounts with queued transactions by heartbeat 1045 addresses := make(addresssByHeartbeat, 0, len(pool.queue)) 1046 for addr := range pool.queue { 1047 if !pool.locals.contains(addr) { // don't drop locals 1048 addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]}) 1049 } 1050 } 1051 sort.Sort(addresses) 1052 1053 // Drop transactions until the total is below the limit or only locals remain 1054 for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; { 1055 addr := addresses[len(addresses)-1] 1056 list := pool.queue[addr.address] 1057 1058 addresses = addresses[:len(addresses)-1] 1059 1060 // Drop all transactions if they are less than the overflow 1061 if size := uint64(list.Len()); size <= drop { 1062 for _, tx := range list.Flatten() { 1063 pool.removeTx(tx.Hash(), true) 1064 } 1065 drop -= size 1066 queuedRateLimitCounter.Inc(int64(size)) 1067 continue 1068 } 1069 // Otherwise drop only last few transactions 1070 txs := list.Flatten() 1071 for i := len(txs) - 1; i >= 0 && drop > 0; i-- { 1072 pool.removeTx(txs[i].Hash(), true) 1073 drop-- 1074 queuedRateLimitCounter.Inc(1) 1075 } 1076 } 1077 } 1078 } 1079 1080 // demoteUnexecutables removes invalid and processed transactions from the pools 1081 // executable/pending queue and any subsequent transactions that become unexecutable 1082 // are moved back into the future queue. 1083 func (pool *TxPool) demoteUnexecutables() { 1084 // Iterate over all accounts and demote any non-executable transactions 1085 for addr, list := range pool.pending { 1086 nonce := pool.currentState.GetNonce(addr) 1087 1088 // Drop all transactions that are deemed too old (low nonce) 1089 for _, tx := range list.Forward(nonce) { 1090 hash := tx.Hash() 1091 log.Trace("Removed old pending transaction", "hash", hash) 1092 pool.all.Remove(hash) 1093 pool.priced.Removed() 1094 } 1095 // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later 1096 drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas) 1097 for _, tx := range drops { 1098 hash := tx.Hash() 1099 log.Trace("Removed unpayable pending transaction", "hash", hash) 1100 pool.all.Remove(hash) 1101 pool.priced.Removed() 1102 pendingNofundsCounter.Inc(1) 1103 } 1104 for _, tx := range invalids { 1105 hash := tx.Hash() 1106 log.Trace("Demoting pending transaction", "hash", hash) 1107 pool.enqueueTx(hash, tx) 1108 } 1109 // If there's a gap in front, warn (should never happen) and postpone all transactions 1110 if list.Len() > 0 && list.txs.Get(nonce) == nil { 1111 for _, tx := range list.Cap(0) { 1112 hash := tx.Hash() 1113 log.Error("Demoting invalidated transaction", "hash", hash) 1114 pool.enqueueTx(hash, tx) 1115 } 1116 } 1117 // Delete the entire queue entry if it became empty. 1118 if list.Empty() { 1119 delete(pool.pending, addr) 1120 delete(pool.beats, addr) 1121 } 1122 } 1123 } 1124 1125 // addressByHeartbeat is an account address tagged with its last activity timestamp. 1126 type addressByHeartbeat struct { 1127 address common.Address 1128 heartbeat time.Time 1129 } 1130 1131 type addresssByHeartbeat []addressByHeartbeat 1132 1133 func (a addresssByHeartbeat) Len() int { return len(a) } 1134 func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) } 1135 func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 1136 1137 // accountSet is simply a set of addresses to check for existence, and a signer 1138 // capable of deriving addresses from transactions. 1139 type accountSet struct { 1140 accounts map[common.Address]struct{} 1141 signer types.Signer 1142 } 1143 1144 // newAccountSet creates a new address set with an associated signer for sender 1145 // derivations. 1146 func newAccountSet(signer types.Signer) *accountSet { 1147 return &accountSet{ 1148 accounts: make(map[common.Address]struct{}), 1149 signer: signer, 1150 } 1151 } 1152 1153 // contains checks if a given address is contained within the set. 1154 func (as *accountSet) contains(addr common.Address) bool { 1155 _, exist := as.accounts[addr] 1156 return exist 1157 } 1158 1159 // containsTx checks if the sender of a given tx is within the set. If the sender 1160 // cannot be derived, this method returns false. 1161 func (as *accountSet) containsTx(tx *types.Transaction) bool { 1162 if addr, err := types.Sender(as.signer, tx); err == nil { 1163 return as.contains(addr) 1164 } 1165 return false 1166 } 1167 1168 // add inserts a new address into the set to track. 1169 func (as *accountSet) add(addr common.Address) { 1170 as.accounts[addr] = struct{}{} 1171 } 1172 1173 // txLookup is used internally by TxPool to track transactions while allowing lookup without 1174 // mutex contention. 1175 // 1176 // Note, although this type is properly protected against concurrent access, it 1177 // is **not** a type that should ever be mutated or even exposed outside of the 1178 // transaction pool, since its internal state is tightly coupled with the pools 1179 // internal mechanisms. The sole purpose of the type is to permit out-of-bound 1180 // peeking into the pool in TxPool.Get without having to acquire the widely scoped 1181 // TxPool.mu mutex. 1182 type txLookup struct { 1183 all map[common.Hash]*types.Transaction 1184 lock sync.RWMutex 1185 } 1186 1187 // newTxLookup returns a new txLookup structure. 1188 func newTxLookup() *txLookup { 1189 return &txLookup{ 1190 all: make(map[common.Hash]*types.Transaction), 1191 } 1192 } 1193 1194 // Range calls f on each key and value present in the map. 1195 func (t *txLookup) Range(f func(hash common.Hash, tx *types.Transaction) bool) { 1196 t.lock.RLock() 1197 defer t.lock.RUnlock() 1198 1199 for key, value := range t.all { 1200 if !f(key, value) { 1201 break 1202 } 1203 } 1204 } 1205 1206 // Get returns a transaction if it exists in the lookup, or nil if not found. 1207 func (t *txLookup) Get(hash common.Hash) *types.Transaction { 1208 t.lock.RLock() 1209 defer t.lock.RUnlock() 1210 1211 return t.all[hash] 1212 } 1213 1214 // Count returns the current number of items in the lookup. 1215 func (t *txLookup) Count() int { 1216 t.lock.RLock() 1217 defer t.lock.RUnlock() 1218 1219 return len(t.all) 1220 } 1221 1222 // Add adds a transaction to the lookup. 1223 func (t *txLookup) Add(tx *types.Transaction) { 1224 t.lock.Lock() 1225 defer t.lock.Unlock() 1226 1227 t.all[tx.Hash()] = tx 1228 } 1229 1230 // Remove removes a transaction from the lookup. 1231 func (t *txLookup) Remove(hash common.Hash) { 1232 t.lock.Lock() 1233 defer t.lock.Unlock() 1234 1235 delete(t.all, hash) 1236 }