transaction_pool.go 14 KB

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