OSDN Git Service

fix bug
[bytom/vapor.git] / mining / miner / miner.go
1 package miner
2
3 import (
4         "sync"
5         "time"
6
7         "github.com/vapor/config"
8
9         log "github.com/sirupsen/logrus"
10
11         "github.com/vapor/account"
12         "github.com/vapor/common"
13         "github.com/vapor/consensus"
14         "github.com/vapor/mining"
15         "github.com/vapor/protocol"
16         "github.com/vapor/protocol/bc"
17 )
18
19 const (
20         maxNonce          = ^uint64(0) // 2^64 - 1
21         defaultNumWorkers = 1
22         hashUpdateSecs    = 1
23         module            = "miner"
24 )
25
26 // Miner creates blocks and searches for proof-of-work values.
27 type Miner struct {
28         sync.Mutex
29         chain            *protocol.Chain
30         accountManager   *account.Manager
31         txPool           *protocol.TxPool
32         numWorkers       uint64
33         started          bool
34         discreteMining   bool
35         workerWg         sync.WaitGroup
36         updateNumWorkers chan struct{}
37         quit             chan struct{}
38         newBlockCh       chan *bc.Hash
39 }
40
41 func NewMiner(c *protocol.Chain, accountManager *account.Manager, txPool *protocol.TxPool, newBlockCh chan *bc.Hash) *Miner {
42         return &Miner{
43                 chain:            c,
44                 accountManager:   accountManager,
45                 txPool:           txPool,
46                 numWorkers:       defaultNumWorkers,
47                 updateNumWorkers: make(chan struct{}),
48                 newBlockCh:       newBlockCh,
49         }
50 }
51
52 // generateBlocks is a worker that is controlled by the miningWorkerController.
53 // It is self contained in that it creates block templates and attempts to solve
54 // them while detecting when it is performing stale work and reacting
55 // accordingly by generating a new block template.  When a block is solved, it
56 // is submitted.
57 //
58 // It must be run as a goroutine.
59 func (m *Miner) generateBlocks(quit chan struct{}) {
60
61 out:
62         for {
63                 select {
64                 case <-quit:
65                         break out
66                 default:
67                 }
68                 var (
69                         delegateInfo interface{}
70                         err          error
71                 )
72                 address, _ := common.DecodeAddress(config.CommonConfig.Consensus.Coinbase, &consensus.ActiveNetParams)
73                 blockTime := uint64(time.Now().Unix())
74                 if delegateInfo, err = m.chain.Engine.IsMining(address, blockTime); err != nil {
75                         time.Sleep(1 * time.Second)
76                         continue
77                 }
78
79                 block, err := mining.NewBlockTemplate(m.chain, m.txPool, m.accountManager, m.chain.Engine, delegateInfo, blockTime)
80                 if err != nil {
81                         log.Errorf("Mining: failed on create NewBlockTemplate: %v", err)
82                         time.Sleep(1 * time.Second)
83                         continue
84                 }
85                 if block == nil {
86                         time.Sleep(1 * time.Second)
87                         continue
88                 }
89
90                 if isOrphan, err := m.chain.ProcessBlock(block); err == nil {
91                         log.WithFields(log.Fields{
92                                 "height":   block.BlockHeader.Height,
93                                 "isOrphan": isOrphan,
94                                 "tx":       len(block.Transactions),
95                         }).Info("Miner processed block")
96
97                         blockHash := block.Hash()
98                         m.newBlockCh <- &blockHash
99                 } else {
100                         log.WithField("height", block.BlockHeader.Height).Errorf("Miner fail on ProcessBlock, %v", err)
101                 }
102                 time.Sleep(time.Duration(config.CommonConfig.Consensus.Period) * time.Second)
103         }
104
105         m.workerWg.Done()
106 }
107
108 // miningWorkerController launches the worker goroutines that are used to
109 // generate block templates and solve them.  It also provides the ability to
110 // dynamically adjust the number of running worker goroutines.
111 //
112 // It must be run as a goroutine.
113 func (m *Miner) miningWorkerController() {
114         // launchWorkers groups common code to launch a specified number of
115         // workers for generating blocks.
116         var runningWorkers []chan struct{}
117         launchWorkers := func(numWorkers uint64) {
118                 for i := uint64(0); i < numWorkers; i++ {
119                         quit := make(chan struct{})
120                         runningWorkers = append(runningWorkers, quit)
121
122                         m.workerWg.Add(1)
123                         go m.generateBlocks(quit)
124                 }
125         }
126
127         // Launch the current number of workers by default.
128         runningWorkers = make([]chan struct{}, 0, m.numWorkers)
129         launchWorkers(m.numWorkers)
130
131 out:
132         for {
133                 select {
134                 // Update the number of running workers.
135                 case <-m.updateNumWorkers:
136                         // No change.
137                         numRunning := uint64(len(runningWorkers))
138                         if m.numWorkers == numRunning {
139                                 continue
140                         }
141
142                         // Add new workers.
143                         if m.numWorkers > numRunning {
144                                 launchWorkers(m.numWorkers - numRunning)
145                                 continue
146                         }
147
148                         // Signal the most recently created goroutines to exit.
149                         for i := numRunning - 1; i >= m.numWorkers; i-- {
150                                 close(runningWorkers[i])
151                                 runningWorkers[i] = nil
152                                 runningWorkers = runningWorkers[:i]
153                         }
154
155                 case <-m.quit:
156                         for _, quit := range runningWorkers {
157                                 close(quit)
158                         }
159                         break out
160                 }
161         }
162
163         m.workerWg.Wait()
164 }
165
166 // Start begins the CPU mining process as well as the speed monitor used to
167 // track hashing metrics.  Calling this function when the CPU miner has
168 // already been started will have no effect.
169 //
170 // This function is safe for concurrent access.
171 func (m *Miner) Start() {
172         m.Lock()
173         defer m.Unlock()
174
175         // Nothing to do if the miner is already running
176         if m.started {
177                 return
178         }
179
180         m.quit = make(chan struct{})
181         go m.miningWorkerController()
182
183         m.started = true
184         log.Infof("CPU miner started")
185 }
186
187 // Stop gracefully stops the mining process by signalling all workers, and the
188 // speed monitor to quit.  Calling this function when the CPU miner has not
189 // already been started will have no effect.
190 //
191 // This function is safe for concurrent access.
192 func (m *Miner) Stop() {
193         m.Lock()
194         defer m.Unlock()
195
196         // Nothing to do if the miner is not currently running
197         if !m.started {
198                 return
199         }
200
201         close(m.quit)
202         m.started = false
203         log.Info("CPU miner stopped")
204 }
205
206 // IsMining returns whether or not the CPU miner has been started and is
207 // therefore currenting mining.
208 //
209 // This function is safe for concurrent access.
210 func (m *Miner) IsMining() bool {
211         m.Lock()
212         defer m.Unlock()
213
214         return m.started
215 }
216
217 // SetNumWorkers sets the number of workers to create which solve blocks.  Any
218 // negative values will cause a default number of workers to be used which is
219 // based on the number of processor cores in the system.  A value of 0 will
220 // cause all CPU mining to be stopped.
221 //
222 // This function is safe for concurrent access.
223 func (m *Miner) SetNumWorkers(numWorkers int32) {
224         if numWorkers == 0 {
225                 m.Stop()
226         }
227
228         // Don't lock until after the first check since Stop does its own
229         // locking.
230         m.Lock()
231         defer m.Unlock()
232
233         // Use default if provided value is negative.
234         if numWorkers < 0 {
235                 m.numWorkers = defaultNumWorkers
236         } else {
237                 m.numWorkers = uint64(numWorkers)
238         }
239
240         // When the miner is already running, notify the controller about the
241         // the change.
242         if m.started {
243                 m.updateNumWorkers <- struct{}{}
244         }
245 }
246
247 // NumWorkers returns the number of workers which are running to solve blocks.
248 //
249 // This function is safe for concurrent access.
250 func (m *Miner) NumWorkers() int32 {
251         m.Lock()
252         defer m.Unlock()
253
254         return int32(m.numWorkers)
255 }