miner.go 5.4 KB

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