miner.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 miner implements Ethereum block creation and mining.
  17. package miner
  18. import (
  19. "fmt"
  20. "math/big"
  21. "sync/atomic"
  22. "github.com/ethereum/go-ethereum/accounts"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/eth/downloader"
  28. "github.com/ethereum/go-ethereum/ethdb"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/logger"
  31. "github.com/ethereum/go-ethereum/logger/glog"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/pow"
  34. )
  35. // Backend wraps all methods required for mining.
  36. type Backend interface {
  37. AccountManager() *accounts.Manager
  38. BlockChain() *core.BlockChain
  39. TxPool() *core.TxPool
  40. ChainDb() ethdb.Database
  41. }
  42. // Miner creates blocks and searches for proof-of-work values.
  43. type Miner struct {
  44. mux *event.TypeMux
  45. worker *worker
  46. threads int
  47. coinbase common.Address
  48. mining int32
  49. eth Backend
  50. pow pow.PoW
  51. canStart int32 // can start indicates whether we can start the mining operation
  52. shouldStart int32 // should start indicates whether we should start after sync
  53. }
  54. func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner {
  55. miner := &Miner{
  56. eth: eth,
  57. mux: mux,
  58. pow: pow,
  59. worker: newWorker(config, common.Address{}, eth, mux),
  60. canStart: 1,
  61. }
  62. go miner.update()
  63. return miner
  64. }
  65. // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
  66. // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
  67. // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
  68. // and halt your mining operation for as long as the DOS continues.
  69. func (self *Miner) update() {
  70. events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
  71. out:
  72. for ev := range events.Chan() {
  73. switch ev.Data.(type) {
  74. case downloader.StartEvent:
  75. atomic.StoreInt32(&self.canStart, 0)
  76. if self.Mining() {
  77. self.Stop()
  78. atomic.StoreInt32(&self.shouldStart, 1)
  79. glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation")
  80. }
  81. case downloader.DoneEvent, downloader.FailedEvent:
  82. shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
  83. atomic.StoreInt32(&self.canStart, 1)
  84. atomic.StoreInt32(&self.shouldStart, 0)
  85. if shouldStart {
  86. self.Start(self.coinbase, self.threads)
  87. }
  88. // unsubscribe. we're only interested in this event once
  89. events.Unsubscribe()
  90. // stop immediately and ignore all further pending events
  91. break out
  92. }
  93. }
  94. }
  95. func (m *Miner) GasPrice() *big.Int {
  96. return new(big.Int).Set(m.worker.gasPrice)
  97. }
  98. func (m *Miner) SetGasPrice(price *big.Int) {
  99. // FIXME block tests set a nil gas price. Quick dirty fix
  100. if price == nil {
  101. return
  102. }
  103. m.worker.setGasPrice(price)
  104. }
  105. func (self *Miner) Start(coinbase common.Address, threads int) {
  106. atomic.StoreInt32(&self.shouldStart, 1)
  107. self.worker.setEtherbase(coinbase)
  108. self.coinbase = coinbase
  109. self.threads = threads
  110. if atomic.LoadInt32(&self.canStart) == 0 {
  111. glog.V(logger.Info).Infoln("Can not start mining operation due to network sync (starts when finished)")
  112. return
  113. }
  114. atomic.StoreInt32(&self.mining, 1)
  115. for i := 0; i < threads; i++ {
  116. self.worker.register(NewCpuAgent(i, self.pow))
  117. }
  118. glog.V(logger.Info).Infof("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents))
  119. self.worker.start()
  120. self.worker.commitNewWork()
  121. }
  122. func (self *Miner) Stop() {
  123. self.worker.stop()
  124. atomic.StoreInt32(&self.mining, 0)
  125. atomic.StoreInt32(&self.shouldStart, 0)
  126. }
  127. func (self *Miner) Register(agent Agent) {
  128. if self.Mining() {
  129. agent.Start()
  130. }
  131. self.worker.register(agent)
  132. }
  133. func (self *Miner) Unregister(agent Agent) {
  134. self.worker.unregister(agent)
  135. }
  136. func (self *Miner) Mining() bool {
  137. return atomic.LoadInt32(&self.mining) > 0
  138. }
  139. func (self *Miner) HashRate() (tot int64) {
  140. tot += self.pow.GetHashrate()
  141. // do we care this might race? is it worth we're rewriting some
  142. // aspects of the worker/locking up agents so we can get an accurate
  143. // hashrate?
  144. for agent := range self.worker.agents {
  145. tot += agent.GetHashRate()
  146. }
  147. return
  148. }
  149. func (self *Miner) SetExtra(extra []byte) error {
  150. if uint64(len(extra)) > params.MaximumExtraDataSize {
  151. return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
  152. }
  153. self.worker.setExtra(extra)
  154. return nil
  155. }
  156. // Pending returns the currently pending block and associated state.
  157. func (self *Miner) Pending() (*types.Block, *state.StateDB) {
  158. return self.worker.pending()
  159. }
  160. // PendingBlock returns the currently pending block.
  161. //
  162. // Note, to access both the pending block and the pending state
  163. // simultaneously, please use Pending(), as the pending state can
  164. // change between multiple method calls
  165. func (self *Miner) PendingBlock() *types.Block {
  166. return self.worker.pendingBlock()
  167. }
  168. func (self *Miner) SetEtherbase(addr common.Address) {
  169. self.coinbase = addr
  170. self.worker.setEtherbase(addr)
  171. }