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