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