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