tx_pool.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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 map[common.Hash]*types.Transaction // 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: make(map[common.Hash]*types.Transaction),
  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.AddLocal); 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. // SubscribeTxPreEvent registers a subscription of TxPreEvent and
  381. // starts sending event to the given channel.
  382. func (pool *TxPool) SubscribeTxPreEvent(ch chan<- TxPreEvent) 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[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(len(pool.all)) >= 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(len(pool.all)-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. delete(pool.all, old.Hash())
  563. pool.priced.Removed()
  564. pendingReplaceCounter.Inc(1)
  565. }
  566. pool.all[tx.Hash()] = 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(TxPreEvent{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. delete(pool.all, old.Hash())
  605. pool.priced.Removed()
  606. queuedReplaceCounter.Inc(1)
  607. }
  608. if pool.all[hash] == nil {
  609. pool.all[hash] = 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. //
  627. // Note, this method assumes the pool lock is held!
  628. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) {
  629. // Try to insert the transaction into the pending queue
  630. if pool.pending[addr] == nil {
  631. pool.pending[addr] = newTxList(true)
  632. }
  633. list := pool.pending[addr]
  634. inserted, old := list.Add(tx, pool.config.PriceBump)
  635. if !inserted {
  636. // An older transaction was better, discard this
  637. delete(pool.all, hash)
  638. pool.priced.Removed()
  639. pendingDiscardCounter.Inc(1)
  640. return
  641. }
  642. // Otherwise discard any previous transaction and mark this
  643. if old != nil {
  644. delete(pool.all, old.Hash())
  645. pool.priced.Removed()
  646. pendingReplaceCounter.Inc(1)
  647. }
  648. // Failsafe to work around direct pending inserts (tests)
  649. if pool.all[hash] == nil {
  650. pool.all[hash] = tx
  651. pool.priced.Put(tx)
  652. }
  653. // Set the potentially new pending nonce and notify any subsystems of the new tx
  654. pool.beats[addr] = time.Now()
  655. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  656. go pool.txFeed.Send(TxPreEvent{tx})
  657. }
  658. // AddLocal enqueues a single transaction into the pool if it is valid, marking
  659. // the sender as a local one in the mean time, ensuring it goes around the local
  660. // pricing constraints.
  661. func (pool *TxPool) AddLocal(tx *types.Transaction) error {
  662. return pool.addTx(tx, !pool.config.NoLocals)
  663. }
  664. // AddRemote enqueues a single transaction into the pool if it is valid. If the
  665. // sender is not among the locally tracked ones, full pricing constraints will
  666. // apply.
  667. func (pool *TxPool) AddRemote(tx *types.Transaction) error {
  668. return pool.addTx(tx, false)
  669. }
  670. // AddLocals enqueues a batch of transactions into the pool if they are valid,
  671. // marking the senders as a local ones in the mean time, ensuring they go around
  672. // the local pricing constraints.
  673. func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
  674. return pool.addTxs(txs, !pool.config.NoLocals)
  675. }
  676. // AddRemotes enqueues a batch of transactions into the pool if they are valid.
  677. // If the senders are not among the locally tracked ones, full pricing constraints
  678. // will apply.
  679. func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
  680. return pool.addTxs(txs, false)
  681. }
  682. // addTx enqueues a single transaction into the pool if it is valid.
  683. func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
  684. pool.mu.Lock()
  685. defer pool.mu.Unlock()
  686. // Try to inject the transaction and update any state
  687. replace, err := pool.add(tx, local)
  688. if err != nil {
  689. return err
  690. }
  691. // If we added a new transaction, run promotion checks and return
  692. if !replace {
  693. from, _ := types.Sender(pool.signer, tx) // already validated
  694. pool.promoteExecutables([]common.Address{from})
  695. }
  696. return nil
  697. }
  698. // addTxs attempts to queue a batch of transactions if they are valid.
  699. func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) []error {
  700. pool.mu.Lock()
  701. defer pool.mu.Unlock()
  702. return pool.addTxsLocked(txs, local)
  703. }
  704. // addTxsLocked attempts to queue a batch of transactions if they are valid,
  705. // whilst assuming the transaction pool lock is already held.
  706. func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error {
  707. // Add the batch of transaction, tracking the accepted ones
  708. dirty := make(map[common.Address]struct{})
  709. errs := make([]error, len(txs))
  710. for i, tx := range txs {
  711. var replace bool
  712. if replace, errs[i] = pool.add(tx, local); errs[i] == nil {
  713. if !replace {
  714. from, _ := types.Sender(pool.signer, tx) // already validated
  715. dirty[from] = struct{}{}
  716. }
  717. }
  718. }
  719. // Only reprocess the internal state if something was actually added
  720. if len(dirty) > 0 {
  721. addrs := make([]common.Address, 0, len(dirty))
  722. for addr := range dirty {
  723. addrs = append(addrs, addr)
  724. }
  725. pool.promoteExecutables(addrs)
  726. }
  727. return errs
  728. }
  729. // Status returns the status (unknown/pending/queued) of a batch of transactions
  730. // identified by their hashes.
  731. func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
  732. pool.mu.RLock()
  733. defer pool.mu.RUnlock()
  734. status := make([]TxStatus, len(hashes))
  735. for i, hash := range hashes {
  736. if tx := pool.all[hash]; tx != nil {
  737. from, _ := types.Sender(pool.signer, tx) // already validated
  738. if pool.pending[from] != nil && pool.pending[from].txs.items[tx.Nonce()] != nil {
  739. status[i] = TxStatusPending
  740. } else {
  741. status[i] = TxStatusQueued
  742. }
  743. }
  744. }
  745. return status
  746. }
  747. // Get returns a transaction if it is contained in the pool
  748. // and nil otherwise.
  749. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  750. pool.mu.RLock()
  751. defer pool.mu.RUnlock()
  752. return pool.all[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, ok := pool.all[hash]
  759. if !ok {
  760. return
  761. }
  762. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  763. // Remove it from the list of known transactions
  764. delete(pool.all, 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. // Gather all the accounts potentially needing updates
  800. if accounts == nil {
  801. accounts = make([]common.Address, 0, len(pool.queue))
  802. for addr := range pool.queue {
  803. accounts = append(accounts, addr)
  804. }
  805. }
  806. // Iterate over all accounts and promote any executable transactions
  807. for _, addr := range accounts {
  808. list := pool.queue[addr]
  809. if list == nil {
  810. continue // Just in case someone calls with a non existing account
  811. }
  812. // Drop all transactions that are deemed too old (low nonce)
  813. for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) {
  814. hash := tx.Hash()
  815. log.Trace("Removed old queued transaction", "hash", hash)
  816. delete(pool.all, hash)
  817. pool.priced.Removed()
  818. }
  819. // Drop all transactions that are too costly (low balance or out of gas)
  820. drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  821. for _, tx := range drops {
  822. hash := tx.Hash()
  823. log.Trace("Removed unpayable queued transaction", "hash", hash)
  824. delete(pool.all, hash)
  825. pool.priced.Removed()
  826. queuedNofundsCounter.Inc(1)
  827. }
  828. // Gather all executable transactions and promote them
  829. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  830. hash := tx.Hash()
  831. log.Trace("Promoting queued transaction", "hash", hash)
  832. pool.promoteTx(addr, hash, tx)
  833. }
  834. // Drop all transactions over the allowed limit
  835. if !pool.locals.contains(addr) {
  836. for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
  837. hash := tx.Hash()
  838. delete(pool.all, hash)
  839. pool.priced.Removed()
  840. queuedRateLimitCounter.Inc(1)
  841. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  842. }
  843. }
  844. // Delete the entire queue entry if it became empty.
  845. if list.Empty() {
  846. delete(pool.queue, addr)
  847. }
  848. }
  849. // If the pending limit is overflown, start equalizing allowances
  850. pending := uint64(0)
  851. for _, list := range pool.pending {
  852. pending += uint64(list.Len())
  853. }
  854. if pending > pool.config.GlobalSlots {
  855. pendingBeforeCap := pending
  856. // Assemble a spam order to penalize large transactors first
  857. spammers := prque.New()
  858. for addr, list := range pool.pending {
  859. // Only evict transactions from high rollers
  860. if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  861. spammers.Push(addr, float32(list.Len()))
  862. }
  863. }
  864. // Gradually drop transactions from offenders
  865. offenders := []common.Address{}
  866. for pending > pool.config.GlobalSlots && !spammers.Empty() {
  867. // Retrieve the next offender if not local address
  868. offender, _ := spammers.Pop()
  869. offenders = append(offenders, offender.(common.Address))
  870. // Equalize balances until all the same or below threshold
  871. if len(offenders) > 1 {
  872. // Calculate the equalization threshold for all current offenders
  873. threshold := pool.pending[offender.(common.Address)].Len()
  874. // Iteratively reduce all offenders until below limit or threshold reached
  875. for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  876. for i := 0; i < len(offenders)-1; i++ {
  877. list := pool.pending[offenders[i]]
  878. for _, tx := range list.Cap(list.Len() - 1) {
  879. // Drop the transaction from the global pools too
  880. hash := tx.Hash()
  881. delete(pool.all, hash)
  882. pool.priced.Removed()
  883. // Update the account nonce to the dropped transaction
  884. if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce {
  885. pool.pendingState.SetNonce(offenders[i], nonce)
  886. }
  887. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  888. }
  889. pending--
  890. }
  891. }
  892. }
  893. }
  894. // If still above threshold, reduce to limit or min allowance
  895. if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  896. for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  897. for _, addr := range offenders {
  898. list := pool.pending[addr]
  899. for _, tx := range list.Cap(list.Len() - 1) {
  900. // Drop the transaction from the global pools too
  901. hash := tx.Hash()
  902. delete(pool.all, hash)
  903. pool.priced.Removed()
  904. // Update the account nonce to the dropped transaction
  905. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  906. pool.pendingState.SetNonce(addr, nonce)
  907. }
  908. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  909. }
  910. pending--
  911. }
  912. }
  913. }
  914. pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending))
  915. }
  916. // If we've queued more transactions than the hard limit, drop oldest ones
  917. queued := uint64(0)
  918. for _, list := range pool.queue {
  919. queued += uint64(list.Len())
  920. }
  921. if queued > pool.config.GlobalQueue {
  922. // Sort all accounts with queued transactions by heartbeat
  923. addresses := make(addresssByHeartbeat, 0, len(pool.queue))
  924. for addr := range pool.queue {
  925. if !pool.locals.contains(addr) { // don't drop locals
  926. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  927. }
  928. }
  929. sort.Sort(addresses)
  930. // Drop transactions until the total is below the limit or only locals remain
  931. for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  932. addr := addresses[len(addresses)-1]
  933. list := pool.queue[addr.address]
  934. addresses = addresses[:len(addresses)-1]
  935. // Drop all transactions if they are less than the overflow
  936. if size := uint64(list.Len()); size <= drop {
  937. for _, tx := range list.Flatten() {
  938. pool.removeTx(tx.Hash(), true)
  939. }
  940. drop -= size
  941. queuedRateLimitCounter.Inc(int64(size))
  942. continue
  943. }
  944. // Otherwise drop only last few transactions
  945. txs := list.Flatten()
  946. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  947. pool.removeTx(txs[i].Hash(), true)
  948. drop--
  949. queuedRateLimitCounter.Inc(1)
  950. }
  951. }
  952. }
  953. }
  954. // demoteUnexecutables removes invalid and processed transactions from the pools
  955. // executable/pending queue and any subsequent transactions that become unexecutable
  956. // are moved back into the future queue.
  957. func (pool *TxPool) demoteUnexecutables() {
  958. // Iterate over all accounts and demote any non-executable transactions
  959. for addr, list := range pool.pending {
  960. nonce := pool.currentState.GetNonce(addr)
  961. // Drop all transactions that are deemed too old (low nonce)
  962. for _, tx := range list.Forward(nonce) {
  963. hash := tx.Hash()
  964. log.Trace("Removed old pending transaction", "hash", hash)
  965. delete(pool.all, hash)
  966. pool.priced.Removed()
  967. }
  968. // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  969. drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  970. for _, tx := range drops {
  971. hash := tx.Hash()
  972. log.Trace("Removed unpayable pending transaction", "hash", hash)
  973. delete(pool.all, hash)
  974. pool.priced.Removed()
  975. pendingNofundsCounter.Inc(1)
  976. }
  977. for _, tx := range invalids {
  978. hash := tx.Hash()
  979. log.Trace("Demoting pending transaction", "hash", hash)
  980. pool.enqueueTx(hash, tx)
  981. }
  982. // If there's a gap in front, warn (should never happen) and postpone all transactions
  983. if list.Len() > 0 && list.txs.Get(nonce) == nil {
  984. for _, tx := range list.Cap(0) {
  985. hash := tx.Hash()
  986. log.Error("Demoting invalidated transaction", "hash", hash)
  987. pool.enqueueTx(hash, tx)
  988. }
  989. }
  990. // Delete the entire queue entry if it became empty.
  991. if list.Empty() {
  992. delete(pool.pending, addr)
  993. delete(pool.beats, addr)
  994. }
  995. }
  996. }
  997. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  998. type addressByHeartbeat struct {
  999. address common.Address
  1000. heartbeat time.Time
  1001. }
  1002. type addresssByHeartbeat []addressByHeartbeat
  1003. func (a addresssByHeartbeat) Len() int { return len(a) }
  1004. func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  1005. func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1006. // accountSet is simply a set of addresses to check for existence, and a signer
  1007. // capable of deriving addresses from transactions.
  1008. type accountSet struct {
  1009. accounts map[common.Address]struct{}
  1010. signer types.Signer
  1011. }
  1012. // newAccountSet creates a new address set with an associated signer for sender
  1013. // derivations.
  1014. func newAccountSet(signer types.Signer) *accountSet {
  1015. return &accountSet{
  1016. accounts: make(map[common.Address]struct{}),
  1017. signer: signer,
  1018. }
  1019. }
  1020. // contains checks if a given address is contained within the set.
  1021. func (as *accountSet) contains(addr common.Address) bool {
  1022. _, exist := as.accounts[addr]
  1023. return exist
  1024. }
  1025. // containsTx checks if the sender of a given tx is within the set. If the sender
  1026. // cannot be derived, this method returns false.
  1027. func (as *accountSet) containsTx(tx *types.Transaction) bool {
  1028. if addr, err := types.Sender(as.signer, tx); err == nil {
  1029. return as.contains(addr)
  1030. }
  1031. return false
  1032. }
  1033. // add inserts a new address into the set to track.
  1034. func (as *accountSet) add(addr common.Address) {
  1035. as.accounts[addr] = struct{}{}
  1036. }