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. pool.addTxsLocked(reinject, false)
  354. // validate the pool of pending transactions, this will remove
  355. // any transactions that have been included in the block or
  356. // have been invalidated because of another transaction (e.g.
  357. // higher gas price)
  358. pool.demoteUnexecutables()
  359. // Update all accounts to the latest known pending nonce
  360. for addr, list := range pool.pending {
  361. txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway
  362. pool.pendingState.SetNonce(addr, txs[len(txs)-1].Nonce()+1)
  363. }
  364. // Check the queue and move transactions over to the pending if possible
  365. // or remove those that have become invalid
  366. pool.promoteExecutables(nil)
  367. }
  368. // Stop terminates the transaction pool.
  369. func (pool *TxPool) Stop() {
  370. // Unsubscribe all subscriptions registered from txpool
  371. pool.scope.Close()
  372. // Unsubscribe subscriptions registered from blockchain
  373. pool.chainHeadSub.Unsubscribe()
  374. pool.wg.Wait()
  375. if pool.journal != nil {
  376. pool.journal.close()
  377. }
  378. log.Info("Transaction pool stopped")
  379. }
  380. // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
  381. // starts sending event to the given channel.
  382. func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
  383. return pool.scope.Track(pool.txFeed.Subscribe(ch))
  384. }
  385. // GasPrice returns the current gas price enforced by the transaction pool.
  386. func (pool *TxPool) GasPrice() *big.Int {
  387. pool.mu.RLock()
  388. defer pool.mu.RUnlock()
  389. return new(big.Int).Set(pool.gasPrice)
  390. }
  391. // SetGasPrice updates the minimum price required by the transaction pool for a
  392. // new transaction, and drops all transactions below this threshold.
  393. func (pool *TxPool) SetGasPrice(price *big.Int) {
  394. pool.mu.Lock()
  395. defer pool.mu.Unlock()
  396. pool.gasPrice = price
  397. for _, tx := range pool.priced.Cap(price, pool.locals) {
  398. pool.removeTx(tx.Hash(), false)
  399. }
  400. log.Info("Transaction pool price threshold updated", "price", price)
  401. }
  402. // State returns the virtual managed state of the transaction pool.
  403. func (pool *TxPool) State() *state.ManagedState {
  404. pool.mu.RLock()
  405. defer pool.mu.RUnlock()
  406. return pool.pendingState
  407. }
  408. // Stats retrieves the current pool stats, namely the number of pending and the
  409. // number of queued (non-executable) transactions.
  410. func (pool *TxPool) Stats() (int, int) {
  411. pool.mu.RLock()
  412. defer pool.mu.RUnlock()
  413. return pool.stats()
  414. }
  415. // stats retrieves the current pool stats, namely the number of pending and the
  416. // number of queued (non-executable) transactions.
  417. func (pool *TxPool) stats() (int, int) {
  418. pending := 0
  419. for _, list := range pool.pending {
  420. pending += list.Len()
  421. }
  422. queued := 0
  423. for _, list := range pool.queue {
  424. queued += list.Len()
  425. }
  426. return pending, queued
  427. }
  428. // Content retrieves the data content of the transaction pool, returning all the
  429. // pending as well as queued transactions, grouped by account and sorted by nonce.
  430. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  431. pool.mu.Lock()
  432. defer pool.mu.Unlock()
  433. pending := make(map[common.Address]types.Transactions)
  434. for addr, list := range pool.pending {
  435. pending[addr] = list.Flatten()
  436. }
  437. queued := make(map[common.Address]types.Transactions)
  438. for addr, list := range pool.queue {
  439. queued[addr] = list.Flatten()
  440. }
  441. return pending, queued
  442. }
  443. // Pending retrieves all currently processable transactions, groupped by origin
  444. // account and sorted by nonce. The returned transaction set is a copy and can be
  445. // freely modified by calling code.
  446. func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
  447. pool.mu.Lock()
  448. defer pool.mu.Unlock()
  449. pending := make(map[common.Address]types.Transactions)
  450. for addr, list := range pool.pending {
  451. pending[addr] = list.Flatten()
  452. }
  453. return pending, nil
  454. }
  455. // local retrieves all currently known local transactions, groupped by origin
  456. // account and sorted by nonce. The returned transaction set is a copy and can be
  457. // freely modified by calling code.
  458. func (pool *TxPool) local() map[common.Address]types.Transactions {
  459. txs := make(map[common.Address]types.Transactions)
  460. for addr := range pool.locals.accounts {
  461. if pending := pool.pending[addr]; pending != nil {
  462. txs[addr] = append(txs[addr], pending.Flatten()...)
  463. }
  464. if queued := pool.queue[addr]; queued != nil {
  465. txs[addr] = append(txs[addr], queued.Flatten()...)
  466. }
  467. }
  468. return txs
  469. }
  470. // validateTx checks whether a transaction is valid according to the consensus
  471. // rules and adheres to some heuristic limits of the local node (price and size).
  472. func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
  473. // Heuristic limit, reject transactions over 32KB to prevent DOS attacks
  474. if tx.Size() > 32*1024 {
  475. return ErrOversizedData
  476. }
  477. // Transactions can't be negative. This may never happen using RLP decoded
  478. // transactions but may occur if you create a transaction using the RPC.
  479. if tx.Value().Sign() < 0 {
  480. return ErrNegativeValue
  481. }
  482. // Ensure the transaction doesn't exceed the current block limit gas.
  483. if pool.currentMaxGas < tx.Gas() {
  484. return ErrGasLimit
  485. }
  486. // Make sure the transaction is signed properly
  487. from, err := types.Sender(pool.signer, tx)
  488. if err != nil {
  489. return ErrInvalidSender
  490. }
  491. // Drop non-local transactions under our own minimal accepted gas price
  492. local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network
  493. if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 {
  494. return ErrUnderpriced
  495. }
  496. // Ensure the transaction adheres to nonce ordering
  497. if pool.currentState.GetNonce(from) > tx.Nonce() {
  498. return ErrNonceTooLow
  499. }
  500. // Transactor should have enough funds to cover the costs
  501. // cost == V + GP * GL
  502. if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  503. return ErrInsufficientFunds
  504. }
  505. intrGas, err := IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead)
  506. if err != nil {
  507. return err
  508. }
  509. if tx.Gas() < intrGas {
  510. return ErrIntrinsicGas
  511. }
  512. return nil
  513. }
  514. // add validates a transaction and inserts it into the non-executable queue for
  515. // later pending promotion and execution. If the transaction is a replacement for
  516. // an already pending or queued one, it overwrites the previous and returns this
  517. // so outer code doesn't uselessly call promote.
  518. //
  519. // If a newly added transaction is marked as local, its sending account will be
  520. // whitelisted, preventing any associated transaction from being dropped out of
  521. // the pool due to pricing constraints.
  522. func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
  523. // If the transaction is already known, discard it
  524. hash := tx.Hash()
  525. if pool.all.Get(hash) != nil {
  526. log.Trace("Discarding already known transaction", "hash", hash)
  527. return false, fmt.Errorf("known transaction: %x", hash)
  528. }
  529. // If the transaction fails basic validation, discard it
  530. if err := pool.validateTx(tx, local); err != nil {
  531. log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
  532. invalidTxCounter.Inc(1)
  533. return false, err
  534. }
  535. // If the transaction pool is full, discard underpriced transactions
  536. if uint64(pool.all.Count()) >= pool.config.GlobalSlots+pool.config.GlobalQueue {
  537. // If the new transaction is underpriced, don't accept it
  538. if !local && pool.priced.Underpriced(tx, pool.locals) {
  539. log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
  540. underpricedTxCounter.Inc(1)
  541. return false, ErrUnderpriced
  542. }
  543. // New transaction is better than our worse ones, make room for it
  544. drop := pool.priced.Discard(pool.all.Count()-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals)
  545. for _, tx := range drop {
  546. log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
  547. underpricedTxCounter.Inc(1)
  548. pool.removeTx(tx.Hash(), false)
  549. }
  550. }
  551. // If the transaction is replacing an already pending one, do directly
  552. from, _ := types.Sender(pool.signer, tx) // already validated
  553. if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
  554. // Nonce already pending, check if required price bump is met
  555. inserted, old := list.Add(tx, pool.config.PriceBump)
  556. if !inserted {
  557. pendingDiscardCounter.Inc(1)
  558. return false, ErrReplaceUnderpriced
  559. }
  560. // New transaction is better, replace old one
  561. if old != nil {
  562. pool.all.Remove(old.Hash())
  563. pool.priced.Removed()
  564. pendingReplaceCounter.Inc(1)
  565. }
  566. pool.all.Add(tx)
  567. pool.priced.Put(tx)
  568. pool.journalTx(from, tx)
  569. log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
  570. // We've directly injected a replacement transaction, notify subsystems
  571. go pool.txFeed.Send(NewTxsEvent{types.Transactions{tx}})
  572. return old != nil, nil
  573. }
  574. // New transaction isn't replacing a pending one, push into queue
  575. replace, err := pool.enqueueTx(hash, tx)
  576. if err != nil {
  577. return false, err
  578. }
  579. // Mark local addresses and journal local transactions
  580. if local {
  581. pool.locals.add(from)
  582. }
  583. pool.journalTx(from, tx)
  584. log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
  585. return replace, nil
  586. }
  587. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  588. //
  589. // Note, this method assumes the pool lock is held!
  590. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) {
  591. // Try to insert the transaction into the future queue
  592. from, _ := types.Sender(pool.signer, tx) // already validated
  593. if pool.queue[from] == nil {
  594. pool.queue[from] = newTxList(false)
  595. }
  596. inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
  597. if !inserted {
  598. // An older transaction was better, discard this
  599. queuedDiscardCounter.Inc(1)
  600. return false, ErrReplaceUnderpriced
  601. }
  602. // Discard any previous transaction and mark this
  603. if old != nil {
  604. pool.all.Remove(old.Hash())
  605. pool.priced.Removed()
  606. queuedReplaceCounter.Inc(1)
  607. }
  608. if pool.all.Get(hash) == nil {
  609. pool.all.Add(tx)
  610. pool.priced.Put(tx)
  611. }
  612. return old != nil, nil
  613. }
  614. // journalTx adds the specified transaction to the local disk journal if it is
  615. // deemed to have been sent from a local account.
  616. func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
  617. // Only journal if it's enabled and the transaction is local
  618. if pool.journal == nil || !pool.locals.contains(from) {
  619. return
  620. }
  621. if err := pool.journal.insert(tx); err != nil {
  622. log.Warn("Failed to journal local transaction", "err", err)
  623. }
  624. }
  625. // promoteTx adds a transaction to the pending (processable) list of transactions
  626. // and returns whether it was inserted or an older was better.
  627. //
  628. // Note, this method assumes the pool lock is held!
  629. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool {
  630. // Try to insert the transaction into the pending queue
  631. if pool.pending[addr] == nil {
  632. pool.pending[addr] = newTxList(true)
  633. }
  634. list := pool.pending[addr]
  635. inserted, old := list.Add(tx, pool.config.PriceBump)
  636. if !inserted {
  637. // An older transaction was better, discard this
  638. pool.all.Remove(hash)
  639. pool.priced.Removed()
  640. pendingDiscardCounter.Inc(1)
  641. return false
  642. }
  643. // Otherwise discard any previous transaction and mark this
  644. if old != nil {
  645. pool.all.Remove(old.Hash())
  646. pool.priced.Removed()
  647. pendingReplaceCounter.Inc(1)
  648. }
  649. // Failsafe to work around direct pending inserts (tests)
  650. if pool.all.Get(hash) == nil {
  651. pool.all.Add(tx)
  652. pool.priced.Put(tx)
  653. }
  654. // Set the potentially new pending nonce and notify any subsystems of the new tx
  655. pool.beats[addr] = time.Now()
  656. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  657. return true
  658. }
  659. // AddLocal enqueues a single transaction into the pool if it is valid, marking
  660. // the sender as a local one in the mean time, ensuring it goes around the local
  661. // pricing constraints.
  662. func (pool *TxPool) AddLocal(tx *types.Transaction) error {
  663. return pool.addTx(tx, !pool.config.NoLocals)
  664. }
  665. // AddRemote enqueues a single transaction into the pool if it is valid. If the
  666. // sender is not among the locally tracked ones, full pricing constraints will
  667. // apply.
  668. func (pool *TxPool) AddRemote(tx *types.Transaction) error {
  669. return pool.addTx(tx, false)
  670. }
  671. // AddLocals enqueues a batch of transactions into the pool if they are valid,
  672. // marking the senders as a local ones in the mean time, ensuring they go around
  673. // the local pricing constraints.
  674. func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
  675. return pool.addTxs(txs, !pool.config.NoLocals)
  676. }
  677. // AddRemotes enqueues a batch of transactions into the pool if they are valid.
  678. // If the senders are not among the locally tracked ones, full pricing constraints
  679. // will apply.
  680. func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
  681. return pool.addTxs(txs, false)
  682. }
  683. // addTx enqueues a single transaction into the pool if it is valid.
  684. func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
  685. pool.mu.Lock()
  686. defer pool.mu.Unlock()
  687. // Try to inject the transaction and update any state
  688. replace, err := pool.add(tx, local)
  689. if err != nil {
  690. return err
  691. }
  692. // If we added a new transaction, run promotion checks and return
  693. if !replace {
  694. from, _ := types.Sender(pool.signer, tx) // already validated
  695. pool.promoteExecutables([]common.Address{from})
  696. }
  697. return nil
  698. }
  699. // addTxs attempts to queue a batch of transactions if they are valid.
  700. func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) []error {
  701. pool.mu.Lock()
  702. defer pool.mu.Unlock()
  703. return pool.addTxsLocked(txs, local)
  704. }
  705. // addTxsLocked attempts to queue a batch of transactions if they are valid,
  706. // whilst assuming the transaction pool lock is already held.
  707. func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error {
  708. // Add the batch of transaction, tracking the accepted ones
  709. dirty := make(map[common.Address]struct{})
  710. errs := make([]error, len(txs))
  711. for i, tx := range txs {
  712. var replace bool
  713. if replace, errs[i] = pool.add(tx, local); errs[i] == nil {
  714. if !replace {
  715. from, _ := types.Sender(pool.signer, tx) // already validated
  716. dirty[from] = struct{}{}
  717. }
  718. }
  719. }
  720. // Only reprocess the internal state if something was actually added
  721. if len(dirty) > 0 {
  722. addrs := make([]common.Address, 0, len(dirty))
  723. for addr := range dirty {
  724. addrs = append(addrs, addr)
  725. }
  726. pool.promoteExecutables(addrs)
  727. }
  728. return errs
  729. }
  730. // Status returns the status (unknown/pending/queued) of a batch of transactions
  731. // identified by their hashes.
  732. func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
  733. pool.mu.RLock()
  734. defer pool.mu.RUnlock()
  735. status := make([]TxStatus, len(hashes))
  736. for i, hash := range hashes {
  737. if tx := pool.all.Get(hash); tx != nil {
  738. from, _ := types.Sender(pool.signer, tx) // already validated
  739. if pool.pending[from] != nil && pool.pending[from].txs.items[tx.Nonce()] != nil {
  740. status[i] = TxStatusPending
  741. } else {
  742. status[i] = TxStatusQueued
  743. }
  744. }
  745. }
  746. return status
  747. }
  748. // Get returns a transaction if it is contained in the pool
  749. // and nil otherwise.
  750. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  751. return pool.all.Get(hash)
  752. }
  753. // removeTx removes a single transaction from the queue, moving all subsequent
  754. // transactions back to the future queue.
  755. func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {
  756. // Fetch the transaction we wish to delete
  757. tx := pool.all.Get(hash)
  758. if tx == nil {
  759. return
  760. }
  761. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  762. // Remove it from the list of known transactions
  763. pool.all.Remove(hash)
  764. if outofbound {
  765. pool.priced.Removed()
  766. }
  767. // Remove the transaction from the pending lists and reset the account nonce
  768. if pending := pool.pending[addr]; pending != nil {
  769. if removed, invalids := pending.Remove(tx); removed {
  770. // If no more pending transactions are left, remove the list
  771. if pending.Empty() {
  772. delete(pool.pending, addr)
  773. delete(pool.beats, addr)
  774. }
  775. // Postpone any invalidated transactions
  776. for _, tx := range invalids {
  777. pool.enqueueTx(tx.Hash(), tx)
  778. }
  779. // Update the account nonce if needed
  780. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  781. pool.pendingState.SetNonce(addr, nonce)
  782. }
  783. return
  784. }
  785. }
  786. // Transaction is in the future queue
  787. if future := pool.queue[addr]; future != nil {
  788. future.Remove(tx)
  789. if future.Empty() {
  790. delete(pool.queue, addr)
  791. }
  792. }
  793. }
  794. // promoteExecutables moves transactions that have become processable from the
  795. // future queue to the set of pending transactions. During this process, all
  796. // invalidated transactions (low nonce, low balance) are deleted.
  797. func (pool *TxPool) promoteExecutables(accounts []common.Address) {
  798. // Track the promoted transactions to broadcast them at once
  799. var promoted []*types.Transaction
  800. // Gather all the accounts potentially needing updates
  801. if accounts == nil {
  802. accounts = make([]common.Address, 0, len(pool.queue))
  803. for addr := range pool.queue {
  804. accounts = append(accounts, addr)
  805. }
  806. }
  807. // Iterate over all accounts and promote any executable transactions
  808. for _, addr := range accounts {
  809. list := pool.queue[addr]
  810. if list == nil {
  811. continue // Just in case someone calls with a non existing account
  812. }
  813. // Drop all transactions that are deemed too old (low nonce)
  814. for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) {
  815. hash := tx.Hash()
  816. log.Trace("Removed old queued transaction", "hash", hash)
  817. pool.all.Remove(hash)
  818. pool.priced.Removed()
  819. }
  820. // Drop all transactions that are too costly (low balance or out of gas)
  821. drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  822. for _, tx := range drops {
  823. hash := tx.Hash()
  824. log.Trace("Removed unpayable queued transaction", "hash", hash)
  825. pool.all.Remove(hash)
  826. pool.priced.Removed()
  827. queuedNofundsCounter.Inc(1)
  828. }
  829. // Gather all executable transactions and promote them
  830. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  831. hash := tx.Hash()
  832. if pool.promoteTx(addr, hash, tx) {
  833. log.Trace("Promoting queued transaction", "hash", hash)
  834. promoted = append(promoted, tx)
  835. }
  836. }
  837. // Drop all transactions over the allowed limit
  838. if !pool.locals.contains(addr) {
  839. for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
  840. hash := tx.Hash()
  841. pool.all.Remove(hash)
  842. pool.priced.Removed()
  843. queuedRateLimitCounter.Inc(1)
  844. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  845. }
  846. }
  847. // Delete the entire queue entry if it became empty.
  848. if list.Empty() {
  849. delete(pool.queue, addr)
  850. }
  851. }
  852. // Notify subsystem for new promoted transactions.
  853. if len(promoted) > 0 {
  854. go pool.txFeed.Send(NewTxsEvent{promoted})
  855. }
  856. // If the pending limit is overflown, start equalizing allowances
  857. pending := uint64(0)
  858. for _, list := range pool.pending {
  859. pending += uint64(list.Len())
  860. }
  861. if pending > pool.config.GlobalSlots {
  862. pendingBeforeCap := pending
  863. // Assemble a spam order to penalize large transactors first
  864. spammers := prque.New()
  865. for addr, list := range pool.pending {
  866. // Only evict transactions from high rollers
  867. if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  868. spammers.Push(addr, float32(list.Len()))
  869. }
  870. }
  871. // Gradually drop transactions from offenders
  872. offenders := []common.Address{}
  873. for pending > pool.config.GlobalSlots && !spammers.Empty() {
  874. // Retrieve the next offender if not local address
  875. offender, _ := spammers.Pop()
  876. offenders = append(offenders, offender.(common.Address))
  877. // Equalize balances until all the same or below threshold
  878. if len(offenders) > 1 {
  879. // Calculate the equalization threshold for all current offenders
  880. threshold := pool.pending[offender.(common.Address)].Len()
  881. // Iteratively reduce all offenders until below limit or threshold reached
  882. for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  883. for i := 0; i < len(offenders)-1; i++ {
  884. list := pool.pending[offenders[i]]
  885. for _, tx := range list.Cap(list.Len() - 1) {
  886. // Drop the transaction from the global pools too
  887. hash := tx.Hash()
  888. pool.all.Remove(hash)
  889. pool.priced.Removed()
  890. // Update the account nonce to the dropped transaction
  891. if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce {
  892. pool.pendingState.SetNonce(offenders[i], nonce)
  893. }
  894. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  895. }
  896. pending--
  897. }
  898. }
  899. }
  900. }
  901. // If still above threshold, reduce to limit or min allowance
  902. if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  903. for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  904. for _, addr := range offenders {
  905. list := pool.pending[addr]
  906. for _, tx := range list.Cap(list.Len() - 1) {
  907. // Drop the transaction from the global pools too
  908. hash := tx.Hash()
  909. pool.all.Remove(hash)
  910. pool.priced.Removed()
  911. // Update the account nonce to the dropped transaction
  912. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  913. pool.pendingState.SetNonce(addr, nonce)
  914. }
  915. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  916. }
  917. pending--
  918. }
  919. }
  920. }
  921. pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending))
  922. }
  923. // If we've queued more transactions than the hard limit, drop oldest ones
  924. queued := uint64(0)
  925. for _, list := range pool.queue {
  926. queued += uint64(list.Len())
  927. }
  928. if queued > pool.config.GlobalQueue {
  929. // Sort all accounts with queued transactions by heartbeat
  930. addresses := make(addresssByHeartbeat, 0, len(pool.queue))
  931. for addr := range pool.queue {
  932. if !pool.locals.contains(addr) { // don't drop locals
  933. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  934. }
  935. }
  936. sort.Sort(addresses)
  937. // Drop transactions until the total is below the limit or only locals remain
  938. for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  939. addr := addresses[len(addresses)-1]
  940. list := pool.queue[addr.address]
  941. addresses = addresses[:len(addresses)-1]
  942. // Drop all transactions if they are less than the overflow
  943. if size := uint64(list.Len()); size <= drop {
  944. for _, tx := range list.Flatten() {
  945. pool.removeTx(tx.Hash(), true)
  946. }
  947. drop -= size
  948. queuedRateLimitCounter.Inc(int64(size))
  949. continue
  950. }
  951. // Otherwise drop only last few transactions
  952. txs := list.Flatten()
  953. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  954. pool.removeTx(txs[i].Hash(), true)
  955. drop--
  956. queuedRateLimitCounter.Inc(1)
  957. }
  958. }
  959. }
  960. }
  961. // demoteUnexecutables removes invalid and processed transactions from the pools
  962. // executable/pending queue and any subsequent transactions that become unexecutable
  963. // are moved back into the future queue.
  964. func (pool *TxPool) demoteUnexecutables() {
  965. // Iterate over all accounts and demote any non-executable transactions
  966. for addr, list := range pool.pending {
  967. nonce := pool.currentState.GetNonce(addr)
  968. // Drop all transactions that are deemed too old (low nonce)
  969. for _, tx := range list.Forward(nonce) {
  970. hash := tx.Hash()
  971. log.Trace("Removed old pending transaction", "hash", hash)
  972. pool.all.Remove(hash)
  973. pool.priced.Removed()
  974. }
  975. // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  976. drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  977. for _, tx := range drops {
  978. hash := tx.Hash()
  979. log.Trace("Removed unpayable pending transaction", "hash", hash)
  980. pool.all.Remove(hash)
  981. pool.priced.Removed()
  982. pendingNofundsCounter.Inc(1)
  983. }
  984. for _, tx := range invalids {
  985. hash := tx.Hash()
  986. log.Trace("Demoting pending transaction", "hash", hash)
  987. pool.enqueueTx(hash, tx)
  988. }
  989. // If there's a gap in front, warn (should never happen) and postpone all transactions
  990. if list.Len() > 0 && list.txs.Get(nonce) == nil {
  991. for _, tx := range list.Cap(0) {
  992. hash := tx.Hash()
  993. log.Error("Demoting invalidated transaction", "hash", hash)
  994. pool.enqueueTx(hash, tx)
  995. }
  996. }
  997. // Delete the entire queue entry if it became empty.
  998. if list.Empty() {
  999. delete(pool.pending, addr)
  1000. delete(pool.beats, addr)
  1001. }
  1002. }
  1003. }
  1004. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  1005. type addressByHeartbeat struct {
  1006. address common.Address
  1007. heartbeat time.Time
  1008. }
  1009. type addresssByHeartbeat []addressByHeartbeat
  1010. func (a addresssByHeartbeat) Len() int { return len(a) }
  1011. func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  1012. func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1013. // accountSet is simply a set of addresses to check for existence, and a signer
  1014. // capable of deriving addresses from transactions.
  1015. type accountSet struct {
  1016. accounts map[common.Address]struct{}
  1017. signer types.Signer
  1018. }
  1019. // newAccountSet creates a new address set with an associated signer for sender
  1020. // derivations.
  1021. func newAccountSet(signer types.Signer) *accountSet {
  1022. return &accountSet{
  1023. accounts: make(map[common.Address]struct{}),
  1024. signer: signer,
  1025. }
  1026. }
  1027. // contains checks if a given address is contained within the set.
  1028. func (as *accountSet) contains(addr common.Address) bool {
  1029. _, exist := as.accounts[addr]
  1030. return exist
  1031. }
  1032. // containsTx checks if the sender of a given tx is within the set. If the sender
  1033. // cannot be derived, this method returns false.
  1034. func (as *accountSet) containsTx(tx *types.Transaction) bool {
  1035. if addr, err := types.Sender(as.signer, tx); err == nil {
  1036. return as.contains(addr)
  1037. }
  1038. return false
  1039. }
  1040. // add inserts a new address into the set to track.
  1041. func (as *accountSet) add(addr common.Address) {
  1042. as.accounts[addr] = struct{}{}
  1043. }
  1044. // txLookup is used internally by TxPool to track transactions while allowing lookup without
  1045. // mutex contention.
  1046. //
  1047. // Note, although this type is properly protected against concurrent access, it
  1048. // is **not** a type that should ever be mutated or even exposed outside of the
  1049. // transaction pool, since its internal state is tightly coupled with the pools
  1050. // internal mechanisms. The sole purpose of the type is to permit out-of-bound
  1051. // peeking into the pool in TxPool.Get without having to acquire the widely scoped
  1052. // TxPool.mu mutex.
  1053. type txLookup struct {
  1054. all map[common.Hash]*types.Transaction
  1055. lock sync.RWMutex
  1056. }
  1057. // newTxLookup returns a new txLookup structure.
  1058. func newTxLookup() *txLookup {
  1059. return &txLookup{
  1060. all: make(map[common.Hash]*types.Transaction),
  1061. }
  1062. }
  1063. // Range calls f on each key and value present in the map.
  1064. func (t *txLookup) Range(f func(hash common.Hash, tx *types.Transaction) bool) {
  1065. t.lock.RLock()
  1066. defer t.lock.RUnlock()
  1067. for key, value := range t.all {
  1068. if !f(key, value) {
  1069. break
  1070. }
  1071. }
  1072. }
  1073. // Get returns a transaction if it exists in the lookup, or nil if not found.
  1074. func (t *txLookup) Get(hash common.Hash) *types.Transaction {
  1075. t.lock.RLock()
  1076. defer t.lock.RUnlock()
  1077. return t.all[hash]
  1078. }
  1079. // Count returns the current number of items in the lookup.
  1080. func (t *txLookup) Count() int {
  1081. t.lock.RLock()
  1082. defer t.lock.RUnlock()
  1083. return len(t.all)
  1084. }
  1085. // Add adds a transaction to the lookup.
  1086. func (t *txLookup) Add(tx *types.Transaction) {
  1087. t.lock.Lock()
  1088. defer t.lock.Unlock()
  1089. t.all[tx.Hash()] = tx
  1090. }
  1091. // Remove removes a transaction from the lookup.
  1092. func (t *txLookup) Remove(hash common.Hash) {
  1093. t.lock.Lock()
  1094. defer t.lock.Unlock()
  1095. delete(t.all, hash)
  1096. }