tx_pool.go 42 KB

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