transaction_pool.go 13 KB

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