transaction_pool.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package core
  2. import (
  3. "bytes"
  4. "container/list"
  5. "fmt"
  6. "math/big"
  7. "sync"
  8. "github.com/ethereum/go-ethereum/core/types"
  9. "github.com/ethereum/go-ethereum/logger"
  10. "github.com/ethereum/go-ethereum/state"
  11. "github.com/ethereum/go-ethereum/wire"
  12. )
  13. var txplogger = logger.NewLogger("TXP")
  14. const txPoolQueueSize = 50
  15. type TxPoolHook chan *types.Transaction
  16. type TxMsgTy byte
  17. const (
  18. minGasPrice = 1000000
  19. )
  20. var MinGasPrice = big.NewInt(10000000000000)
  21. type TxMsg struct {
  22. Tx *types.Transaction
  23. Type TxMsgTy
  24. }
  25. func EachTx(pool *list.List, it func(*types.Transaction, *list.Element) bool) {
  26. for e := pool.Front(); e != nil; e = e.Next() {
  27. if it(e.Value.(*types.Transaction), e) {
  28. break
  29. }
  30. }
  31. }
  32. func FindTx(pool *list.List, finder func(*types.Transaction, *list.Element) bool) *types.Transaction {
  33. for e := pool.Front(); e != nil; e = e.Next() {
  34. if tx, ok := e.Value.(*types.Transaction); ok {
  35. if finder(tx, e) {
  36. return tx
  37. }
  38. }
  39. }
  40. return nil
  41. }
  42. type TxProcessor interface {
  43. ProcessTransaction(tx *types.Transaction)
  44. }
  45. // The tx pool a thread safe transaction pool handler. In order to
  46. // guarantee a non blocking pool we use a queue channel which can be
  47. // independently read without needing access to the actual pool. If the
  48. // pool is being drained or synced for whatever reason the transactions
  49. // will simple queue up and handled when the mutex is freed.
  50. type TxPool struct {
  51. Ethereum EthManager
  52. // The mutex for accessing the Tx pool.
  53. mutex sync.Mutex
  54. // Queueing channel for reading and writing incoming
  55. // transactions to
  56. queueChan chan *types.Transaction
  57. // Quiting channel
  58. quit chan bool
  59. // The actual pool
  60. pool *list.List
  61. SecondaryProcessor TxProcessor
  62. subscribers []chan TxMsg
  63. }
  64. func NewTxPool(ethereum EthManager) *TxPool {
  65. return &TxPool{
  66. pool: list.New(),
  67. queueChan: make(chan *types.Transaction, txPoolQueueSize),
  68. quit: make(chan bool),
  69. Ethereum: ethereum,
  70. }
  71. }
  72. // Blocking function. Don't use directly. Use QueueTransaction instead
  73. func (pool *TxPool) addTransaction(tx *types.Transaction) {
  74. pool.mutex.Lock()
  75. defer pool.mutex.Unlock()
  76. pool.pool.PushBack(tx)
  77. // Broadcast the transaction to the rest of the peers
  78. pool.Ethereum.Broadcast(wire.MsgTxTy, []interface{}{tx.RlpData()})
  79. }
  80. func (pool *TxPool) ValidateTransaction(tx *types.Transaction) error {
  81. // Get the last block so we can retrieve the sender and receiver from
  82. // the merkle trie
  83. block := pool.Ethereum.ChainManager().CurrentBlock
  84. // Something has gone horribly wrong if this happens
  85. if block == nil {
  86. return fmt.Errorf("No last block on the block chain")
  87. }
  88. if len(tx.Recipient) != 0 && len(tx.Recipient) != 20 {
  89. return fmt.Errorf("Invalid recipient. len = %d", len(tx.Recipient))
  90. }
  91. v, _, _ := tx.Curve()
  92. if v > 28 || v < 27 {
  93. return fmt.Errorf("tx.v != (28 || 27)")
  94. }
  95. if tx.GasPrice.Cmp(MinGasPrice) < 0 {
  96. return fmt.Errorf("Gas price to low. Require %v > Got %v", MinGasPrice, tx.GasPrice)
  97. }
  98. // Get the sender
  99. sender := pool.Ethereum.BlockManager().CurrentState().GetAccount(tx.Sender())
  100. totAmount := new(big.Int).Set(tx.Value)
  101. // Make sure there's enough in the sender's account. Having insufficient
  102. // funds won't invalidate this transaction but simple ignores it.
  103. if sender.Balance().Cmp(totAmount) < 0 {
  104. return fmt.Errorf("Insufficient amount in sender's (%x) account", tx.Sender())
  105. }
  106. if tx.IsContract() {
  107. if tx.GasPrice.Cmp(big.NewInt(minGasPrice)) < 0 {
  108. return fmt.Errorf("Gasprice too low, %s given should be at least %d.", tx.GasPrice, minGasPrice)
  109. }
  110. }
  111. // Increment the nonce making each tx valid only once to prevent replay
  112. // attacks
  113. return nil
  114. }
  115. func (self *TxPool) Add(tx *types.Transaction) error {
  116. hash := tx.Hash()
  117. foundTx := FindTx(self.pool, func(tx *types.Transaction, e *list.Element) bool {
  118. return bytes.Compare(tx.Hash(), hash) == 0
  119. })
  120. if foundTx != nil {
  121. return fmt.Errorf("Known transaction (%x)", hash[0:4])
  122. }
  123. err := self.ValidateTransaction(tx)
  124. if err != nil {
  125. return err
  126. }
  127. self.addTransaction(tx)
  128. tmp := make([]byte, 4)
  129. copy(tmp, tx.Recipient)
  130. txplogger.Debugf("(t) %x => %x (%v) %x\n", tx.Sender()[:4], tmp, tx.Value, tx.Hash())
  131. // Notify the subscribers
  132. self.Ethereum.EventMux().Post(TxPreEvent{tx})
  133. return nil
  134. }
  135. func (pool *TxPool) CurrentTransactions() []*types.Transaction {
  136. pool.mutex.Lock()
  137. defer pool.mutex.Unlock()
  138. txList := make([]*types.Transaction, pool.pool.Len())
  139. i := 0
  140. for e := pool.pool.Front(); e != nil; e = e.Next() {
  141. tx := e.Value.(*types.Transaction)
  142. txList[i] = tx
  143. i++
  144. }
  145. return txList
  146. }
  147. func (pool *TxPool) RemoveInvalid(state *state.State) {
  148. pool.mutex.Lock()
  149. defer pool.mutex.Unlock()
  150. for e := pool.pool.Front(); e != nil; e = e.Next() {
  151. tx := e.Value.(*types.Transaction)
  152. sender := state.GetAccount(tx.Sender())
  153. err := pool.ValidateTransaction(tx)
  154. if err != nil || sender.Nonce >= tx.Nonce {
  155. pool.pool.Remove(e)
  156. }
  157. }
  158. }
  159. func (self *TxPool) RemoveSet(txs types.Transactions) {
  160. self.mutex.Lock()
  161. defer self.mutex.Unlock()
  162. for _, tx := range txs {
  163. EachTx(self.pool, func(t *types.Transaction, element *list.Element) bool {
  164. if t == tx {
  165. self.pool.Remove(element)
  166. return true // To stop the loop
  167. }
  168. return false
  169. })
  170. }
  171. }
  172. func (pool *TxPool) Flush() []*types.Transaction {
  173. txList := pool.CurrentTransactions()
  174. // Recreate a new list all together
  175. // XXX Is this the fastest way?
  176. pool.pool = list.New()
  177. return txList
  178. }
  179. func (pool *TxPool) Start() {
  180. //go pool.queueHandler()
  181. }
  182. func (pool *TxPool) Stop() {
  183. pool.Flush()
  184. txplogger.Infoln("Stopped")
  185. }