tx_pool.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. const (
  44. maxQueued = 64 // max limit of queued txs per address
  45. )
  46. type stateFn func() (*state.StateDB, error)
  47. // TxPool contains all currently known transactions. Transactions
  48. // enter the pool when they are received from the network or submitted
  49. // locally. They exit the pool when they are included in the blockchain.
  50. //
  51. // The pool separates processable transactions (which can be applied to the
  52. // current state) and future transactions. Transactions move between those
  53. // two states over time as they are received and processed.
  54. type TxPool struct {
  55. config *ChainConfig
  56. currentState stateFn // The state function which will allow us to do some pre checks
  57. pendingState *state.ManagedState
  58. gasLimit func() *big.Int // The current gas limit function callback
  59. minGasPrice *big.Int
  60. eventMux *event.TypeMux
  61. events event.Subscription
  62. localTx *txSet
  63. mu sync.RWMutex
  64. pending map[common.Hash]*types.Transaction // processable transactions
  65. queue map[common.Address]map[common.Hash]*types.Transaction
  66. wg sync.WaitGroup // for shutdown sync
  67. homestead bool
  68. }
  69. func NewTxPool(config *ChainConfig, eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
  70. pool := &TxPool{
  71. config: config,
  72. pending: make(map[common.Hash]*types.Transaction),
  73. queue: make(map[common.Address]map[common.Hash]*types.Transaction),
  74. eventMux: eventMux,
  75. currentState: currentStateFn,
  76. gasLimit: gasLimitFn,
  77. minGasPrice: new(big.Int),
  78. pendingState: nil,
  79. localTx: newTxSet(),
  80. events: eventMux.Subscribe(ChainHeadEvent{}, GasPriceChanged{}, RemovedTransactionEvent{}),
  81. }
  82. pool.wg.Add(1)
  83. go pool.eventLoop()
  84. return pool
  85. }
  86. func (pool *TxPool) eventLoop() {
  87. defer pool.wg.Done()
  88. // Track chain events. When a chain events occurs (new chain canon block)
  89. // we need to know the new state. The new state will help us determine
  90. // the nonces in the managed state
  91. for ev := range pool.events.Chan() {
  92. switch ev := ev.Data.(type) {
  93. case ChainHeadEvent:
  94. pool.mu.Lock()
  95. if ev.Block != nil && pool.config.IsHomestead(ev.Block.Number()) {
  96. pool.homestead = true
  97. }
  98. pool.resetState()
  99. pool.mu.Unlock()
  100. case GasPriceChanged:
  101. pool.mu.Lock()
  102. pool.minGasPrice = ev.Price
  103. pool.mu.Unlock()
  104. case RemovedTransactionEvent:
  105. pool.AddTransactions(ev.Txs)
  106. }
  107. }
  108. }
  109. func (pool *TxPool) resetState() {
  110. currentState, err := pool.currentState()
  111. if err != nil {
  112. glog.V(logger.Info).Infoln("failed to get current state: %v", err)
  113. return
  114. }
  115. managedState := state.ManageState(currentState)
  116. if err != nil {
  117. glog.V(logger.Info).Infoln("failed to get managed state: %v", err)
  118. return
  119. }
  120. pool.pendingState = managedState
  121. // validate the pool of pending transactions, this will remove
  122. // any transactions that have been included in the block or
  123. // have been invalidated because of another transaction (e.g.
  124. // higher gas price)
  125. pool.validatePool()
  126. // Loop over the pending transactions and base the nonce of the new
  127. // pending transaction set.
  128. for _, tx := range pool.pending {
  129. if addr, err := tx.From(); err == nil {
  130. // Set the nonce. Transaction nonce can never be lower
  131. // than the state nonce; validatePool took care of that.
  132. if pool.pendingState.GetNonce(addr) <= tx.Nonce() {
  133. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  134. }
  135. }
  136. }
  137. // Check the queue and move transactions over to the pending if possible
  138. // or remove those that have become invalid
  139. pool.checkQueue()
  140. }
  141. func (pool *TxPool) Stop() {
  142. pool.events.Unsubscribe()
  143. pool.wg.Wait()
  144. glog.V(logger.Info).Infoln("Transaction pool stopped")
  145. }
  146. func (pool *TxPool) State() *state.ManagedState {
  147. pool.mu.RLock()
  148. defer pool.mu.RUnlock()
  149. return pool.pendingState
  150. }
  151. func (pool *TxPool) Stats() (pending int, queued int) {
  152. pool.mu.RLock()
  153. defer pool.mu.RUnlock()
  154. pending = len(pool.pending)
  155. for _, txs := range pool.queue {
  156. queued += len(txs)
  157. }
  158. return
  159. }
  160. // Content retrieves the data content of the transaction pool, returning all the
  161. // pending as well as queued transactions, grouped by account and nonce.
  162. func (pool *TxPool) Content() (map[common.Address]map[uint64][]*types.Transaction, map[common.Address]map[uint64][]*types.Transaction) {
  163. pool.mu.RLock()
  164. defer pool.mu.RUnlock()
  165. // Retrieve all the pending transactions and sort by account and by nonce
  166. pending := make(map[common.Address]map[uint64][]*types.Transaction)
  167. for _, tx := range pool.pending {
  168. account, _ := tx.From()
  169. owned, ok := pending[account]
  170. if !ok {
  171. owned = make(map[uint64][]*types.Transaction)
  172. pending[account] = owned
  173. }
  174. owned[tx.Nonce()] = append(owned[tx.Nonce()], tx)
  175. }
  176. // Retrieve all the queued transactions and sort by account and by nonce
  177. queued := make(map[common.Address]map[uint64][]*types.Transaction)
  178. for account, txs := range pool.queue {
  179. owned := make(map[uint64][]*types.Transaction)
  180. for _, tx := range txs {
  181. owned[tx.Nonce()] = append(owned[tx.Nonce()], tx)
  182. }
  183. queued[account] = owned
  184. }
  185. return pending, queued
  186. }
  187. // SetLocal marks a transaction as local, skipping gas price
  188. // check against local miner minimum in the future
  189. func (pool *TxPool) SetLocal(tx *types.Transaction) {
  190. pool.mu.Lock()
  191. defer pool.mu.Unlock()
  192. pool.localTx.add(tx.Hash())
  193. }
  194. // validateTx checks whether a transaction is valid according
  195. // to the consensus rules.
  196. func (pool *TxPool) validateTx(tx *types.Transaction) error {
  197. local := pool.localTx.contains(tx.Hash())
  198. // Drop transactions under our own minimal accepted gas price
  199. if !local && pool.minGasPrice.Cmp(tx.GasPrice()) > 0 {
  200. return ErrCheap
  201. }
  202. currentState, err := pool.currentState()
  203. if err != nil {
  204. return err
  205. }
  206. from, err := tx.From()
  207. if err != nil {
  208. return ErrInvalidSender
  209. }
  210. // Make sure the account exist. Non existent accounts
  211. // haven't got funds and well therefor never pass.
  212. if !currentState.HasAccount(from) {
  213. return ErrNonExistentAccount
  214. }
  215. // Last but not least check for nonce errors
  216. if currentState.GetNonce(from) > tx.Nonce() {
  217. return ErrNonce
  218. }
  219. // Check the transaction doesn't exceed the current
  220. // block limit gas.
  221. if pool.gasLimit().Cmp(tx.Gas()) < 0 {
  222. return ErrGasLimit
  223. }
  224. // Transactions can't be negative. This may never happen
  225. // using RLP decoded transactions but may occur if you create
  226. // a transaction using the RPC for example.
  227. if tx.Value().Cmp(common.Big0) < 0 {
  228. return ErrNegativeValue
  229. }
  230. // Transactor should have enough funds to cover the costs
  231. // cost == V + GP * GL
  232. if currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  233. return ErrInsufficientFunds
  234. }
  235. intrGas := IntrinsicGas(tx.Data(), MessageCreatesContract(tx), pool.homestead)
  236. if tx.Gas().Cmp(intrGas) < 0 {
  237. return ErrIntrinsicGas
  238. }
  239. return nil
  240. }
  241. // validate and queue transactions.
  242. func (self *TxPool) add(tx *types.Transaction) error {
  243. hash := tx.Hash()
  244. if self.pending[hash] != nil {
  245. return fmt.Errorf("Known transaction (%x)", hash[:4])
  246. }
  247. err := self.validateTx(tx)
  248. if err != nil {
  249. return err
  250. }
  251. self.queueTx(hash, tx)
  252. if glog.V(logger.Debug) {
  253. var toname string
  254. if to := tx.To(); to != nil {
  255. toname = common.Bytes2Hex(to[:4])
  256. } else {
  257. toname = "[NEW_CONTRACT]"
  258. }
  259. // we can ignore the error here because From is
  260. // verified in ValidateTransaction.
  261. f, _ := tx.From()
  262. from := common.Bytes2Hex(f[:4])
  263. glog.Infof("(t) %x => %s (%v) %x\n", from, toname, tx.Value, hash)
  264. }
  265. return nil
  266. }
  267. // queueTx will queue an unknown transaction
  268. func (self *TxPool) queueTx(hash common.Hash, tx *types.Transaction) {
  269. from, _ := tx.From() // already validated
  270. if self.queue[from] == nil {
  271. self.queue[from] = make(map[common.Hash]*types.Transaction)
  272. }
  273. self.queue[from][hash] = tx
  274. }
  275. // addTx will add a transaction to the pending (processable queue) list of transactions
  276. func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *types.Transaction) {
  277. // init delayed since tx pool could have been started before any state sync
  278. if pool.pendingState == nil {
  279. pool.resetState()
  280. }
  281. if _, ok := pool.pending[hash]; !ok {
  282. pool.pending[hash] = tx
  283. // Increment the nonce on the pending state. This can only happen if
  284. // the nonce is +1 to the previous one.
  285. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  286. // Notify the subscribers. This event is posted in a goroutine
  287. // because it's possible that somewhere during the post "Remove transaction"
  288. // gets called which will then wait for the global tx pool lock and deadlock.
  289. go pool.eventMux.Post(TxPreEvent{tx})
  290. }
  291. }
  292. // Add queues a single transaction in the pool if it is valid.
  293. func (self *TxPool) Add(tx *types.Transaction) error {
  294. self.mu.Lock()
  295. defer self.mu.Unlock()
  296. if err := self.add(tx); err != nil {
  297. return err
  298. }
  299. self.checkQueue()
  300. return nil
  301. }
  302. // AddTransactions attempts to queue all valid transactions in txs.
  303. func (self *TxPool) AddTransactions(txs []*types.Transaction) {
  304. self.mu.Lock()
  305. defer self.mu.Unlock()
  306. for _, tx := range txs {
  307. if err := self.add(tx); err != nil {
  308. glog.V(logger.Debug).Infoln("tx error:", err)
  309. } else {
  310. h := tx.Hash()
  311. glog.V(logger.Debug).Infof("tx %x\n", h[:4])
  312. }
  313. }
  314. // check and validate the queue
  315. self.checkQueue()
  316. }
  317. // GetTransaction returns a transaction if it is contained in the pool
  318. // and nil otherwise.
  319. func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
  320. // check the txs first
  321. if tx, ok := tp.pending[hash]; ok {
  322. return tx
  323. }
  324. // check queue
  325. for _, txs := range tp.queue {
  326. if tx, ok := txs[hash]; ok {
  327. return tx
  328. }
  329. }
  330. return nil
  331. }
  332. // GetTransactions returns all currently processable transactions.
  333. // The returned slice may be modified by the caller.
  334. func (self *TxPool) GetTransactions() (txs types.Transactions) {
  335. self.mu.Lock()
  336. defer self.mu.Unlock()
  337. // check queue first
  338. self.checkQueue()
  339. // invalidate any txs
  340. self.validatePool()
  341. txs = make(types.Transactions, len(self.pending))
  342. i := 0
  343. for _, tx := range self.pending {
  344. txs[i] = tx
  345. i++
  346. }
  347. return txs
  348. }
  349. // GetQueuedTransactions returns all non-processable transactions.
  350. func (self *TxPool) GetQueuedTransactions() types.Transactions {
  351. self.mu.RLock()
  352. defer self.mu.RUnlock()
  353. var ret types.Transactions
  354. for _, txs := range self.queue {
  355. for _, tx := range txs {
  356. ret = append(ret, tx)
  357. }
  358. }
  359. sort.Sort(types.TxByNonce(ret))
  360. return ret
  361. }
  362. // RemoveTransactions removes all given transactions from the pool.
  363. func (self *TxPool) RemoveTransactions(txs types.Transactions) {
  364. self.mu.Lock()
  365. defer self.mu.Unlock()
  366. for _, tx := range txs {
  367. self.RemoveTx(tx.Hash())
  368. }
  369. }
  370. // RemoveTx removes the transaction with the given hash from the pool.
  371. func (pool *TxPool) RemoveTx(hash common.Hash) {
  372. // delete from pending pool
  373. delete(pool.pending, hash)
  374. // delete from queue
  375. for address, txs := range pool.queue {
  376. if _, ok := txs[hash]; ok {
  377. if len(txs) == 1 {
  378. // if only one tx, remove entire address entry.
  379. delete(pool.queue, address)
  380. } else {
  381. delete(txs, hash)
  382. }
  383. break
  384. }
  385. }
  386. }
  387. // checkQueue moves transactions that have become processable to main pool.
  388. func (pool *TxPool) checkQueue() {
  389. // init delayed since tx pool could have been started before any state sync
  390. if pool.pendingState == nil {
  391. pool.resetState()
  392. }
  393. var promote txQueue
  394. for address, txs := range pool.queue {
  395. currentState, err := pool.currentState()
  396. if err != nil {
  397. glog.Errorf("could not get current state: %v", err)
  398. return
  399. }
  400. balance := currentState.GetBalance(address)
  401. var (
  402. guessedNonce = pool.pendingState.GetNonce(address) // nonce currently kept by the tx pool (pending state)
  403. trueNonce = currentState.GetNonce(address) // nonce known by the last state
  404. )
  405. promote = promote[:0]
  406. for hash, tx := range txs {
  407. // Drop processed or out of fund transactions
  408. if tx.Nonce() < trueNonce || balance.Cmp(tx.Cost()) < 0 {
  409. if glog.V(logger.Core) {
  410. glog.Infof("removed tx (%v) from pool queue: low tx nonce or out of funds\n", tx)
  411. }
  412. delete(txs, hash)
  413. continue
  414. }
  415. // Collect the remaining transactions for the next pass.
  416. promote = append(promote, txQueueEntry{hash, address, tx})
  417. }
  418. // Find the next consecutive nonce range starting at the current account nonce,
  419. // pushing the guessed nonce forward if we add consecutive transactions.
  420. sort.Sort(promote)
  421. for i, entry := range promote {
  422. // If we reached a gap in the nonces, enforce transaction limit and stop
  423. if entry.Nonce() > guessedNonce {
  424. if len(promote)-i > maxQueued {
  425. if glog.V(logger.Debug) {
  426. glog.Infof("Queued tx limit exceeded for %s. Tx %s removed\n", common.PP(address[:]), common.PP(entry.hash[:]))
  427. }
  428. for _, drop := range promote[i+maxQueued:] {
  429. delete(txs, drop.hash)
  430. }
  431. }
  432. break
  433. }
  434. // Otherwise promote the transaction and move the guess nonce if needed
  435. pool.addTx(entry.hash, address, entry.Transaction)
  436. delete(txs, entry.hash)
  437. if entry.Nonce() == guessedNonce {
  438. guessedNonce++
  439. }
  440. }
  441. // Delete the entire queue entry if it became empty.
  442. if len(txs) == 0 {
  443. delete(pool.queue, address)
  444. }
  445. }
  446. }
  447. // validatePool removes invalid and processed transactions from the main pool.
  448. // If a transaction is removed for being invalid (e.g. out of funds), all sub-
  449. // sequent (Still valid) transactions are moved back into the future queue. This
  450. // is important to prevent a drained account from DOSing the network with non
  451. // executable transactions.
  452. func (pool *TxPool) validatePool() {
  453. state, err := pool.currentState()
  454. if err != nil {
  455. glog.V(logger.Info).Infoln("failed to get current state: %v", err)
  456. return
  457. }
  458. balanceCache := make(map[common.Address]*big.Int)
  459. // Clean up the pending pool, accumulating invalid nonces
  460. gaps := make(map[common.Address]uint64)
  461. for hash, tx := range pool.pending {
  462. sender, _ := tx.From() // err already checked
  463. // Perform light nonce and balance validation
  464. balance := balanceCache[sender]
  465. if balance == nil {
  466. balance = state.GetBalance(sender)
  467. balanceCache[sender] = balance
  468. }
  469. if past := state.GetNonce(sender) > tx.Nonce(); past || balance.Cmp(tx.Cost()) < 0 {
  470. // Remove an already past it invalidated transaction
  471. if glog.V(logger.Core) {
  472. glog.Infof("removed tx (%v) from pool: low tx nonce or out of funds\n", tx)
  473. }
  474. delete(pool.pending, hash)
  475. // Track the smallest invalid nonce to postpone subsequent transactions
  476. if !past {
  477. if prev, ok := gaps[sender]; !ok || tx.Nonce() < prev {
  478. gaps[sender] = tx.Nonce()
  479. }
  480. }
  481. }
  482. }
  483. // Move all transactions after a gap back to the future queue
  484. if len(gaps) > 0 {
  485. for hash, tx := range pool.pending {
  486. sender, _ := tx.From()
  487. if gap, ok := gaps[sender]; ok && tx.Nonce() >= gap {
  488. if glog.V(logger.Core) {
  489. glog.Infof("postponed tx (%v) due to introduced gap\n", tx)
  490. }
  491. pool.queueTx(hash, tx)
  492. delete(pool.pending, hash)
  493. }
  494. }
  495. }
  496. }
  497. type txQueue []txQueueEntry
  498. type txQueueEntry struct {
  499. hash common.Hash
  500. addr common.Address
  501. *types.Transaction
  502. }
  503. func (q txQueue) Len() int { return len(q) }
  504. func (q txQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
  505. func (q txQueue) Less(i, j int) bool { return q[i].Nonce() < q[j].Nonce() }
  506. // txSet represents a set of transaction hashes in which entries
  507. // are automatically dropped after txSetDuration time
  508. type txSet struct {
  509. txMap map[common.Hash]struct{}
  510. txOrd map[uint64]txOrdType
  511. addPtr, delPtr uint64
  512. }
  513. const txSetDuration = time.Hour * 2
  514. // txOrdType represents an entry in the time-ordered list of transaction hashes
  515. type txOrdType struct {
  516. hash common.Hash
  517. time time.Time
  518. }
  519. // newTxSet creates a new transaction set
  520. func newTxSet() *txSet {
  521. return &txSet{
  522. txMap: make(map[common.Hash]struct{}),
  523. txOrd: make(map[uint64]txOrdType),
  524. }
  525. }
  526. // contains returns true if the set contains the given transaction hash
  527. // (not thread safe, should be called from a locked environment)
  528. func (self *txSet) contains(hash common.Hash) bool {
  529. _, ok := self.txMap[hash]
  530. return ok
  531. }
  532. // add adds a transaction hash to the set, then removes entries older than txSetDuration
  533. // (not thread safe, should be called from a locked environment)
  534. func (self *txSet) add(hash common.Hash) {
  535. self.txMap[hash] = struct{}{}
  536. now := time.Now()
  537. self.txOrd[self.addPtr] = txOrdType{hash: hash, time: now}
  538. self.addPtr++
  539. delBefore := now.Add(-txSetDuration)
  540. for self.delPtr < self.addPtr && self.txOrd[self.delPtr].time.Before(delBefore) {
  541. delete(self.txMap, self.txOrd[self.delPtr].hash)
  542. delete(self.txOrd, self.delPtr)
  543. self.delPtr++
  544. }
  545. }