transaction_pool.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package core
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "github.com/ethereum/go-ethereum/common"
  8. "github.com/ethereum/go-ethereum/core/state"
  9. "github.com/ethereum/go-ethereum/core/types"
  10. "github.com/ethereum/go-ethereum/event"
  11. "github.com/ethereum/go-ethereum/logger"
  12. "github.com/ethereum/go-ethereum/logger/glog"
  13. "gopkg.in/fatih/set.v0"
  14. )
  15. var (
  16. ErrInvalidSender = errors.New("Invalid sender")
  17. ErrImpossibleNonce = errors.New("Impossible nonce")
  18. ErrNonExistentAccount = errors.New("Account does not exist")
  19. ErrInsufficientFunds = errors.New("Insufficient funds")
  20. ErrIntrinsicGas = errors.New("Intrinsic gas too low")
  21. )
  22. const txPoolQueueSize = 50
  23. type TxPoolHook chan *types.Transaction
  24. type TxMsg struct{ Tx *types.Transaction }
  25. type stateFn func() *state.StateDB
  26. const (
  27. minGasPrice = 1000000
  28. )
  29. type TxProcessor interface {
  30. ProcessTransaction(tx *types.Transaction)
  31. }
  32. // The tx pool a thread safe transaction pool handler. In order to
  33. // guarantee a non blocking pool we use a queue channel which can be
  34. // independently read without needing access to the actual pool.
  35. type TxPool struct {
  36. mu sync.RWMutex
  37. // Queueing channel for reading and writing incoming
  38. // transactions to
  39. queueChan chan *types.Transaction
  40. // Quiting channel
  41. quit chan bool
  42. // The state function which will allow us to do some pre checkes
  43. currentState stateFn
  44. // The actual pool
  45. txs map[common.Hash]*types.Transaction
  46. invalidHashes *set.Set
  47. subscribers []chan TxMsg
  48. eventMux *event.TypeMux
  49. }
  50. func NewTxPool(eventMux *event.TypeMux, currentStateFn stateFn) *TxPool {
  51. return &TxPool{
  52. txs: make(map[common.Hash]*types.Transaction),
  53. queueChan: make(chan *types.Transaction, txPoolQueueSize),
  54. quit: make(chan bool),
  55. eventMux: eventMux,
  56. invalidHashes: set.New(),
  57. currentState: currentStateFn,
  58. }
  59. }
  60. func (pool *TxPool) ValidateTransaction(tx *types.Transaction) error {
  61. // Validate sender
  62. var (
  63. from common.Address
  64. err error
  65. )
  66. if from, err = tx.From(); err != nil {
  67. return ErrInvalidSender
  68. }
  69. // Validate curve param
  70. v, _, _ := tx.Curve()
  71. if v > 28 || v < 27 {
  72. return fmt.Errorf("tx.v != (28 || 27) => %v", v)
  73. }
  74. if !pool.currentState().HasAccount(from) {
  75. return ErrNonExistentAccount
  76. }
  77. if pool.currentState().GetBalance(from).Cmp(new(big.Int).Mul(tx.Price, tx.GasLimit)) < 0 {
  78. return ErrInsufficientFunds
  79. }
  80. if tx.GasLimit.Cmp(IntrinsicGas(tx)) < 0 {
  81. return ErrIntrinsicGas
  82. }
  83. if pool.currentState().GetNonce(from) > tx.Nonce() {
  84. return ErrImpossibleNonce
  85. }
  86. return nil
  87. }
  88. func (self *TxPool) addTx(tx *types.Transaction) {
  89. self.txs[tx.Hash()] = tx
  90. }
  91. func (self *TxPool) add(tx *types.Transaction) error {
  92. hash := tx.Hash()
  93. /* XXX I'm unsure about this. This is extremely dangerous and may result
  94. in total black listing of certain transactions
  95. if self.invalidHashes.Has(hash) {
  96. return fmt.Errorf("Invalid transaction (%x)", hash[:4])
  97. }
  98. */
  99. if self.txs[hash] != nil {
  100. return fmt.Errorf("Known transaction (%x)", hash[:4])
  101. }
  102. err := self.ValidateTransaction(tx)
  103. if err != nil {
  104. return err
  105. }
  106. self.addTx(tx)
  107. var toname string
  108. if to := tx.To(); to != nil {
  109. toname = common.Bytes2Hex(to[:4])
  110. } else {
  111. toname = "[NEW_CONTRACT]"
  112. }
  113. // we can ignore the error here because From is
  114. // verified in ValidateTransaction.
  115. f, _ := tx.From()
  116. from := common.Bytes2Hex(f[:4])
  117. if glog.V(logger.Debug) {
  118. glog.Infof("(t) %x => %s (%v) %x\n", from, toname, tx.Value, tx.Hash())
  119. }
  120. // Notify the subscribers
  121. go self.eventMux.Post(TxPreEvent{tx})
  122. return nil
  123. }
  124. func (self *TxPool) Size() int {
  125. return len(self.txs)
  126. }
  127. func (self *TxPool) Add(tx *types.Transaction) error {
  128. self.mu.Lock()
  129. defer self.mu.Unlock()
  130. return self.add(tx)
  131. }
  132. func (self *TxPool) AddTransactions(txs []*types.Transaction) {
  133. self.mu.Lock()
  134. defer self.mu.Unlock()
  135. for _, tx := range txs {
  136. if err := self.add(tx); err != nil {
  137. glog.V(logger.Debug).Infoln(err)
  138. } else {
  139. h := tx.Hash()
  140. glog.V(logger.Debug).Infof("tx %x\n", h[:4])
  141. }
  142. }
  143. }
  144. func (self *TxPool) GetTransactions() (txs types.Transactions) {
  145. self.mu.RLock()
  146. defer self.mu.RUnlock()
  147. txs = make(types.Transactions, self.Size())
  148. i := 0
  149. for _, tx := range self.txs {
  150. txs[i] = tx
  151. i++
  152. }
  153. return
  154. }
  155. func (self *TxPool) RemoveSet(txs types.Transactions) {
  156. self.mu.Lock()
  157. defer self.mu.Unlock()
  158. for _, tx := range txs {
  159. delete(self.txs, tx.Hash())
  160. }
  161. }
  162. func (self *TxPool) InvalidateSet(hashes *set.Set) {
  163. self.mu.Lock()
  164. defer self.mu.Unlock()
  165. hashes.Each(func(v interface{}) bool {
  166. delete(self.txs, v.(common.Hash))
  167. return true
  168. })
  169. self.invalidHashes.Merge(hashes)
  170. }
  171. func (pool *TxPool) Flush() {
  172. pool.txs = make(map[common.Hash]*types.Transaction)
  173. }
  174. func (pool *TxPool) Start() {
  175. }
  176. func (pool *TxPool) Stop() {
  177. pool.Flush()
  178. glog.V(logger.Info).Infoln("TX Pool stopped")
  179. }