7 "github.com/vapor/config"
9 log "github.com/sirupsen/logrus"
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"
20 maxNonce = ^uint64(0) // 2^64 - 1
26 // Miner creates blocks and searches for proof-of-work values.
30 accountManager *account.Manager
31 txPool *protocol.TxPool
35 workerWg sync.WaitGroup
36 updateNumWorkers chan struct{}
38 newBlockCh chan *bc.Hash
41 func NewMiner(c *protocol.Chain, accountManager *account.Manager, txPool *protocol.TxPool, newBlockCh chan *bc.Hash) *Miner {
44 accountManager: accountManager,
46 numWorkers: defaultNumWorkers,
47 updateNumWorkers: make(chan struct{}),
48 newBlockCh: newBlockCh,
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
58 // It must be run as a goroutine.
59 func (m *Miner) generateBlocks(quit chan struct{}) {
69 delegateInfo interface{}
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)
79 block, err := mining.NewBlockTemplate(m.chain, m.txPool, m.accountManager, m.chain.Engine, delegateInfo, blockTime)
81 log.Errorf("Mining: failed on create NewBlockTemplate: %v", err)
82 time.Sleep(1 * time.Second)
86 time.Sleep(1 * time.Second)
90 if isOrphan, err := m.chain.ProcessBlock(block); err == nil {
91 log.WithFields(log.Fields{
92 "height": block.BlockHeader.Height,
94 "tx": len(block.Transactions),
95 }).Info("Miner processed block")
97 blockHash := block.Hash()
98 m.newBlockCh <- &blockHash
100 log.WithField("height", block.BlockHeader.Height).Errorf("Miner fail on ProcessBlock, %v", err)
102 time.Sleep(time.Duration(config.CommonConfig.Consensus.Period) * time.Second)
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.
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)
123 go m.generateBlocks(quit)
127 // Launch the current number of workers by default.
128 runningWorkers = make([]chan struct{}, 0, m.numWorkers)
129 launchWorkers(m.numWorkers)
134 // Update the number of running workers.
135 case <-m.updateNumWorkers:
137 numRunning := uint64(len(runningWorkers))
138 if m.numWorkers == numRunning {
143 if m.numWorkers > numRunning {
144 launchWorkers(m.numWorkers - numRunning)
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]
156 for _, quit := range runningWorkers {
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.
170 // This function is safe for concurrent access.
171 func (m *Miner) Start() {
175 // Nothing to do if the miner is already running
180 m.quit = make(chan struct{})
181 go m.miningWorkerController()
184 log.Infof("CPU miner started")
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.
191 // This function is safe for concurrent access.
192 func (m *Miner) Stop() {
196 // Nothing to do if the miner is not currently running
203 log.Info("CPU miner stopped")
206 // IsMining returns whether or not the CPU miner has been started and is
207 // therefore currenting mining.
209 // This function is safe for concurrent access.
210 func (m *Miner) IsMining() bool {
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.
222 // This function is safe for concurrent access.
223 func (m *Miner) SetNumWorkers(numWorkers int32) {
228 // Don't lock until after the first check since Stop does its own
233 // Use default if provided value is negative.
235 m.numWorkers = defaultNumWorkers
237 m.numWorkers = uint64(numWorkers)
240 // When the miner is already running, notify the controller about the
243 m.updateNumWorkers <- struct{}{}
247 // NumWorkers returns the number of workers which are running to solve blocks.
249 // This function is safe for concurrent access.
250 func (m *Miner) NumWorkers() int32 {
254 return int32(m.numWorkers)