tx_pool.go 18 KB

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