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