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