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