github.com/m3shine/gochain@v2.2.26+incompatible/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  	"context"
    22  	"fmt"
    23  	"sync/atomic"
    24  	"time"
    25  
    26  	"go.opencensus.io/trace"
    27  
    28  	"github.com/gochain-io/gochain/common"
    29  	"github.com/gochain-io/gochain/consensus"
    30  	"github.com/gochain-io/gochain/core"
    31  	"github.com/gochain-io/gochain/core/state"
    32  	"github.com/gochain-io/gochain/core/types"
    33  	"github.com/gochain-io/gochain/eth/downloader"
    34  	"github.com/gochain-io/gochain/event"
    35  	"github.com/gochain-io/gochain/log"
    36  	"github.com/gochain-io/gochain/params"
    37  )
    38  
    39  // Backend wraps all methods required for mining.
    40  type Backend interface {
    41  	BlockChain() *core.BlockChain
    42  	TxPool() *core.TxPool
    43  }
    44  
    45  // Miner creates blocks and searches for proof-of-work values.
    46  type Miner struct {
    47  	mux      *event.TypeMux
    48  	worker   *worker
    49  	coinbase common.Address
    50  	eth      Backend
    51  	engine   consensus.Engine
    52  	exitCh   chan struct{}
    53  
    54  	canStart    int32 // can start indicates whether we can start the mining operation
    55  	shouldStart int32 // should start indicates whether we should start after sync
    56  }
    57  
    58  func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, recommit time.Duration, gasFloor, gasCeil uint64, isLocalBlock func(block *types.Block) bool) *Miner {
    59  	miner := &Miner{
    60  		eth:      eth,
    61  		mux:      mux,
    62  		engine:   engine,
    63  		exitCh:   make(chan struct{}),
    64  		worker:   newWorker(config, engine, eth, mux, recommit, gasFloor, gasCeil, isLocalBlock),
    65  		canStart: 1,
    66  	}
    67  	go miner.update()
    68  
    69  	return miner
    70  }
    71  
    72  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    73  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    74  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    75  // and halt your mining operation for as long as the DOS continues.
    76  func (self *Miner) update() {
    77  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    78  	defer events.Unsubscribe()
    79  
    80  	for {
    81  		select {
    82  		case ev := <-events.Chan():
    83  			if ev == nil {
    84  				return
    85  			}
    86  			switch ev.Data.(type) {
    87  			case downloader.StartEvent:
    88  				atomic.StoreInt32(&self.canStart, 0)
    89  				if self.Mining() {
    90  					self.Stop()
    91  					atomic.StoreInt32(&self.shouldStart, 1)
    92  					log.Info("Mining aborted due to sync")
    93  				}
    94  			case downloader.DoneEvent, downloader.FailedEvent:
    95  				shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    96  
    97  				atomic.StoreInt32(&self.canStart, 1)
    98  				atomic.StoreInt32(&self.shouldStart, 0)
    99  				if shouldStart {
   100  					self.Start(self.coinbase)
   101  				}
   102  				// stop immediately and ignore all further pending events
   103  				return
   104  			}
   105  		case <-self.exitCh:
   106  			return
   107  		}
   108  	}
   109  }
   110  
   111  func (self *Miner) Start(coinbase common.Address) {
   112  	atomic.StoreInt32(&self.shouldStart, 1)
   113  	self.SetEtherbase(coinbase)
   114  
   115  	if atomic.LoadInt32(&self.canStart) == 0 {
   116  		log.Info("Network syncing, will start miner afterwards")
   117  		return
   118  	}
   119  	self.worker.start()
   120  }
   121  
   122  func (self *Miner) Stop() {
   123  	self.worker.stop()
   124  	atomic.StoreInt32(&self.shouldStart, 0)
   125  }
   126  
   127  func (self *Miner) Close() {
   128  	self.worker.close()
   129  	close(self.exitCh)
   130  }
   131  
   132  func (self *Miner) Mining() bool {
   133  	return self.worker.isRunning()
   134  }
   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  
   144  // SetRecommitInterval sets the interval for sealing work resubmitting.
   145  func (self *Miner) SetRecommitInterval(interval time.Duration) {
   146  	self.worker.setRecommitInterval(interval)
   147  }
   148  
   149  // Pending returns the currently pending block and associated state.
   150  func (self *Miner) Pending(ctx context.Context) (*types.Block, *state.StateDB) {
   151  	ctx, span := trace.StartSpan(ctx, "Miner.Pending")
   152  	defer span.End()
   153  	return self.worker.pending(ctx)
   154  }
   155  
   156  // PendingBlock returns the currently pending block.
   157  //
   158  // Note, to access both the pending block and the pending state
   159  // simultaneously, please use Pending(), as the pending state can
   160  // change between multiple method calls
   161  func (self *Miner) PendingBlock(ctx context.Context) *types.Block {
   162  	ctx, span := trace.StartSpan(ctx, "Miner.PendingBlock")
   163  	defer span.End()
   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  }