tx_pool.go 18 KB

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