tx_pool.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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 py 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 *big.Int // Current gas limit for transaction caps
  169. locals *accountSet // Set of local transaction to exepmt from evicion 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. // trnsactions 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.Warn("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.Cmp(tx.Gas()) < 0 {
  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 := IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead)
  508. if tx.Gas().Cmp(intrGas) < 0 {
  509. return ErrIntrinsicGas
  510. }
  511. return nil
  512. }
  513. // add validates a transaction and inserts it into the non-executable queue for
  514. // later pending promotion and execution. If the transaction is a replacement for
  515. // an already pending or queued one, it overwrites the previous and returns this
  516. // so outer code doesn't uselessly call promote.
  517. //
  518. // If a newly added transaction is marked as local, its sending account will be
  519. // whitelisted, preventing any associated transaction from being dropped out of
  520. // the pool due to pricing constraints.
  521. func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
  522. // If the transaction is already known, discard it
  523. hash := tx.Hash()
  524. if pool.all[hash] != nil {
  525. log.Trace("Discarding already known transaction", "hash", hash)
  526. return false, fmt.Errorf("known transaction: %x", hash)
  527. }
  528. // If the transaction fails basic validation, discard it
  529. if err := pool.validateTx(tx, local); err != nil {
  530. log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
  531. invalidTxCounter.Inc(1)
  532. return false, err
  533. }
  534. // If the transaction pool is full, discard underpriced transactions
  535. if uint64(len(pool.all)) >= pool.config.GlobalSlots+pool.config.GlobalQueue {
  536. // If the new transaction is underpriced, don't accept it
  537. if pool.priced.Underpriced(tx, pool.locals) {
  538. log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
  539. underpricedTxCounter.Inc(1)
  540. return false, ErrUnderpriced
  541. }
  542. // New transaction is better than our worse ones, make room for it
  543. drop := pool.priced.Discard(len(pool.all)-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals)
  544. for _, tx := range drop {
  545. log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
  546. underpricedTxCounter.Inc(1)
  547. pool.removeTx(tx.Hash())
  548. }
  549. }
  550. // If the transaction is replacing an already pending one, do directly
  551. from, _ := types.Sender(pool.signer, tx) // already validated
  552. if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
  553. // Nonce already pending, check if required price bump is met
  554. inserted, old := list.Add(tx, pool.config.PriceBump)
  555. if !inserted {
  556. pendingDiscardCounter.Inc(1)
  557. return false, ErrReplaceUnderpriced
  558. }
  559. // New transaction is better, replace old one
  560. if old != nil {
  561. delete(pool.all, old.Hash())
  562. pool.priced.Removed()
  563. pendingReplaceCounter.Inc(1)
  564. }
  565. pool.all[tx.Hash()] = tx
  566. pool.priced.Put(tx)
  567. pool.journalTx(from, tx)
  568. log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
  569. // We've directly injected a replacement transaction, notify subsystems
  570. go pool.txFeed.Send(TxPreEvent{tx})
  571. return old != nil, nil
  572. }
  573. // New transaction isn't replacing a pending one, push into queue
  574. replace, err := pool.enqueueTx(hash, tx)
  575. if err != nil {
  576. return false, err
  577. }
  578. // Mark local addresses and journal local transactions
  579. if local {
  580. pool.locals.add(from)
  581. }
  582. pool.journalTx(from, tx)
  583. log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
  584. return replace, nil
  585. }
  586. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  587. //
  588. // Note, this method assumes the pool lock is held!
  589. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) {
  590. // Try to insert the transaction into the future queue
  591. from, _ := types.Sender(pool.signer, tx) // already validated
  592. if pool.queue[from] == nil {
  593. pool.queue[from] = newTxList(false)
  594. }
  595. inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
  596. if !inserted {
  597. // An older transaction was better, discard this
  598. queuedDiscardCounter.Inc(1)
  599. return false, ErrReplaceUnderpriced
  600. }
  601. // Discard any previous transaction and mark this
  602. if old != nil {
  603. delete(pool.all, old.Hash())
  604. pool.priced.Removed()
  605. queuedReplaceCounter.Inc(1)
  606. }
  607. pool.all[hash] = tx
  608. pool.priced.Put(tx)
  609. return old != nil, nil
  610. }
  611. // journalTx adds the specified transaction to the local disk journal if it is
  612. // deemed to have been sent from a local account.
  613. func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
  614. // Only journal if it's enabled and the transaction is local
  615. if pool.journal == nil || !pool.locals.contains(from) {
  616. return
  617. }
  618. if err := pool.journal.insert(tx); err != nil {
  619. log.Warn("Failed to journal local transaction", "err", err)
  620. }
  621. }
  622. // promoteTx adds a transaction to the pending (processable) list of transactions.
  623. //
  624. // Note, this method assumes the pool lock is held!
  625. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) {
  626. // Try to insert the transaction into the pending queue
  627. if pool.pending[addr] == nil {
  628. pool.pending[addr] = newTxList(true)
  629. }
  630. list := pool.pending[addr]
  631. inserted, old := list.Add(tx, pool.config.PriceBump)
  632. if !inserted {
  633. // An older transaction was better, discard this
  634. delete(pool.all, hash)
  635. pool.priced.Removed()
  636. pendingDiscardCounter.Inc(1)
  637. return
  638. }
  639. // Otherwise discard any previous transaction and mark this
  640. if old != nil {
  641. delete(pool.all, old.Hash())
  642. pool.priced.Removed()
  643. pendingReplaceCounter.Inc(1)
  644. }
  645. // Failsafe to work around direct pending inserts (tests)
  646. if pool.all[hash] == nil {
  647. pool.all[hash] = tx
  648. pool.priced.Put(tx)
  649. }
  650. // Set the potentially new pending nonce and notify any subsystems of the new tx
  651. pool.beats[addr] = time.Now()
  652. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  653. go pool.txFeed.Send(TxPreEvent{tx})
  654. }
  655. // AddLocal enqueues a single transaction into the pool if it is valid, marking
  656. // the sender as a local one in the mean time, ensuring it goes around the local
  657. // pricing constraints.
  658. func (pool *TxPool) AddLocal(tx *types.Transaction) error {
  659. return pool.addTx(tx, !pool.config.NoLocals)
  660. }
  661. // AddRemote enqueues a single transaction into the pool if it is valid. If the
  662. // sender is not among the locally tracked ones, full pricing constraints will
  663. // apply.
  664. func (pool *TxPool) AddRemote(tx *types.Transaction) error {
  665. return pool.addTx(tx, false)
  666. }
  667. // AddLocals enqueues a batch of transactions into the pool if they are valid,
  668. // marking the senders as a local ones in the mean time, ensuring they go around
  669. // the local pricing constraints.
  670. func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
  671. return pool.addTxs(txs, !pool.config.NoLocals)
  672. }
  673. // AddRemotes enqueues a batch of transactions into the pool if they are valid.
  674. // If the senders are not among the locally tracked ones, full pricing constraints
  675. // will apply.
  676. func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
  677. return pool.addTxs(txs, false)
  678. }
  679. // addTx enqueues a single transaction into the pool if it is valid.
  680. func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
  681. pool.mu.Lock()
  682. defer pool.mu.Unlock()
  683. // Try to inject the transaction and update any state
  684. replace, err := pool.add(tx, local)
  685. if err != nil {
  686. return err
  687. }
  688. // If we added a new transaction, run promotion checks and return
  689. if !replace {
  690. from, _ := types.Sender(pool.signer, tx) // already validated
  691. pool.promoteExecutables([]common.Address{from})
  692. }
  693. return nil
  694. }
  695. // addTxs attempts to queue a batch of transactions if they are valid.
  696. func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) []error {
  697. pool.mu.Lock()
  698. defer pool.mu.Unlock()
  699. return pool.addTxsLocked(txs, local)
  700. }
  701. // addTxsLocked attempts to queue a batch of transactions if they are valid,
  702. // whilst assuming the transaction pool lock is already held.
  703. func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error {
  704. // Add the batch of transaction, tracking the accepted ones
  705. dirty := make(map[common.Address]struct{})
  706. errs := make([]error, len(txs))
  707. for i, tx := range txs {
  708. var replace bool
  709. if replace, errs[i] = pool.add(tx, local); errs[i] == nil {
  710. if !replace {
  711. from, _ := types.Sender(pool.signer, tx) // already validated
  712. dirty[from] = struct{}{}
  713. }
  714. }
  715. }
  716. // Only reprocess the internal state if something was actually added
  717. if len(dirty) > 0 {
  718. addrs := make([]common.Address, 0, len(dirty))
  719. for addr := range dirty {
  720. addrs = append(addrs, addr)
  721. }
  722. pool.promoteExecutables(addrs)
  723. }
  724. return errs
  725. }
  726. // Status returns the status (unknown/pending/queued) of a batch of transactions
  727. // identified by their hashes.
  728. func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
  729. pool.mu.RLock()
  730. defer pool.mu.RUnlock()
  731. status := make([]TxStatus, len(hashes))
  732. for i, hash := range hashes {
  733. if tx := pool.all[hash]; tx != nil {
  734. from, _ := types.Sender(pool.signer, tx) // already validated
  735. if pool.pending[from].txs.items[tx.Nonce()] != nil {
  736. status[i] = TxStatusPending
  737. } else {
  738. status[i] = TxStatusQueued
  739. }
  740. }
  741. }
  742. return status
  743. }
  744. // Get returns a transaction if it is contained in the pool
  745. // and nil otherwise.
  746. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  747. pool.mu.RLock()
  748. defer pool.mu.RUnlock()
  749. return pool.all[hash]
  750. }
  751. // removeTx removes a single transaction from the queue, moving all subsequent
  752. // transactions back to the future queue.
  753. func (pool *TxPool) removeTx(hash common.Hash) {
  754. // Fetch the transaction we wish to delete
  755. tx, ok := pool.all[hash]
  756. if !ok {
  757. return
  758. }
  759. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  760. // Remove it from the list of known transactions
  761. delete(pool.all, hash)
  762. pool.priced.Removed()
  763. // Remove the transaction from the pending lists and reset the account nonce
  764. if pending := pool.pending[addr]; pending != nil {
  765. if removed, invalids := pending.Remove(tx); removed {
  766. // If no more transactions are left, remove the list
  767. if pending.Empty() {
  768. delete(pool.pending, addr)
  769. delete(pool.beats, addr)
  770. } else {
  771. // Otherwise postpone any invalidated transactions
  772. for _, tx := range invalids {
  773. pool.enqueueTx(tx.Hash(), tx)
  774. }
  775. }
  776. // Update the account nonce if needed
  777. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  778. pool.pendingState.SetNonce(addr, nonce)
  779. }
  780. return
  781. }
  782. }
  783. // Transaction is in the future queue
  784. if future := pool.queue[addr]; future != nil {
  785. future.Remove(tx)
  786. if future.Empty() {
  787. delete(pool.queue, addr)
  788. }
  789. }
  790. }
  791. // promoteExecutables moves transactions that have become processable from the
  792. // future queue to the set of pending transactions. During this process, all
  793. // invalidated transactions (low nonce, low balance) are deleted.
  794. func (pool *TxPool) promoteExecutables(accounts []common.Address) {
  795. // Gather all the accounts potentially needing updates
  796. if accounts == nil {
  797. accounts = make([]common.Address, 0, len(pool.queue))
  798. for addr := range pool.queue {
  799. accounts = append(accounts, addr)
  800. }
  801. }
  802. // Iterate over all accounts and promote any executable transactions
  803. for _, addr := range accounts {
  804. list := pool.queue[addr]
  805. if list == nil {
  806. continue // Just in case someone calls with a non existing account
  807. }
  808. // Drop all transactions that are deemed too old (low nonce)
  809. for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) {
  810. hash := tx.Hash()
  811. log.Trace("Removed old queued transaction", "hash", hash)
  812. delete(pool.all, hash)
  813. pool.priced.Removed()
  814. }
  815. // Drop all transactions that are too costly (low balance or out of gas)
  816. drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  817. for _, tx := range drops {
  818. hash := tx.Hash()
  819. log.Trace("Removed unpayable queued transaction", "hash", hash)
  820. delete(pool.all, hash)
  821. pool.priced.Removed()
  822. queuedNofundsCounter.Inc(1)
  823. }
  824. // Gather all executable transactions and promote them
  825. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  826. hash := tx.Hash()
  827. log.Trace("Promoting queued transaction", "hash", hash)
  828. pool.promoteTx(addr, hash, tx)
  829. }
  830. // Drop all transactions over the allowed limit
  831. if !pool.locals.contains(addr) {
  832. for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
  833. hash := tx.Hash()
  834. delete(pool.all, hash)
  835. pool.priced.Removed()
  836. queuedRateLimitCounter.Inc(1)
  837. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  838. }
  839. }
  840. // Delete the entire queue entry if it became empty.
  841. if list.Empty() {
  842. delete(pool.queue, addr)
  843. }
  844. }
  845. // If the pending limit is overflown, start equalizing allowances
  846. pending := uint64(0)
  847. for _, list := range pool.pending {
  848. pending += uint64(list.Len())
  849. }
  850. if pending > pool.config.GlobalSlots {
  851. pendingBeforeCap := pending
  852. // Assemble a spam order to penalize large transactors first
  853. spammers := prque.New()
  854. for addr, list := range pool.pending {
  855. // Only evict transactions from high rollers
  856. if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  857. spammers.Push(addr, float32(list.Len()))
  858. }
  859. }
  860. // Gradually drop transactions from offenders
  861. offenders := []common.Address{}
  862. for pending > pool.config.GlobalSlots && !spammers.Empty() {
  863. // Retrieve the next offender if not local address
  864. offender, _ := spammers.Pop()
  865. offenders = append(offenders, offender.(common.Address))
  866. // Equalize balances until all the same or below threshold
  867. if len(offenders) > 1 {
  868. // Calculate the equalization threshold for all current offenders
  869. threshold := pool.pending[offender.(common.Address)].Len()
  870. // Iteratively reduce all offenders until below limit or threshold reached
  871. for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  872. for i := 0; i < len(offenders)-1; i++ {
  873. list := pool.pending[offenders[i]]
  874. for _, tx := range list.Cap(list.Len() - 1) {
  875. // Drop the transaction from the global pools too
  876. hash := tx.Hash()
  877. delete(pool.all, hash)
  878. pool.priced.Removed()
  879. // Update the account nonce to the dropped transaction
  880. if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce {
  881. pool.pendingState.SetNonce(offenders[i], nonce)
  882. }
  883. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  884. }
  885. pending--
  886. }
  887. }
  888. }
  889. }
  890. // If still above threshold, reduce to limit or min allowance
  891. if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  892. for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  893. for _, addr := range offenders {
  894. list := pool.pending[addr]
  895. for _, tx := range list.Cap(list.Len() - 1) {
  896. // Drop the transaction from the global pools too
  897. hash := tx.Hash()
  898. delete(pool.all, hash)
  899. pool.priced.Removed()
  900. // Update the account nonce to the dropped transaction
  901. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  902. pool.pendingState.SetNonce(addr, nonce)
  903. }
  904. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  905. }
  906. pending--
  907. }
  908. }
  909. }
  910. pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending))
  911. }
  912. // If we've queued more transactions than the hard limit, drop oldest ones
  913. queued := uint64(0)
  914. for _, list := range pool.queue {
  915. queued += uint64(list.Len())
  916. }
  917. if queued > pool.config.GlobalQueue {
  918. // Sort all accounts with queued transactions by heartbeat
  919. addresses := make(addresssByHeartbeat, 0, len(pool.queue))
  920. for addr := range pool.queue {
  921. if !pool.locals.contains(addr) { // don't drop locals
  922. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  923. }
  924. }
  925. sort.Sort(addresses)
  926. // Drop transactions until the total is below the limit or only locals remain
  927. for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  928. addr := addresses[len(addresses)-1]
  929. list := pool.queue[addr.address]
  930. addresses = addresses[:len(addresses)-1]
  931. // Drop all transactions if they are less than the overflow
  932. if size := uint64(list.Len()); size <= drop {
  933. for _, tx := range list.Flatten() {
  934. pool.removeTx(tx.Hash())
  935. }
  936. drop -= size
  937. queuedRateLimitCounter.Inc(int64(size))
  938. continue
  939. }
  940. // Otherwise drop only last few transactions
  941. txs := list.Flatten()
  942. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  943. pool.removeTx(txs[i].Hash())
  944. drop--
  945. queuedRateLimitCounter.Inc(1)
  946. }
  947. }
  948. }
  949. }
  950. // demoteUnexecutables removes invalid and processed transactions from the pools
  951. // executable/pending queue and any subsequent transactions that become unexecutable
  952. // are moved back into the future queue.
  953. func (pool *TxPool) demoteUnexecutables() {
  954. // Iterate over all accounts and demote any non-executable transactions
  955. for addr, list := range pool.pending {
  956. nonce := pool.currentState.GetNonce(addr)
  957. // Drop all transactions that are deemed too old (low nonce)
  958. for _, tx := range list.Forward(nonce) {
  959. hash := tx.Hash()
  960. log.Trace("Removed old pending transaction", "hash", hash)
  961. delete(pool.all, hash)
  962. pool.priced.Removed()
  963. }
  964. // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  965. drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  966. for _, tx := range drops {
  967. hash := tx.Hash()
  968. log.Trace("Removed unpayable pending transaction", "hash", hash)
  969. delete(pool.all, hash)
  970. pool.priced.Removed()
  971. pendingNofundsCounter.Inc(1)
  972. }
  973. for _, tx := range invalids {
  974. hash := tx.Hash()
  975. log.Trace("Demoting pending transaction", "hash", hash)
  976. pool.enqueueTx(hash, tx)
  977. }
  978. // If there's a gap in front, warn (should never happen) and postpone all transactions
  979. if list.Len() > 0 && list.txs.Get(nonce) == nil {
  980. for _, tx := range list.Cap(0) {
  981. hash := tx.Hash()
  982. log.Error("Demoting invalidated transaction", "hash", hash)
  983. pool.enqueueTx(hash, tx)
  984. }
  985. }
  986. // Delete the entire queue entry if it became empty.
  987. if list.Empty() {
  988. delete(pool.pending, addr)
  989. delete(pool.beats, addr)
  990. }
  991. }
  992. }
  993. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  994. type addressByHeartbeat struct {
  995. address common.Address
  996. heartbeat time.Time
  997. }
  998. type addresssByHeartbeat []addressByHeartbeat
  999. func (a addresssByHeartbeat) Len() int { return len(a) }
  1000. func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  1001. func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1002. // accountSet is simply a set of addresses to check for existence, and a signer
  1003. // capable of deriving addresses from transactions.
  1004. type accountSet struct {
  1005. accounts map[common.Address]struct{}
  1006. signer types.Signer
  1007. }
  1008. // newAccountSet creates a new address set with an associated signer for sender
  1009. // derivations.
  1010. func newAccountSet(signer types.Signer) *accountSet {
  1011. return &accountSet{
  1012. accounts: make(map[common.Address]struct{}),
  1013. signer: signer,
  1014. }
  1015. }
  1016. // contains checks if a given address is contained within the set.
  1017. func (as *accountSet) contains(addr common.Address) bool {
  1018. _, exist := as.accounts[addr]
  1019. return exist
  1020. }
  1021. // containsTx checks if the sender of a given tx is within the set. If the sender
  1022. // cannot be derived, this method returns false.
  1023. func (as *accountSet) containsTx(tx *types.Transaction) bool {
  1024. if addr, err := types.Sender(as.signer, tx); err == nil {
  1025. return as.contains(addr)
  1026. }
  1027. return false
  1028. }
  1029. // add inserts a new address into the set to track.
  1030. func (as *accountSet) add(addr common.Address) {
  1031. as.accounts[addr] = struct{}{}
  1032. }