tx_pool.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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/big"
  21. "sort"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/event"
  28. "github.com/ethereum/go-ethereum/logger"
  29. "github.com/ethereum/go-ethereum/logger/glog"
  30. )
  31. var (
  32. // Transaction Pool Errors
  33. ErrInvalidSender = errors.New("Invalid sender")
  34. ErrNonce = errors.New("Nonce too low")
  35. ErrCheap = errors.New("Gas price too low for acceptance")
  36. ErrBalance = errors.New("Insufficient balance")
  37. ErrNonExistentAccount = errors.New("Account does not exist or account balance too low")
  38. ErrInsufficientFunds = errors.New("Insufficient funds for gas * price + value")
  39. ErrIntrinsicGas = errors.New("Intrinsic gas too low")
  40. ErrGasLimit = errors.New("Exceeds block gas limit")
  41. ErrNegativeValue = errors.New("Negative value")
  42. )
  43. var (
  44. maxQueuedPerAccount = uint64(64) // Max limit of queued transactions per address
  45. maxQueuedInTotal = uint64(65536) // Max limit of queued transactions from all accounts
  46. maxQueuedLifetime = 3 * time.Hour // Max amount of time transactions from idle accounts are queued
  47. evictionInterval = time.Minute // Time interval to check for evictable transactions
  48. )
  49. type stateFn func() (*state.StateDB, error)
  50. // TxPool contains all currently known transactions. Transactions
  51. // enter the pool when they are received from the network or submitted
  52. // locally. They exit the pool when they are included in the blockchain.
  53. //
  54. // The pool separates processable transactions (which can be applied to the
  55. // current state) and future transactions. Transactions move between those
  56. // two states over time as they are received and processed.
  57. type TxPool struct {
  58. config *ChainConfig
  59. currentState stateFn // The state function which will allow us to do some pre checks
  60. pendingState *state.ManagedState
  61. gasLimit func() *big.Int // The current gas limit function callback
  62. minGasPrice *big.Int
  63. eventMux *event.TypeMux
  64. events event.Subscription
  65. localTx *txSet
  66. mu sync.RWMutex
  67. pending map[common.Address]*txList // All currently processable transactions
  68. queue map[common.Address]*txList // Queued but non-processable transactions
  69. all map[common.Hash]*types.Transaction // All transactions to allow lookups
  70. beats map[common.Address]time.Time // Last heartbeat from each known account
  71. wg sync.WaitGroup // for shutdown sync
  72. quit chan struct{}
  73. homestead bool
  74. }
  75. func NewTxPool(config *ChainConfig, eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
  76. pool := &TxPool{
  77. config: config,
  78. pending: make(map[common.Address]*txList),
  79. queue: make(map[common.Address]*txList),
  80. all: make(map[common.Hash]*types.Transaction),
  81. beats: make(map[common.Address]time.Time),
  82. eventMux: eventMux,
  83. currentState: currentStateFn,
  84. gasLimit: gasLimitFn,
  85. minGasPrice: new(big.Int),
  86. pendingState: nil,
  87. localTx: newTxSet(),
  88. events: eventMux.Subscribe(ChainHeadEvent{}, GasPriceChanged{}, RemovedTransactionEvent{}),
  89. quit: make(chan struct{}),
  90. }
  91. pool.wg.Add(2)
  92. go pool.eventLoop()
  93. go pool.expirationLoop()
  94. return pool
  95. }
  96. func (pool *TxPool) eventLoop() {
  97. defer pool.wg.Done()
  98. // Track chain events. When a chain events occurs (new chain canon block)
  99. // we need to know the new state. The new state will help us determine
  100. // the nonces in the managed state
  101. for ev := range pool.events.Chan() {
  102. switch ev := ev.Data.(type) {
  103. case ChainHeadEvent:
  104. pool.mu.Lock()
  105. if ev.Block != nil && pool.config.IsHomestead(ev.Block.Number()) {
  106. pool.homestead = true
  107. }
  108. pool.resetState()
  109. pool.mu.Unlock()
  110. case GasPriceChanged:
  111. pool.mu.Lock()
  112. pool.minGasPrice = ev.Price
  113. pool.mu.Unlock()
  114. case RemovedTransactionEvent:
  115. pool.AddBatch(ev.Txs)
  116. }
  117. }
  118. }
  119. func (pool *TxPool) resetState() {
  120. currentState, err := pool.currentState()
  121. if err != nil {
  122. glog.V(logger.Error).Infof("Failed to get current state: %v", err)
  123. return
  124. }
  125. managedState := state.ManageState(currentState)
  126. if err != nil {
  127. glog.V(logger.Error).Infof("Failed to get managed state: %v", err)
  128. return
  129. }
  130. pool.pendingState = managedState
  131. // validate the pool of pending transactions, this will remove
  132. // any transactions that have been included in the block or
  133. // have been invalidated because of another transaction (e.g.
  134. // higher gas price)
  135. pool.demoteUnexecutables()
  136. // Update all accounts to the latest known pending nonce
  137. for addr, list := range pool.pending {
  138. txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway
  139. pool.pendingState.SetNonce(addr, txs[len(txs)-1].Nonce()+1)
  140. }
  141. // Check the queue and move transactions over to the pending if possible
  142. // or remove those that have become invalid
  143. pool.promoteExecutables()
  144. }
  145. func (pool *TxPool) Stop() {
  146. pool.events.Unsubscribe()
  147. close(pool.quit)
  148. pool.wg.Wait()
  149. glog.V(logger.Info).Infoln("Transaction pool stopped")
  150. }
  151. func (pool *TxPool) State() *state.ManagedState {
  152. pool.mu.RLock()
  153. defer pool.mu.RUnlock()
  154. return pool.pendingState
  155. }
  156. // Stats retrieves the current pool stats, namely the number of pending and the
  157. // number of queued (non-executable) transactions.
  158. func (pool *TxPool) Stats() (pending int, queued int) {
  159. pool.mu.RLock()
  160. defer pool.mu.RUnlock()
  161. for _, list := range pool.pending {
  162. pending += list.Len()
  163. }
  164. for _, list := range pool.queue {
  165. queued += list.Len()
  166. }
  167. return
  168. }
  169. // Content retrieves the data content of the transaction pool, returning all the
  170. // pending as well as queued transactions, grouped by account and sorted by nonce.
  171. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  172. pool.mu.RLock()
  173. defer pool.mu.RUnlock()
  174. pending := make(map[common.Address]types.Transactions)
  175. for addr, list := range pool.pending {
  176. pending[addr] = list.Flatten()
  177. }
  178. queued := make(map[common.Address]types.Transactions)
  179. for addr, list := range pool.queue {
  180. queued[addr] = list.Flatten()
  181. }
  182. return pending, queued
  183. }
  184. // Pending retrieves all currently processable transactions, groupped by origin
  185. // account and sorted by nonce. The returned transaction set is a copy and can be
  186. // freely modified by calling code.
  187. func (pool *TxPool) Pending() map[common.Address]types.Transactions {
  188. pool.mu.Lock()
  189. defer pool.mu.Unlock()
  190. // check queue first
  191. pool.promoteExecutables()
  192. // invalidate any txs
  193. pool.demoteUnexecutables()
  194. pending := make(map[common.Address]types.Transactions)
  195. for addr, list := range pool.pending {
  196. pending[addr] = list.Flatten()
  197. }
  198. return pending
  199. }
  200. // SetLocal marks a transaction as local, skipping gas price
  201. // check against local miner minimum in the future
  202. func (pool *TxPool) SetLocal(tx *types.Transaction) {
  203. pool.mu.Lock()
  204. defer pool.mu.Unlock()
  205. pool.localTx.add(tx.Hash())
  206. }
  207. // validateTx checks whether a transaction is valid according
  208. // to the consensus rules.
  209. func (pool *TxPool) validateTx(tx *types.Transaction) error {
  210. local := pool.localTx.contains(tx.Hash())
  211. // Drop transactions under our own minimal accepted gas price
  212. if !local && pool.minGasPrice.Cmp(tx.GasPrice()) > 0 {
  213. return ErrCheap
  214. }
  215. currentState, err := pool.currentState()
  216. if err != nil {
  217. return err
  218. }
  219. from, err := tx.From()
  220. if err != nil {
  221. return ErrInvalidSender
  222. }
  223. // Make sure the account exist. Non existent accounts
  224. // haven't got funds and well therefor never pass.
  225. if !currentState.Exist(from) {
  226. return ErrNonExistentAccount
  227. }
  228. // Last but not least check for nonce errors
  229. if currentState.GetNonce(from) > tx.Nonce() {
  230. return ErrNonce
  231. }
  232. // Check the transaction doesn't exceed the current
  233. // block limit gas.
  234. if pool.gasLimit().Cmp(tx.Gas()) < 0 {
  235. return ErrGasLimit
  236. }
  237. // Transactions can't be negative. This may never happen
  238. // using RLP decoded transactions but may occur if you create
  239. // a transaction using the RPC for example.
  240. if tx.Value().Cmp(common.Big0) < 0 {
  241. return ErrNegativeValue
  242. }
  243. // Transactor should have enough funds to cover the costs
  244. // cost == V + GP * GL
  245. if currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  246. return ErrInsufficientFunds
  247. }
  248. intrGas := IntrinsicGas(tx.Data(), MessageCreatesContract(tx), pool.homestead)
  249. if tx.Gas().Cmp(intrGas) < 0 {
  250. return ErrIntrinsicGas
  251. }
  252. return nil
  253. }
  254. // add validates a transaction and inserts it into the non-executable queue for
  255. // later pending promotion and execution.
  256. func (pool *TxPool) add(tx *types.Transaction) error {
  257. // If the transaction is alreayd known, discard it
  258. hash := tx.Hash()
  259. if pool.all[hash] != nil {
  260. return fmt.Errorf("Known transaction: %x", hash[:4])
  261. }
  262. // Otherwise ensure basic validation passes and queue it up
  263. if err := pool.validateTx(tx); err != nil {
  264. return err
  265. }
  266. pool.enqueueTx(hash, tx)
  267. // Print a log message if low enough level is set
  268. if glog.V(logger.Debug) {
  269. rcpt := "[NEW_CONTRACT]"
  270. if to := tx.To(); to != nil {
  271. rcpt = common.Bytes2Hex(to[:4])
  272. }
  273. from, _ := tx.From() // from already verified during tx validation
  274. glog.Infof("(t) 0x%x => %s (%v) %x\n", from[:4], rcpt, tx.Value, hash)
  275. }
  276. return nil
  277. }
  278. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  279. //
  280. // Note, this method assumes the pool lock is held!
  281. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) {
  282. // Try to insert the transaction into the future queue
  283. from, _ := tx.From() // already validated
  284. if pool.queue[from] == nil {
  285. pool.queue[from] = newTxList(false)
  286. }
  287. inserted, old := pool.queue[from].Add(tx)
  288. if !inserted {
  289. return // An older transaction was better, discard this
  290. }
  291. // Discard any previous transaction and mark this
  292. if old != nil {
  293. delete(pool.all, old.Hash())
  294. }
  295. pool.all[hash] = tx
  296. }
  297. // promoteTx adds a transaction to the pending (processable) list of transactions.
  298. //
  299. // Note, this method assumes the pool lock is held!
  300. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) {
  301. // Init delayed since tx pool could have been started before any state sync
  302. if pool.pendingState == nil {
  303. pool.resetState()
  304. }
  305. // Try to insert the transaction into the pending queue
  306. if pool.pending[addr] == nil {
  307. pool.pending[addr] = newTxList(true)
  308. }
  309. list := pool.pending[addr]
  310. inserted, old := list.Add(tx)
  311. if !inserted {
  312. // An older transaction was better, discard this
  313. delete(pool.all, hash)
  314. return
  315. }
  316. // Otherwise discard any previous transaction and mark this
  317. if old != nil {
  318. delete(pool.all, old.Hash())
  319. }
  320. pool.all[hash] = tx // Failsafe to work around direct pending inserts (tests)
  321. // Set the potentially new pending nonce and notify any subsystems of the new tx
  322. pool.beats[addr] = time.Now()
  323. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  324. go pool.eventMux.Post(TxPreEvent{tx})
  325. }
  326. // Add queues a single transaction in the pool if it is valid.
  327. func (pool *TxPool) Add(tx *types.Transaction) error {
  328. pool.mu.Lock()
  329. defer pool.mu.Unlock()
  330. if err := pool.add(tx); err != nil {
  331. return err
  332. }
  333. pool.promoteExecutables()
  334. return nil
  335. }
  336. // AddBatch attempts to queue a batch of transactions.
  337. func (pool *TxPool) AddBatch(txs []*types.Transaction) {
  338. pool.mu.Lock()
  339. defer pool.mu.Unlock()
  340. for _, tx := range txs {
  341. if err := pool.add(tx); err != nil {
  342. glog.V(logger.Debug).Infoln("tx error:", err)
  343. }
  344. }
  345. pool.promoteExecutables()
  346. }
  347. // Get returns a transaction if it is contained in the pool
  348. // and nil otherwise.
  349. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  350. pool.mu.RLock()
  351. defer pool.mu.RUnlock()
  352. return pool.all[hash]
  353. }
  354. // Remove removes the transaction with the given hash from the pool.
  355. func (pool *TxPool) Remove(hash common.Hash) {
  356. pool.mu.Lock()
  357. defer pool.mu.Unlock()
  358. pool.removeTx(hash)
  359. }
  360. // RemoveBatch removes all given transactions from the pool.
  361. func (pool *TxPool) RemoveBatch(txs types.Transactions) {
  362. pool.mu.Lock()
  363. defer pool.mu.Unlock()
  364. for _, tx := range txs {
  365. pool.removeTx(tx.Hash())
  366. }
  367. }
  368. // removeTx removes a single transaction from the queue, moving all subsequent
  369. // transactions back to the future queue.
  370. func (pool *TxPool) removeTx(hash common.Hash) {
  371. // Fetch the transaction we wish to delete
  372. tx, ok := pool.all[hash]
  373. if !ok {
  374. return
  375. }
  376. addr, _ := tx.From() // already validated during insertion
  377. // Remove it from the list of known transactions
  378. delete(pool.all, hash)
  379. // Remove the transaction from the pending lists and reset the account nonce
  380. if pending := pool.pending[addr]; pending != nil {
  381. if removed, invalids := pending.Remove(tx); removed {
  382. // If no more transactions are left, remove the list
  383. if pending.Empty() {
  384. delete(pool.pending, addr)
  385. delete(pool.beats, addr)
  386. } else {
  387. // Otherwise postpone any invalidated transactions
  388. for _, tx := range invalids {
  389. pool.enqueueTx(tx.Hash(), tx)
  390. }
  391. }
  392. // Update the account nonce if needed
  393. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  394. pool.pendingState.SetNonce(addr, tx.Nonce())
  395. }
  396. }
  397. }
  398. // Transaction is in the future queue
  399. if future := pool.queue[addr]; future != nil {
  400. future.Remove(tx)
  401. if future.Empty() {
  402. delete(pool.queue, addr)
  403. }
  404. }
  405. }
  406. // promoteExecutables moves transactions that have become processable from the
  407. // future queue to the set of pending transactions. During this process, all
  408. // invalidated transactions (low nonce, low balance) are deleted.
  409. func (pool *TxPool) promoteExecutables() {
  410. // Init delayed since tx pool could have been started before any state sync
  411. if pool.pendingState == nil {
  412. pool.resetState()
  413. }
  414. // Retrieve the current state to allow nonce and balance checking
  415. state, err := pool.currentState()
  416. if err != nil {
  417. glog.Errorf("Could not get current state: %v", err)
  418. return
  419. }
  420. // Iterate over all accounts and promote any executable transactions
  421. queued := uint64(0)
  422. for addr, list := range pool.queue {
  423. // Drop all transactions that are deemed too old (low nonce)
  424. for _, tx := range list.Forward(state.GetNonce(addr)) {
  425. if glog.V(logger.Core) {
  426. glog.Infof("Removed old queued transaction: %v", tx)
  427. }
  428. delete(pool.all, tx.Hash())
  429. }
  430. // Drop all transactions that are too costly (low balance)
  431. drops, _ := list.Filter(state.GetBalance(addr))
  432. for _, tx := range drops {
  433. if glog.V(logger.Core) {
  434. glog.Infof("Removed unpayable queued transaction: %v", tx)
  435. }
  436. delete(pool.all, tx.Hash())
  437. }
  438. // Gather all executable transactions and promote them
  439. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  440. if glog.V(logger.Core) {
  441. glog.Infof("Promoting queued transaction: %v", tx)
  442. }
  443. pool.promoteTx(addr, tx.Hash(), tx)
  444. }
  445. // Drop all transactions over the allowed limit
  446. for _, tx := range list.Cap(int(maxQueuedPerAccount)) {
  447. if glog.V(logger.Core) {
  448. glog.Infof("Removed cap-exceeding queued transaction: %v", tx)
  449. }
  450. delete(pool.all, tx.Hash())
  451. }
  452. queued += uint64(list.Len())
  453. // Delete the entire queue entry if it became empty.
  454. if list.Empty() {
  455. delete(pool.queue, addr)
  456. }
  457. }
  458. // If we've queued more transactions than the hard limit, drop oldest ones
  459. if queued > maxQueuedInTotal {
  460. // Sort all accounts with queued transactions by heartbeat
  461. addresses := make(addresssByHeartbeat, 0, len(pool.queue))
  462. for addr, _ := range pool.queue {
  463. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  464. }
  465. sort.Sort(addresses)
  466. // Drop transactions until the total is below the limit
  467. for drop := queued - maxQueuedInTotal; drop > 0; {
  468. addr := addresses[len(addresses)-1]
  469. list := pool.queue[addr.address]
  470. addresses = addresses[:len(addresses)-1]
  471. // Drop all transactions if they are less than the overflow
  472. if size := uint64(list.Len()); size <= drop {
  473. for _, tx := range list.Flatten() {
  474. pool.removeTx(tx.Hash())
  475. }
  476. drop -= size
  477. continue
  478. }
  479. // Otherwise drop only last few transactions
  480. txs := list.Flatten()
  481. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  482. pool.removeTx(txs[i].Hash())
  483. drop--
  484. }
  485. }
  486. }
  487. }
  488. // demoteUnexecutables removes invalid and processed transactions from the pools
  489. // executable/pending queue and any subsequent transactions that become unexecutable
  490. // are moved back into the future queue.
  491. func (pool *TxPool) demoteUnexecutables() {
  492. // Retrieve the current state to allow nonce and balance checking
  493. state, err := pool.currentState()
  494. if err != nil {
  495. glog.V(logger.Info).Infoln("failed to get current state: %v", err)
  496. return
  497. }
  498. // Iterate over all accounts and demote any non-executable transactions
  499. for addr, list := range pool.pending {
  500. nonce := state.GetNonce(addr)
  501. // Drop all transactions that are deemed too old (low nonce)
  502. for _, tx := range list.Forward(nonce) {
  503. if glog.V(logger.Core) {
  504. glog.Infof("Removed old pending transaction: %v", tx)
  505. }
  506. delete(pool.all, tx.Hash())
  507. }
  508. // Drop all transactions that are too costly (low balance), and queue any invalids back for later
  509. drops, invalids := list.Filter(state.GetBalance(addr))
  510. for _, tx := range drops {
  511. if glog.V(logger.Core) {
  512. glog.Infof("Removed unpayable pending transaction: %v", tx)
  513. }
  514. delete(pool.all, tx.Hash())
  515. }
  516. for _, tx := range invalids {
  517. if glog.V(logger.Core) {
  518. glog.Infof("Demoting pending transaction: %v", tx)
  519. }
  520. pool.enqueueTx(tx.Hash(), tx)
  521. }
  522. // Delete the entire queue entry if it became empty.
  523. if list.Empty() {
  524. delete(pool.pending, addr)
  525. delete(pool.beats, addr)
  526. }
  527. }
  528. }
  529. // expirationLoop is a loop that periodically iterates over all accounts with
  530. // queued transactions and drop all that have been inactive for a prolonged amount
  531. // of time.
  532. func (pool *TxPool) expirationLoop() {
  533. defer pool.wg.Done()
  534. evict := time.NewTicker(evictionInterval)
  535. defer evict.Stop()
  536. for {
  537. select {
  538. case <-evict.C:
  539. pool.mu.Lock()
  540. for addr := range pool.queue {
  541. if time.Since(pool.beats[addr]) > maxQueuedLifetime {
  542. for _, tx := range pool.queue[addr].Flatten() {
  543. pool.removeTx(tx.Hash())
  544. }
  545. }
  546. }
  547. pool.mu.Unlock()
  548. case <-pool.quit:
  549. return
  550. }
  551. }
  552. }
  553. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  554. type addressByHeartbeat struct {
  555. address common.Address
  556. heartbeat time.Time
  557. }
  558. type addresssByHeartbeat []addressByHeartbeat
  559. func (a addresssByHeartbeat) Len() int { return len(a) }
  560. func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  561. func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  562. // txSet represents a set of transaction hashes in which entries
  563. // are automatically dropped after txSetDuration time
  564. type txSet struct {
  565. txMap map[common.Hash]struct{}
  566. txOrd map[uint64]txOrdType
  567. addPtr, delPtr uint64
  568. }
  569. const txSetDuration = time.Hour * 2
  570. // txOrdType represents an entry in the time-ordered list of transaction hashes
  571. type txOrdType struct {
  572. hash common.Hash
  573. time time.Time
  574. }
  575. // newTxSet creates a new transaction set
  576. func newTxSet() *txSet {
  577. return &txSet{
  578. txMap: make(map[common.Hash]struct{}),
  579. txOrd: make(map[uint64]txOrdType),
  580. }
  581. }
  582. // contains returns true if the set contains the given transaction hash
  583. // (not thread safe, should be called from a locked environment)
  584. func (self *txSet) contains(hash common.Hash) bool {
  585. _, ok := self.txMap[hash]
  586. return ok
  587. }
  588. // add adds a transaction hash to the set, then removes entries older than txSetDuration
  589. // (not thread safe, should be called from a locked environment)
  590. func (self *txSet) add(hash common.Hash) {
  591. self.txMap[hash] = struct{}{}
  592. now := time.Now()
  593. self.txOrd[self.addPtr] = txOrdType{hash: hash, time: now}
  594. self.addPtr++
  595. delBefore := now.Add(-txSetDuration)
  596. for self.delPtr < self.addPtr && self.txOrd[self.delPtr].time.Before(delBefore) {
  597. delete(self.txMap, self.txOrd[self.delPtr].hash)
  598. delete(self.txOrd, self.delPtr)
  599. self.delPtr++
  600. }
  601. }