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