transaction_pool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/state"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/event"
  27. "github.com/ethereum/go-ethereum/logger"
  28. "github.com/ethereum/go-ethereum/logger/glog"
  29. )
  30. var (
  31. // Transaction Pool Errors
  32. ErrInvalidSender = errors.New("Invalid sender")
  33. ErrNonce = errors.New("Nonce too low")
  34. ErrCheap = errors.New("Gas price too low for acceptance")
  35. ErrBalance = errors.New("Insufficient balance")
  36. ErrNonExistentAccount = errors.New("Account does not exist or account balance too low")
  37. ErrInsufficientFunds = errors.New("Insufficient funds for gas * price + value")
  38. ErrIntrinsicGas = errors.New("Intrinsic gas too low")
  39. ErrGasLimit = errors.New("Exceeds block gas limit")
  40. ErrNegativeValue = errors.New("Negative value")
  41. )
  42. const (
  43. maxQueued = 64 // max limit of queued txs per address
  44. )
  45. type stateFn func() *state.StateDB
  46. // TxPool contains all currently known transactions. Transactions
  47. // enter the pool when they are received from the network or submitted
  48. // locally. They exit the pool when they are included in the blockchain.
  49. //
  50. // The pool separates processable transactions (which can be applied to the
  51. // current state) and future transactions. Transactions move between those
  52. // two states over time as they are received and processed.
  53. type TxPool struct {
  54. quit chan bool // Quiting channel
  55. currentState stateFn // The state function which will allow us to do some pre checkes
  56. pendingState *state.ManagedState
  57. gasLimit func() *big.Int // The current gas limit function callback
  58. minGasPrice *big.Int
  59. eventMux *event.TypeMux
  60. events event.Subscription
  61. mu sync.RWMutex
  62. pending map[common.Hash]*types.Transaction // processable transactions
  63. queue map[common.Address]map[common.Hash]*types.Transaction
  64. }
  65. func NewTxPool(eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
  66. pool := &TxPool{
  67. pending: make(map[common.Hash]*types.Transaction),
  68. queue: make(map[common.Address]map[common.Hash]*types.Transaction),
  69. quit: make(chan bool),
  70. eventMux: eventMux,
  71. currentState: currentStateFn,
  72. gasLimit: gasLimitFn,
  73. minGasPrice: new(big.Int),
  74. pendingState: state.ManageState(currentStateFn()),
  75. events: eventMux.Subscribe(ChainHeadEvent{}, GasPriceChanged{}, RemovedTransactionEvent{}),
  76. }
  77. go pool.eventLoop()
  78. return pool
  79. }
  80. func (pool *TxPool) eventLoop() {
  81. // Track chain events. When a chain events occurs (new chain canon block)
  82. // we need to know the new state. The new state will help us determine
  83. // the nonces in the managed state
  84. for ev := range pool.events.Chan() {
  85. switch ev := ev.Data.(type) {
  86. case ChainHeadEvent:
  87. pool.mu.Lock()
  88. pool.resetState()
  89. pool.mu.Unlock()
  90. case GasPriceChanged:
  91. pool.mu.Lock()
  92. pool.minGasPrice = ev.Price
  93. pool.mu.Unlock()
  94. case RemovedTransactionEvent:
  95. pool.AddTransactions(ev.Txs)
  96. }
  97. }
  98. }
  99. func (pool *TxPool) resetState() {
  100. pool.pendingState = state.ManageState(pool.currentState())
  101. // validate the pool of pending transactions, this will remove
  102. // any transactions that have been included in the block or
  103. // have been invalidated because of another transaction (e.g.
  104. // higher gas price)
  105. pool.validatePool()
  106. // Loop over the pending transactions and base the nonce of the new
  107. // pending transaction set.
  108. for _, tx := range pool.pending {
  109. if addr, err := tx.From(); err == nil {
  110. // Set the nonce. Transaction nonce can never be lower
  111. // than the state nonce; validatePool took care of that.
  112. if pool.pendingState.GetNonce(addr) <= tx.Nonce() {
  113. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  114. }
  115. }
  116. }
  117. // Check the queue and move transactions over to the pending if possible
  118. // or remove those that have become invalid
  119. pool.checkQueue()
  120. }
  121. func (pool *TxPool) Stop() {
  122. close(pool.quit)
  123. pool.events.Unsubscribe()
  124. glog.V(logger.Info).Infoln("Transaction pool stopped")
  125. }
  126. func (pool *TxPool) State() *state.ManagedState {
  127. pool.mu.RLock()
  128. defer pool.mu.RUnlock()
  129. return pool.pendingState
  130. }
  131. func (pool *TxPool) Stats() (pending int, queued int) {
  132. pool.mu.RLock()
  133. defer pool.mu.RUnlock()
  134. pending = len(pool.pending)
  135. for _, txs := range pool.queue {
  136. queued += len(txs)
  137. }
  138. return
  139. }
  140. // validateTx checks whether a transaction is valid according
  141. // to the consensus rules.
  142. func (pool *TxPool) validateTx(tx *types.Transaction) error {
  143. // Validate sender
  144. var (
  145. from common.Address
  146. err error
  147. )
  148. // Drop transactions under our own minimal accepted gas price
  149. if pool.minGasPrice.Cmp(tx.GasPrice()) > 0 {
  150. return ErrCheap
  151. }
  152. // Validate the transaction sender and it's sig. Throw
  153. // if the from fields is invalid.
  154. if from, err = tx.From(); err != nil {
  155. return ErrInvalidSender
  156. }
  157. // Make sure the account exist. Non existent accounts
  158. // haven't got funds and well therefor never pass.
  159. if !pool.currentState().HasAccount(from) {
  160. return ErrNonExistentAccount
  161. }
  162. // Last but not least check for nonce errors
  163. if pool.currentState().GetNonce(from) > tx.Nonce() {
  164. return ErrNonce
  165. }
  166. // Check the transaction doesn't exceed the current
  167. // block limit gas.
  168. if pool.gasLimit().Cmp(tx.Gas()) < 0 {
  169. return ErrGasLimit
  170. }
  171. // Transactions can't be negative. This may never happen
  172. // using RLP decoded transactions but may occur if you create
  173. // a transaction using the RPC for example.
  174. if tx.Value().Cmp(common.Big0) < 0 {
  175. return ErrNegativeValue
  176. }
  177. // Transactor should have enough funds to cover the costs
  178. // cost == V + GP * GL
  179. if pool.currentState().GetBalance(from).Cmp(tx.Cost()) < 0 {
  180. return ErrInsufficientFunds
  181. }
  182. // Should supply enough intrinsic gas
  183. if tx.Gas().Cmp(IntrinsicGas(tx.Data())) < 0 {
  184. return ErrIntrinsicGas
  185. }
  186. return nil
  187. }
  188. // validate and queue transactions.
  189. func (self *TxPool) add(tx *types.Transaction) error {
  190. hash := tx.Hash()
  191. if self.pending[hash] != nil {
  192. return fmt.Errorf("Known transaction (%x)", hash[:4])
  193. }
  194. err := self.validateTx(tx)
  195. if err != nil {
  196. return err
  197. }
  198. self.queueTx(hash, tx)
  199. if glog.V(logger.Debug) {
  200. var toname string
  201. if to := tx.To(); to != nil {
  202. toname = common.Bytes2Hex(to[:4])
  203. } else {
  204. toname = "[NEW_CONTRACT]"
  205. }
  206. // we can ignore the error here because From is
  207. // verified in ValidateTransaction.
  208. f, _ := tx.From()
  209. from := common.Bytes2Hex(f[:4])
  210. glog.Infof("(t) %x => %s (%v) %x\n", from, toname, tx.Value, hash)
  211. }
  212. return nil
  213. }
  214. // queueTx will queue an unknown transaction
  215. func (self *TxPool) queueTx(hash common.Hash, tx *types.Transaction) {
  216. from, _ := tx.From() // already validated
  217. if self.queue[from] == nil {
  218. self.queue[from] = make(map[common.Hash]*types.Transaction)
  219. }
  220. self.queue[from][hash] = tx
  221. }
  222. // addTx will add a transaction to the pending (processable queue) list of transactions
  223. func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *types.Transaction) {
  224. if _, ok := pool.pending[hash]; !ok {
  225. pool.pending[hash] = tx
  226. // Increment the nonce on the pending state. This can only happen if
  227. // the nonce is +1 to the previous one.
  228. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  229. // Notify the subscribers. This event is posted in a goroutine
  230. // because it's possible that somewhere during the post "Remove transaction"
  231. // gets called which will then wait for the global tx pool lock and deadlock.
  232. go pool.eventMux.Post(TxPreEvent{tx})
  233. }
  234. }
  235. // Add queues a single transaction in the pool if it is valid.
  236. func (self *TxPool) Add(tx *types.Transaction) (err error) {
  237. self.mu.Lock()
  238. defer self.mu.Unlock()
  239. err = self.add(tx)
  240. if err == nil {
  241. // check and validate the queueue
  242. self.checkQueue()
  243. }
  244. return
  245. }
  246. // AddTransactions attempts to queue all valid transactions in txs.
  247. func (self *TxPool) AddTransactions(txs []*types.Transaction) {
  248. self.mu.Lock()
  249. defer self.mu.Unlock()
  250. for _, tx := range txs {
  251. if err := self.add(tx); err != nil {
  252. glog.V(logger.Debug).Infoln("tx error:", err)
  253. } else {
  254. h := tx.Hash()
  255. glog.V(logger.Debug).Infof("tx %x\n", h[:4])
  256. }
  257. }
  258. // check and validate the queueue
  259. self.checkQueue()
  260. }
  261. // GetTransaction returns a transaction if it is contained in the pool
  262. // and nil otherwise.
  263. func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
  264. // check the txs first
  265. if tx, ok := tp.pending[hash]; ok {
  266. return tx
  267. }
  268. // check queue
  269. for _, txs := range tp.queue {
  270. if tx, ok := txs[hash]; ok {
  271. return tx
  272. }
  273. }
  274. return nil
  275. }
  276. // GetTransactions returns all currently processable transactions.
  277. // The returned slice may be modified by the caller.
  278. func (self *TxPool) GetTransactions() (txs types.Transactions) {
  279. self.mu.Lock()
  280. defer self.mu.Unlock()
  281. // check queue first
  282. self.checkQueue()
  283. // invalidate any txs
  284. self.validatePool()
  285. txs = make(types.Transactions, len(self.pending))
  286. i := 0
  287. for _, tx := range self.pending {
  288. txs[i] = tx
  289. i++
  290. }
  291. return txs
  292. }
  293. // GetQueuedTransactions returns all non-processable transactions.
  294. func (self *TxPool) GetQueuedTransactions() types.Transactions {
  295. self.mu.RLock()
  296. defer self.mu.RUnlock()
  297. var ret types.Transactions
  298. for _, txs := range self.queue {
  299. for _, tx := range txs {
  300. ret = append(ret, tx)
  301. }
  302. }
  303. sort.Sort(types.TxByNonce{ret})
  304. return ret
  305. }
  306. // RemoveTransactions removes all given transactions from the pool.
  307. func (self *TxPool) RemoveTransactions(txs types.Transactions) {
  308. self.mu.Lock()
  309. defer self.mu.Unlock()
  310. for _, tx := range txs {
  311. self.RemoveTx(tx.Hash())
  312. }
  313. }
  314. // RemoveTx removes the transaction with the given hash from the pool.
  315. func (pool *TxPool) RemoveTx(hash common.Hash) {
  316. // delete from pending pool
  317. delete(pool.pending, hash)
  318. // delete from queue
  319. for address, txs := range pool.queue {
  320. if _, ok := txs[hash]; ok {
  321. if len(txs) == 1 {
  322. // if only one tx, remove entire address entry.
  323. delete(pool.queue, address)
  324. } else {
  325. delete(txs, hash)
  326. }
  327. break
  328. }
  329. }
  330. }
  331. // checkQueue moves transactions that have become processable to main pool.
  332. func (pool *TxPool) checkQueue() {
  333. state := pool.pendingState
  334. var addq txQueue
  335. for address, txs := range pool.queue {
  336. // guessed nonce is the nonce currently kept by the tx pool (pending state)
  337. guessedNonce := state.GetNonce(address)
  338. // true nonce is the nonce known by the last state
  339. trueNonce := pool.currentState().GetNonce(address)
  340. addq := addq[:0]
  341. for hash, tx := range txs {
  342. if tx.Nonce() < trueNonce {
  343. // Drop queued transactions whose nonce is lower than
  344. // the account nonce because they have been processed.
  345. delete(txs, hash)
  346. } else {
  347. // Collect the remaining transactions for the next pass.
  348. addq = append(addq, txQueueEntry{hash, address, tx})
  349. }
  350. }
  351. // Find the next consecutive nonce range starting at the
  352. // current account nonce.
  353. sort.Sort(addq)
  354. for i, e := range addq {
  355. // start deleting the transactions from the queue if they exceed the limit
  356. if i > maxQueued {
  357. delete(pool.queue[address], e.hash)
  358. continue
  359. }
  360. if e.Nonce() > guessedNonce {
  361. if len(addq)-i > maxQueued {
  362. if glog.V(logger.Debug) {
  363. glog.Infof("Queued tx limit exceeded for %s. Tx %s removed\n", common.PP(address[:]), common.PP(e.hash[:]))
  364. }
  365. for j := i + maxQueued; j < len(addq); j++ {
  366. delete(txs, addq[j].hash)
  367. }
  368. }
  369. break
  370. }
  371. delete(txs, e.hash)
  372. pool.addTx(e.hash, address, e.Transaction)
  373. }
  374. // Delete the entire queue entry if it became empty.
  375. if len(txs) == 0 {
  376. delete(pool.queue, address)
  377. }
  378. }
  379. }
  380. // validatePool removes invalid and processed transactions from the main pool.
  381. func (pool *TxPool) validatePool() {
  382. state := pool.currentState()
  383. for hash, tx := range pool.pending {
  384. from, _ := tx.From() // err already checked
  385. // perform light nonce validation
  386. if state.GetNonce(from) > tx.Nonce() {
  387. if glog.V(logger.Core) {
  388. glog.Infof("removed tx (%x) from pool: low tx nonce\n", hash[:4])
  389. }
  390. delete(pool.pending, hash)
  391. }
  392. }
  393. }
  394. type txQueue []txQueueEntry
  395. type txQueueEntry struct {
  396. hash common.Hash
  397. addr common.Address
  398. *types.Transaction
  399. }
  400. func (q txQueue) Len() int { return len(q) }
  401. func (q txQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
  402. func (q txQueue) Less(i, j int) bool { return q[i].Nonce() < q[j].Nonce() }