github.com/luckypickle/go-ethereum-vet@v1.14.2/miner/miner.go (about)

     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  
    17  // Package miner implements Ethereum block creation and mining.
    18  package miner
    19  
    20  import (
    21  	"fmt"
    22  	"sync/atomic"
    23  	"time"
    24  
    25  	"github.com/luckypickle/go-ethereum-vet/common"
    26  	"github.com/luckypickle/go-ethereum-vet/consensus"
    27  	"github.com/luckypickle/go-ethereum-vet/core"
    28  	"github.com/luckypickle/go-ethereum-vet/core/state"
    29  	"github.com/luckypickle/go-ethereum-vet/core/types"
    30  	"github.com/luckypickle/go-ethereum-vet/eth/downloader"
    31  	"github.com/luckypickle/go-ethereum-vet/event"
    32  	"github.com/luckypickle/go-ethereum-vet/log"
    33  	"github.com/luckypickle/go-ethereum-vet/params"
    34  )
    35  
    36  // Backend wraps all methods required for mining.
    37  type Backend interface {
    38  	BlockChain() *core.BlockChain
    39  	TxPool() *core.TxPool
    40  }
    41  
    42  // Miner creates blocks and searches for proof-of-work values.
    43  type Miner struct {
    44  	mux      *event.TypeMux
    45  	worker   *worker
    46  	coinbase common.Address
    47  	eth      Backend
    48  	engine   consensus.Engine
    49  	exitCh   chan struct{}
    50  
    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  
    55  func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, recommit time.Duration) *Miner {
    56  	miner := &Miner{
    57  		eth:      eth,
    58  		mux:      mux,
    59  		engine:   engine,
    60  		exitCh:   make(chan struct{}),
    61  		worker:   newWorker(config, engine, eth, mux, recommit),
    62  		canStart: 1,
    63  	}
    64  	go miner.update()
    65  
    66  	return miner
    67  }
    68  
    69  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    70  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    71  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    72  // and halt your mining operation for as long as the DOS continues.
    73  func (self *Miner) update() {
    74  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    75  	defer events.Unsubscribe()
    76  
    77  	for {
    78  		select {
    79  		case ev := <-events.Chan():
    80  			if ev == nil {
    81  				return
    82  			}
    83  			switch ev.Data.(type) {
    84  			case downloader.StartEvent:
    85  				atomic.StoreInt32(&self.canStart, 0)
    86  				if self.Mining() {
    87  					self.Stop()
    88  					atomic.StoreInt32(&self.shouldStart, 1)
    89  					log.Info("Mining aborted due to sync")
    90  				}
    91  			case downloader.DoneEvent, downloader.FailedEvent:
    92  				shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    93  
    94  				atomic.StoreInt32(&self.canStart, 1)
    95  				atomic.StoreInt32(&self.shouldStart, 0)
    96  				if shouldStart {
    97  					self.Start(self.coinbase)
    98  				}
    99  				// stop immediately and ignore all further pending events
   100  				return
   101  			}
   102  		case <-self.exitCh:
   103  			return
   104  		}
   105  	}
   106  }
   107  
   108  func (self *Miner) Start(coinbase common.Address) {
   109  	atomic.StoreInt32(&self.shouldStart, 1)
   110  	self.SetEtherbase(coinbase)
   111  
   112  	if atomic.LoadInt32(&self.canStart) == 0 {
   113  		log.Info("Network syncing, will start miner afterwards")
   114  		return
   115  	}
   116  	self.worker.start()
   117  }
   118  
   119  func (self *Miner) Stop() {
   120  	self.worker.stop()
   121  	atomic.StoreInt32(&self.shouldStart, 0)
   122  }
   123  
   124  func (self *Miner) Close() {
   125  	self.worker.close()
   126  	close(self.exitCh)
   127  }
   128  
   129  func (self *Miner) Mining() bool {
   130  	return self.worker.isRunning()
   131  }
   132  
   133  func (self *Miner) HashRate() uint64 {
   134  	if pow, ok := self.engine.(consensus.PoW); ok {
   135  		return uint64(pow.Hashrate())
   136  	}
   137  	return 0
   138  }
   139  
   140  func (self *Miner) SetExtra(extra []byte) error {
   141  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   142  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   143  	}
   144  	self.worker.setExtra(extra)
   145  	return nil
   146  }
   147  
   148  // SetRecommitInterval sets the interval for sealing work resubmitting.
   149  func (self *Miner) SetRecommitInterval(interval time.Duration) {
   150  	self.worker.setRecommitInterval(interval)
   151  }
   152  
   153  // Pending returns the currently pending block and associated state.
   154  func (self *Miner) Pending() (*types.Block, *state.StateDB) {
   155  	return self.worker.pending()
   156  }
   157  
   158  // PendingBlock returns the currently pending block.
   159  //
   160  // Note, to access both the pending block and the pending state
   161  // simultaneously, please use Pending(), as the pending state can
   162  // change between multiple method calls
   163  func (self *Miner) PendingBlock() *types.Block {
   164  	return self.worker.pendingBlock()
   165  }
   166  
   167  func (self *Miner) SetEtherbase(addr common.Address) {
   168  	self.coinbase = addr
   169  	self.worker.setEtherbase(addr)
   170  }