tx_pool.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. tp.mu.RLock()
  321. defer tp.mu.RUnlock()
  322. // check the txs first
  323. if tx, ok := tp.pending[hash]; ok {
  324. return tx
  325. }
  326. // check queue
  327. for _, txs := range tp.queue {
  328. if tx, ok := txs[hash]; ok {
  329. return tx
  330. }
  331. }
  332. return nil
  333. }
  334. // GetTransactions returns all currently processable transactions.
  335. // The returned slice may be modified by the caller.
  336. func (self *TxPool) GetTransactions() (txs types.Transactions) {
  337. self.mu.Lock()
  338. defer self.mu.Unlock()
  339. // check queue first
  340. self.checkQueue()
  341. // invalidate any txs
  342. self.validatePool()
  343. txs = make(types.Transactions, len(self.pending))
  344. i := 0
  345. for _, tx := range self.pending {
  346. txs[i] = tx
  347. i++
  348. }
  349. return txs
  350. }
  351. // GetQueuedTransactions returns all non-processable transactions.
  352. func (self *TxPool) GetQueuedTransactions() types.Transactions {
  353. self.mu.RLock()
  354. defer self.mu.RUnlock()
  355. var ret types.Transactions
  356. for _, txs := range self.queue {
  357. for _, tx := range txs {
  358. ret = append(ret, tx)
  359. }
  360. }
  361. sort.Sort(types.TxByNonce(ret))
  362. return ret
  363. }
  364. // RemoveTransactions removes all given transactions from the pool.
  365. func (self *TxPool) RemoveTransactions(txs types.Transactions) {
  366. self.mu.Lock()
  367. defer self.mu.Unlock()
  368. for _, tx := range txs {
  369. self.removeTx(tx.Hash())
  370. }
  371. }
  372. // RemoveTx removes the transaction with the given hash from the pool.
  373. func (pool *TxPool) RemoveTx(hash common.Hash) {
  374. pool.mu.Lock()
  375. defer pool.mu.Unlock()
  376. pool.removeTx(hash)
  377. }
  378. func (pool *TxPool) removeTx(hash common.Hash) {
  379. // delete from pending pool
  380. delete(pool.pending, hash)
  381. // delete from queue
  382. for address, txs := range pool.queue {
  383. if _, ok := txs[hash]; ok {
  384. if len(txs) == 1 {
  385. // if only one tx, remove entire address entry.
  386. delete(pool.queue, address)
  387. } else {
  388. delete(txs, hash)
  389. }
  390. break
  391. }
  392. }
  393. }
  394. // checkQueue moves transactions that have become processable to main pool.
  395. func (pool *TxPool) checkQueue() {
  396. // init delayed since tx pool could have been started before any state sync
  397. if pool.pendingState == nil {
  398. pool.resetState()
  399. }
  400. var promote txQueue
  401. for address, txs := range pool.queue {
  402. currentState, err := pool.currentState()
  403. if err != nil {
  404. glog.Errorf("could not get current state: %v", err)
  405. return
  406. }
  407. balance := currentState.GetBalance(address)
  408. var (
  409. guessedNonce = pool.pendingState.GetNonce(address) // nonce currently kept by the tx pool (pending state)
  410. trueNonce = currentState.GetNonce(address) // nonce known by the last state
  411. )
  412. promote = promote[:0]
  413. for hash, tx := range txs {
  414. // Drop processed or out of fund transactions
  415. if tx.Nonce() < trueNonce || balance.Cmp(tx.Cost()) < 0 {
  416. if glog.V(logger.Core) {
  417. glog.Infof("removed tx (%v) from pool queue: low tx nonce or out of funds\n", tx)
  418. }
  419. delete(txs, hash)
  420. continue
  421. }
  422. // Collect the remaining transactions for the next pass.
  423. promote = append(promote, txQueueEntry{hash, address, tx})
  424. }
  425. // Find the next consecutive nonce range starting at the current account nonce,
  426. // pushing the guessed nonce forward if we add consecutive transactions.
  427. sort.Sort(promote)
  428. for i, entry := range promote {
  429. // If we reached a gap in the nonces, enforce transaction limit and stop
  430. if entry.Nonce() > guessedNonce {
  431. if len(promote)-i > maxQueued {
  432. if glog.V(logger.Debug) {
  433. glog.Infof("Queued tx limit exceeded for %s. Tx %s removed\n", common.PP(address[:]), common.PP(entry.hash[:]))
  434. }
  435. for _, drop := range promote[i+maxQueued:] {
  436. delete(txs, drop.hash)
  437. }
  438. }
  439. break
  440. }
  441. // Otherwise promote the transaction and move the guess nonce if needed
  442. pool.addTx(entry.hash, address, entry.Transaction)
  443. delete(txs, entry.hash)
  444. if entry.Nonce() == guessedNonce {
  445. guessedNonce++
  446. }
  447. }
  448. // Delete the entire queue entry if it became empty.
  449. if len(txs) == 0 {
  450. delete(pool.queue, address)
  451. }
  452. }
  453. }
  454. // validatePool removes invalid and processed transactions from the main pool.
  455. // If a transaction is removed for being invalid (e.g. out of funds), all sub-
  456. // sequent (Still valid) transactions are moved back into the future queue. This
  457. // is important to prevent a drained account from DOSing the network with non
  458. // executable transactions.
  459. func (pool *TxPool) validatePool() {
  460. state, err := pool.currentState()
  461. if err != nil {
  462. glog.V(logger.Info).Infoln("failed to get current state: %v", err)
  463. return
  464. }
  465. balanceCache := make(map[common.Address]*big.Int)
  466. // Clean up the pending pool, accumulating invalid nonces
  467. gaps := make(map[common.Address]uint64)
  468. for hash, tx := range pool.pending {
  469. sender, _ := tx.From() // err already checked
  470. // Perform light nonce and balance validation
  471. balance := balanceCache[sender]
  472. if balance == nil {
  473. balance = state.GetBalance(sender)
  474. balanceCache[sender] = balance
  475. }
  476. if past := state.GetNonce(sender) > tx.Nonce(); past || balance.Cmp(tx.Cost()) < 0 {
  477. // Remove an already past it invalidated transaction
  478. if glog.V(logger.Core) {
  479. glog.Infof("removed tx (%v) from pool: low tx nonce or out of funds\n", tx)
  480. }
  481. delete(pool.pending, hash)
  482. // Track the smallest invalid nonce to postpone subsequent transactions
  483. if !past {
  484. if prev, ok := gaps[sender]; !ok || tx.Nonce() < prev {
  485. gaps[sender] = tx.Nonce()
  486. }
  487. }
  488. }
  489. }
  490. // Move all transactions after a gap back to the future queue
  491. if len(gaps) > 0 {
  492. for hash, tx := range pool.pending {
  493. sender, _ := tx.From()
  494. if gap, ok := gaps[sender]; ok && tx.Nonce() >= gap {
  495. if glog.V(logger.Core) {
  496. glog.Infof("postponed tx (%v) due to introduced gap\n", tx)
  497. }
  498. pool.queueTx(hash, tx)
  499. delete(pool.pending, hash)
  500. }
  501. }
  502. }
  503. }
  504. type txQueue []txQueueEntry
  505. type txQueueEntry struct {
  506. hash common.Hash
  507. addr common.Address
  508. *types.Transaction
  509. }
  510. func (q txQueue) Len() int { return len(q) }
  511. func (q txQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
  512. func (q txQueue) Less(i, j int) bool { return q[i].Nonce() < q[j].Nonce() }
  513. // txSet represents a set of transaction hashes in which entries
  514. // are automatically dropped after txSetDuration time
  515. type txSet struct {
  516. txMap map[common.Hash]struct{}
  517. txOrd map[uint64]txOrdType
  518. addPtr, delPtr uint64
  519. }
  520. const txSetDuration = time.Hour * 2
  521. // txOrdType represents an entry in the time-ordered list of transaction hashes
  522. type txOrdType struct {
  523. hash common.Hash
  524. time time.Time
  525. }
  526. // newTxSet creates a new transaction set
  527. func newTxSet() *txSet {
  528. return &txSet{
  529. txMap: make(map[common.Hash]struct{}),
  530. txOrd: make(map[uint64]txOrdType),
  531. }
  532. }
  533. // contains returns true if the set contains the given transaction hash
  534. // (not thread safe, should be called from a locked environment)
  535. func (self *txSet) contains(hash common.Hash) bool {
  536. _, ok := self.txMap[hash]
  537. return ok
  538. }
  539. // add adds a transaction hash to the set, then removes entries older than txSetDuration
  540. // (not thread safe, should be called from a locked environment)
  541. func (self *txSet) add(hash common.Hash) {
  542. self.txMap[hash] = struct{}{}
  543. now := time.Now()
  544. self.txOrd[self.addPtr] = txOrdType{hash: hash, time: now}
  545. self.addPtr++
  546. delBefore := now.Add(-txSetDuration)
  547. for self.delPtr < self.addPtr && self.txOrd[self.delPtr].time.Before(delBefore) {
  548. delete(self.txMap, self.txOrd[self.delPtr].hash)
  549. delete(self.txOrd, self.delPtr)
  550. self.delPtr++
  551. }
  552. }