github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/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 ) 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 map[common.Hash]*types.Transaction // 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: make(map[common.Hash]*types.Transaction), 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.AddLocal); 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 // SubscribeTxPreEvent registers a subscription of TxPreEvent and 448 // starts sending event to the given channel. 449 func (pool *TxPool) SubscribeTxPreEvent(ch chan<- TxPreEvent) 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[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(len(pool.all)) >= 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(len(pool.all)-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 delete(pool.all, old.Hash()) 646 pool.priced.Removed() 647 pendingReplaceCounter.Inc(1) 648 } 649 pool.all[tx.Hash()] = 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(TxPreEvent{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 delete(pool.all, old.Hash()) 693 pool.priced.Removed() 694 queuedReplaceCounter.Inc(1) 695 } 696 if pool.all[hash] == nil { 697 pool.all[hash] = 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 // 717 // Note, this method assumes the pool lock is held! 718 func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) { 719 // Try to insert the transaction into the pending queue 720 if pool.pending[addr] == nil { 721 pool.pending[addr] = newTxList(true) 722 } 723 list := pool.pending[addr] 724 725 inserted, old := list.Add(tx, pool.config.PriceBump) 726 if !inserted { 727 // An older transaction was better, discard this 728 delete(pool.all, hash) 729 pool.priced.Removed() 730 731 pendingDiscardCounter.Inc(1) 732 return 733 } 734 // Otherwise discard any previous transaction and mark this 735 if old != nil { 736 delete(pool.all, old.Hash()) 737 pool.priced.Removed() 738 739 pendingReplaceCounter.Inc(1) 740 } 741 // Failsafe to work around direct pending inserts (tests) 742 if pool.all[hash] == nil { 743 pool.all[hash] = tx 744 pool.priced.Put(tx) 745 } 746 // Set the potentially new pending nonce and notify any subsystems of the new tx 747 pool.beats[addr] = time.Now() 748 pool.pendingState.SetNonce(addr, tx.Nonce()+1) 749 750 go pool.txFeed.Send(TxPreEvent{tx}) 751 } 752 753 // AddLocal enqueues a single transaction into the pool if it is valid, marking 754 // the sender as a local one in the mean time, ensuring it goes around the local 755 // pricing constraints. 756 func (pool *TxPool) AddLocal(tx *types.Transaction) error { 757 return pool.addTx(tx, !pool.config.NoLocals) 758 } 759 760 // AddRemote enqueues a single transaction into the pool if it is valid. If the 761 // sender is not among the locally tracked ones, full pricing constraints will 762 // apply. 763 func (pool *TxPool) AddRemote(tx *types.Transaction) error { 764 return pool.addTx(tx, false) 765 } 766 767 // AddLocals enqueues a batch of transactions into the pool if they are valid, 768 // marking the senders as a local ones in the mean time, ensuring they go around 769 // the local pricing constraints. 770 func (pool *TxPool) AddLocals(txs []*types.Transaction) []error { 771 return pool.addTxs(txs, !pool.config.NoLocals) 772 } 773 774 // AddRemotes enqueues a batch of transactions into the pool if they are valid. 775 // If the senders are not among the locally tracked ones, full pricing constraints 776 // will apply. 777 func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error { 778 return pool.addTxs(txs, false) 779 } 780 781 // addTx enqueues a single transaction into the pool if it is valid. 782 func (pool *TxPool) addTx(tx *types.Transaction, local bool) error { 783 pool.mu.Lock() 784 defer pool.mu.Unlock() 785 786 // Try to inject the transaction and update any state 787 replace, err := pool.add(tx, local) 788 if err != nil { 789 return err 790 } 791 // If we added a new transaction, run promotion checks and return 792 if !replace { 793 from, _ := types.Sender(pool.signer, tx) // already validated 794 pool.promoteExecutables([]common.Address{from}) 795 } 796 return nil 797 } 798 799 // addTxs attempts to queue a batch of transactions if they are valid. 800 func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) []error { 801 pool.mu.Lock() 802 defer pool.mu.Unlock() 803 804 return pool.addTxsLocked(txs, local) 805 } 806 807 // addTxsLocked attempts to queue a batch of transactions if they are valid, 808 // whilst assuming the transaction pool lock is already held. 809 func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error { 810 // Add the batch of transaction, tracking the accepted ones 811 dirty := make(map[common.Address]struct{}) 812 errs := make([]error, len(txs)) 813 814 for i, tx := range txs { 815 var replace bool 816 if replace, errs[i] = pool.add(tx, local); errs[i] == nil { 817 if !replace { 818 from, _ := types.Sender(pool.signer, tx) // already validated 819 dirty[from] = struct{}{} 820 } 821 } 822 } 823 // Only reprocess the internal state if something was actually added 824 if len(dirty) > 0 { 825 addrs := make([]common.Address, 0, len(dirty)) 826 for addr := range dirty { 827 addrs = append(addrs, addr) 828 } 829 pool.promoteExecutables(addrs) 830 } 831 return errs 832 } 833 834 // Status returns the status (unknown/pending/queued) of a batch of transactions 835 // identified by their hashes. 836 func (pool *TxPool) Status(hashes []common.Hash) []TxStatus { 837 pool.mu.RLock() 838 defer pool.mu.RUnlock() 839 840 status := make([]TxStatus, len(hashes)) 841 for i, hash := range hashes { 842 if tx := pool.all[hash]; tx != nil { 843 from, _ := types.Sender(pool.signer, tx) // already validated 844 if pool.pending[from] != nil && pool.pending[from].txs.items[tx.Nonce()] != nil { 845 status[i] = TxStatusPending 846 } else { 847 status[i] = TxStatusQueued 848 } 849 } 850 } 851 return status 852 } 853 854 // Get returns a transaction if it is contained in the pool 855 // and nil otherwise. 856 func (pool *TxPool) Get(hash common.Hash) *types.Transaction { 857 pool.mu.RLock() 858 defer pool.mu.RUnlock() 859 860 return pool.all[hash] 861 } 862 863 // removeTx removes a single transaction from the queue, moving all subsequent 864 // transactions back to the future queue. 865 func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) { 866 // Fetch the transaction we wish to delete 867 tx, ok := pool.all[hash] 868 if !ok { 869 return 870 } 871 addr, _ := types.Sender(pool.signer, tx) // already validated during insertion 872 873 // Remove it from the list of known transactions 874 delete(pool.all, hash) 875 if outofbound { 876 pool.priced.Removed() 877 } 878 // Remove the transaction from the pending lists and reset the account nonce 879 if pending := pool.pending[addr]; pending != nil { 880 if removed, invalids := pending.Remove(tx); removed { 881 // If no more pending transactions are left, remove the list 882 if pending.Empty() { 883 delete(pool.pending, addr) 884 delete(pool.beats, addr) 885 } 886 // Postpone any invalidated transactions 887 for _, tx := range invalids { 888 pool.enqueueTx(tx.Hash(), tx) 889 } 890 // Update the account nonce if needed 891 if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce { 892 pool.pendingState.SetNonce(addr, nonce) 893 } 894 return 895 } 896 } 897 // Transaction is in the future queue 898 if future := pool.queue[addr]; future != nil { 899 future.Remove(tx) 900 if future.Empty() { 901 delete(pool.queue, addr) 902 } 903 } 904 } 905 906 // promoteExecutables moves transactions that have become processable from the 907 // future queue to the set of pending transactions. During this process, all 908 // invalidated transactions (low nonce, low balance) are deleted. 909 func (pool *TxPool) promoteExecutables(accounts []common.Address) { 910 // Gather all the accounts potentially needing updates 911 if accounts == nil { 912 accounts = make([]common.Address, 0, len(pool.queue)) 913 for addr := range pool.queue { 914 accounts = append(accounts, addr) 915 } 916 } 917 // Iterate over all accounts and promote any executable transactions 918 for _, addr := range accounts { 919 list := pool.queue[addr] 920 if list == nil { 921 continue // Just in case someone calls with a non existing account 922 } 923 // Drop all transactions that are deemed too old (low nonce) 924 for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) { 925 hash := tx.Hash() 926 log.Trace("Removed old queued transaction", "hash", hash) 927 delete(pool.all, hash) 928 pool.priced.Removed() 929 } 930 // Drop all transactions that are too costly (low balance or out of gas) 931 drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas) 932 for _, tx := range drops { 933 hash := tx.Hash() 934 log.Trace("Removed unpayable queued transaction", "hash", hash) 935 delete(pool.all, hash) 936 pool.priced.Removed() 937 queuedNofundsCounter.Inc(1) 938 } 939 // Gather all executable transactions and promote them 940 for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) { 941 hash := tx.Hash() 942 log.Trace("Promoting queued transaction", "hash", hash) 943 pool.promoteTx(addr, hash, tx) 944 } 945 // Drop all transactions over the allowed limit 946 if !pool.locals.contains(addr) { 947 for _, tx := range list.Cap(int(pool.config.AccountQueue)) { 948 hash := tx.Hash() 949 delete(pool.all, hash) 950 pool.priced.Removed() 951 queuedRateLimitCounter.Inc(1) 952 log.Trace("Removed cap-exceeding queued transaction", "hash", hash) 953 } 954 } 955 // Delete the entire queue entry if it became empty. 956 if list.Empty() { 957 delete(pool.queue, addr) 958 } 959 } 960 // If the pending limit is overflown, start equalizing allowances 961 pending := uint64(0) 962 for _, list := range pool.pending { 963 pending += uint64(list.Len()) 964 } 965 if pending > pool.config.GlobalSlots { 966 pendingBeforeCap := pending 967 // Assemble a spam order to penalize large transactors first 968 spammers := prque.New() 969 for addr, list := range pool.pending { 970 // Only evict transactions from high rollers 971 if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots { 972 spammers.Push(addr, float32(list.Len())) 973 } 974 } 975 // Gradually drop transactions from offenders 976 offenders := []common.Address{} 977 for pending > pool.config.GlobalSlots && !spammers.Empty() { 978 // Retrieve the next offender if not local address 979 offender, _ := spammers.Pop() 980 offenders = append(offenders, offender.(common.Address)) 981 982 // Equalize balances until all the same or below threshold 983 if len(offenders) > 1 { 984 // Calculate the equalization threshold for all current offenders 985 threshold := pool.pending[offender.(common.Address)].Len() 986 987 // Iteratively reduce all offenders until below limit or threshold reached 988 for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold { 989 for i := 0; i < len(offenders)-1; i++ { 990 list := pool.pending[offenders[i]] 991 for _, tx := range list.Cap(list.Len() - 1) { 992 // Drop the transaction from the global pools too 993 hash := tx.Hash() 994 delete(pool.all, hash) 995 pool.priced.Removed() 996 997 // Update the account nonce to the dropped transaction 998 if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce { 999 pool.pendingState.SetNonce(offenders[i], nonce) 1000 } 1001 log.Trace("Removed fairness-exceeding pending transaction", "hash", hash) 1002 } 1003 pending-- 1004 } 1005 } 1006 } 1007 } 1008 // If still above threshold, reduce to limit or min allowance 1009 if pending > pool.config.GlobalSlots && len(offenders) > 0 { 1010 for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots { 1011 for _, addr := range offenders { 1012 list := pool.pending[addr] 1013 for _, tx := range list.Cap(list.Len() - 1) { 1014 // Drop the transaction from the global pools too 1015 hash := tx.Hash() 1016 delete(pool.all, hash) 1017 pool.priced.Removed() 1018 1019 // Update the account nonce to the dropped transaction 1020 if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce { 1021 pool.pendingState.SetNonce(addr, nonce) 1022 } 1023 log.Trace("Removed fairness-exceeding pending transaction", "hash", hash) 1024 } 1025 pending-- 1026 } 1027 } 1028 } 1029 pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending)) 1030 } 1031 // If we've queued more transactions than the hard limit, drop oldest ones 1032 queued := uint64(0) 1033 for _, list := range pool.queue { 1034 queued += uint64(list.Len()) 1035 } 1036 if queued > pool.config.GlobalQueue { 1037 // Sort all accounts with queued transactions by heartbeat 1038 addresses := make(addresssByHeartbeat, 0, len(pool.queue)) 1039 for addr := range pool.queue { 1040 if !pool.locals.contains(addr) { // don't drop locals 1041 addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]}) 1042 } 1043 } 1044 sort.Sort(addresses) 1045 1046 // Drop transactions until the total is below the limit or only locals remain 1047 for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; { 1048 addr := addresses[len(addresses)-1] 1049 list := pool.queue[addr.address] 1050 1051 addresses = addresses[:len(addresses)-1] 1052 1053 // Drop all transactions if they are less than the overflow 1054 if size := uint64(list.Len()); size <= drop { 1055 for _, tx := range list.Flatten() { 1056 pool.removeTx(tx.Hash(), true) 1057 } 1058 drop -= size 1059 queuedRateLimitCounter.Inc(int64(size)) 1060 continue 1061 } 1062 // Otherwise drop only last few transactions 1063 txs := list.Flatten() 1064 for i := len(txs) - 1; i >= 0 && drop > 0; i-- { 1065 pool.removeTx(txs[i].Hash(), true) 1066 drop-- 1067 queuedRateLimitCounter.Inc(1) 1068 } 1069 } 1070 } 1071 } 1072 1073 // demoteUnexecutables removes invalid and processed transactions from the pools 1074 // executable/pending queue and any subsequent transactions that become unexecutable 1075 // are moved back into the future queue. 1076 func (pool *TxPool) demoteUnexecutables() { 1077 // Iterate over all accounts and demote any non-executable transactions 1078 for addr, list := range pool.pending { 1079 nonce := pool.currentState.GetNonce(addr) 1080 1081 // Drop all transactions that are deemed too old (low nonce) 1082 for _, tx := range list.Forward(nonce) { 1083 hash := tx.Hash() 1084 log.Trace("Removed old pending transaction", "hash", hash) 1085 delete(pool.all, hash) 1086 pool.priced.Removed() 1087 } 1088 // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later 1089 drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas) 1090 for _, tx := range drops { 1091 hash := tx.Hash() 1092 log.Trace("Removed unpayable pending transaction", "hash", hash) 1093 delete(pool.all, hash) 1094 pool.priced.Removed() 1095 pendingNofundsCounter.Inc(1) 1096 } 1097 for _, tx := range invalids { 1098 hash := tx.Hash() 1099 log.Trace("Demoting pending transaction", "hash", hash) 1100 pool.enqueueTx(hash, tx) 1101 } 1102 // If there's a gap in front, warn (should never happen) and postpone all transactions 1103 if list.Len() > 0 && list.txs.Get(nonce) == nil { 1104 for _, tx := range list.Cap(0) { 1105 hash := tx.Hash() 1106 log.Error("Demoting invalidated transaction", "hash", hash) 1107 pool.enqueueTx(hash, tx) 1108 } 1109 } 1110 // Delete the entire queue entry if it became empty. 1111 if list.Empty() { 1112 delete(pool.pending, addr) 1113 delete(pool.beats, addr) 1114 } 1115 } 1116 } 1117 1118 // addressByHeartbeat is an account address tagged with its last activity timestamp. 1119 type addressByHeartbeat struct { 1120 address common.Address 1121 heartbeat time.Time 1122 } 1123 1124 type addresssByHeartbeat []addressByHeartbeat 1125 1126 func (a addresssByHeartbeat) Len() int { return len(a) } 1127 func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) } 1128 func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 1129 1130 // accountSet is simply a set of addresses to check for existence, and a signer 1131 // capable of deriving addresses from transactions. 1132 type accountSet struct { 1133 accounts map[common.Address]struct{} 1134 signer types.Signer 1135 } 1136 1137 // newAccountSet creates a new address set with an associated signer for sender 1138 // derivations. 1139 func newAccountSet(signer types.Signer) *accountSet { 1140 return &accountSet{ 1141 accounts: make(map[common.Address]struct{}), 1142 signer: signer, 1143 } 1144 } 1145 1146 // contains checks if a given address is contained within the set. 1147 func (as *accountSet) contains(addr common.Address) bool { 1148 _, exist := as.accounts[addr] 1149 return exist 1150 } 1151 1152 // containsTx checks if the sender of a given tx is within the set. If the sender 1153 // cannot be derived, this method returns false. 1154 func (as *accountSet) containsTx(tx *types.Transaction) bool { 1155 if addr, err := types.Sender(as.signer, tx); err == nil { 1156 return as.contains(addr) 1157 } 1158 return false 1159 } 1160 1161 // add inserts a new address into the set to track. 1162 func (as *accountSet) add(addr common.Address) { 1163 as.accounts[addr] = struct{}{} 1164 }