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