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