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