github.com/daragao/go-ethereum@v1.8.14-0.20180809141559-45eaef243198/consensus/ethash/sealer.go (about)

     1  // Copyright 2017 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 ethash
    18  
    19  import (
    20  	crand "crypto/rand"
    21  	"errors"
    22  	"math"
    23  	"math/big"
    24  	"math/rand"
    25  	"runtime"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/consensus"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/log"
    33  )
    34  
    35  var (
    36  	errNoMiningWork      = errors.New("no mining work available yet")
    37  	errInvalidSealResult = errors.New("invalid or stale proof-of-work solution")
    38  )
    39  
    40  // Seal implements consensus.Engine, attempting to find a nonce that satisfies
    41  // the block's difficulty requirements.
    42  func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
    43  	// If we're running a fake PoW, simply return a 0 nonce immediately
    44  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
    45  		header := block.Header()
    46  		header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
    47  		return block.WithSeal(header), nil
    48  	}
    49  	// If we're running a shared PoW, delegate sealing to it
    50  	if ethash.shared != nil {
    51  		return ethash.shared.Seal(chain, block, stop)
    52  	}
    53  	// Create a runner and the multiple search threads it directs
    54  	abort := make(chan struct{})
    55  
    56  	ethash.lock.Lock()
    57  	threads := ethash.threads
    58  	if ethash.rand == nil {
    59  		seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    60  		if err != nil {
    61  			ethash.lock.Unlock()
    62  			return nil, err
    63  		}
    64  		ethash.rand = rand.New(rand.NewSource(seed.Int64()))
    65  	}
    66  	ethash.lock.Unlock()
    67  	if threads == 0 {
    68  		threads = runtime.NumCPU()
    69  	}
    70  	if threads < 0 {
    71  		threads = 0 // Allows disabling local mining without extra logic around local/remote
    72  	}
    73  	// Push new work to remote sealer
    74  	if ethash.workCh != nil {
    75  		ethash.workCh <- block
    76  	}
    77  	var pend sync.WaitGroup
    78  	for i := 0; i < threads; i++ {
    79  		pend.Add(1)
    80  		go func(id int, nonce uint64) {
    81  			defer pend.Done()
    82  			ethash.mine(block, id, nonce, abort, ethash.resultCh)
    83  		}(i, uint64(ethash.rand.Int63()))
    84  	}
    85  	// Wait until sealing is terminated or a nonce is found
    86  	var result *types.Block
    87  	select {
    88  	case <-stop:
    89  		// Outside abort, stop all miner threads
    90  		close(abort)
    91  	case result = <-ethash.resultCh:
    92  		// One of the threads found a block, abort all others
    93  		close(abort)
    94  	case <-ethash.update:
    95  		// Thread count was changed on user request, restart
    96  		close(abort)
    97  		pend.Wait()
    98  		return ethash.Seal(chain, block, stop)
    99  	}
   100  	// Wait for all miners to terminate and return the block
   101  	pend.Wait()
   102  	return result, nil
   103  }
   104  
   105  // mine is the actual proof-of-work miner that searches for a nonce starting from
   106  // seed that results in correct final block difficulty.
   107  func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) {
   108  	// Extract some data from the header
   109  	var (
   110  		header  = block.Header()
   111  		hash    = header.HashNoNonce().Bytes()
   112  		target  = new(big.Int).Div(maxUint256, header.Difficulty)
   113  		number  = header.Number.Uint64()
   114  		dataset = ethash.dataset(number)
   115  	)
   116  	// Start generating random nonces until we abort or find a good one
   117  	var (
   118  		attempts = int64(0)
   119  		nonce    = seed
   120  	)
   121  	logger := log.New("miner", id)
   122  	logger.Trace("Started ethash search for new nonces", "seed", seed)
   123  search:
   124  	for {
   125  		select {
   126  		case <-abort:
   127  			// Mining terminated, update stats and abort
   128  			logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
   129  			ethash.hashrate.Mark(attempts)
   130  			break search
   131  
   132  		default:
   133  			// We don't have to update hash rate on every nonce, so update after after 2^X nonces
   134  			attempts++
   135  			if (attempts % (1 << 15)) == 0 {
   136  				ethash.hashrate.Mark(attempts)
   137  				attempts = 0
   138  			}
   139  			// Compute the PoW value of this nonce
   140  			digest, result := hashimotoFull(dataset.dataset, hash, nonce)
   141  			if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
   142  				// Correct nonce found, create a new header with it
   143  				header = types.CopyHeader(header)
   144  				header.Nonce = types.EncodeNonce(nonce)
   145  				header.MixDigest = common.BytesToHash(digest)
   146  
   147  				// Seal and return a block (if still needed)
   148  				select {
   149  				case found <- block.WithSeal(header):
   150  					logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
   151  				case <-abort:
   152  					logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
   153  				}
   154  				break search
   155  			}
   156  			nonce++
   157  		}
   158  	}
   159  	// Datasets are unmapped in a finalizer. Ensure that the dataset stays live
   160  	// during sealing so it's not unmapped while being read.
   161  	runtime.KeepAlive(dataset)
   162  }
   163  
   164  // remote starts a standalone goroutine to handle remote mining related stuff.
   165  func (ethash *Ethash) remote() {
   166  	var (
   167  		works       = make(map[common.Hash]*types.Block)
   168  		rates       = make(map[common.Hash]hashrate)
   169  		currentWork *types.Block
   170  	)
   171  
   172  	// getWork returns a work package for external miner.
   173  	//
   174  	// The work package consists of 3 strings:
   175  	//   result[0], 32 bytes hex encoded current block header pow-hash
   176  	//   result[1], 32 bytes hex encoded seed hash used for DAG
   177  	//   result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
   178  	getWork := func() ([3]string, error) {
   179  		var res [3]string
   180  		if currentWork == nil {
   181  			return res, errNoMiningWork
   182  		}
   183  		res[0] = currentWork.HashNoNonce().Hex()
   184  		res[1] = common.BytesToHash(SeedHash(currentWork.NumberU64())).Hex()
   185  
   186  		// Calculate the "target" to be returned to the external sealer.
   187  		n := big.NewInt(1)
   188  		n.Lsh(n, 255)
   189  		n.Div(n, currentWork.Difficulty())
   190  		n.Lsh(n, 1)
   191  		res[2] = common.BytesToHash(n.Bytes()).Hex()
   192  
   193  		// Trace the seal work fetched by remote sealer.
   194  		works[currentWork.HashNoNonce()] = currentWork
   195  		return res, nil
   196  	}
   197  
   198  	// submitWork verifies the submitted pow solution, returning
   199  	// whether the solution was accepted or not (not can be both a bad pow as well as
   200  	// any other error, like no pending work or stale mining result).
   201  	submitWork := func(nonce types.BlockNonce, mixDigest common.Hash, hash common.Hash) bool {
   202  		// Make sure the work submitted is present
   203  		block := works[hash]
   204  		if block == nil {
   205  			log.Info("Work submitted but none pending", "hash", hash)
   206  			return false
   207  		}
   208  
   209  		// Verify the correctness of submitted result.
   210  		header := block.Header()
   211  		header.Nonce = nonce
   212  		header.MixDigest = mixDigest
   213  		if err := ethash.VerifySeal(nil, header); err != nil {
   214  			log.Warn("Invalid proof-of-work submitted", "hash", hash, "err", err)
   215  			return false
   216  		}
   217  
   218  		// Make sure the result channel is created.
   219  		if ethash.resultCh == nil {
   220  			log.Warn("Ethash result channel is empty, submitted mining result is rejected")
   221  			return false
   222  		}
   223  
   224  		// Solutions seems to be valid, return to the miner and notify acceptance.
   225  		select {
   226  		case ethash.resultCh <- block.WithSeal(header):
   227  			delete(works, hash)
   228  			return true
   229  		default:
   230  			log.Info("Work submitted is stale", "hash", hash)
   231  			return false
   232  		}
   233  	}
   234  
   235  	ticker := time.NewTicker(5 * time.Second)
   236  	defer ticker.Stop()
   237  
   238  	for {
   239  		select {
   240  		case block := <-ethash.workCh:
   241  			if currentWork != nil && block.ParentHash() != currentWork.ParentHash() {
   242  				// Start new round mining, throw out all previous work.
   243  				works = make(map[common.Hash]*types.Block)
   244  			}
   245  			// Update current work with new received block.
   246  			// Note same work can be past twice, happens when changing CPU threads.
   247  			currentWork = block
   248  
   249  		case work := <-ethash.fetchWorkCh:
   250  			// Return current mining work to remote miner.
   251  			miningWork, err := getWork()
   252  			if err != nil {
   253  				work.errc <- err
   254  			} else {
   255  				work.res <- miningWork
   256  			}
   257  
   258  		case result := <-ethash.submitWorkCh:
   259  			// Verify submitted PoW solution based on maintained mining blocks.
   260  			if submitWork(result.nonce, result.mixDigest, result.hash) {
   261  				result.errc <- nil
   262  			} else {
   263  				result.errc <- errInvalidSealResult
   264  			}
   265  
   266  		case result := <-ethash.submitRateCh:
   267  			// Trace remote sealer's hash rate by submitted value.
   268  			rates[result.id] = hashrate{rate: result.rate, ping: time.Now()}
   269  			close(result.done)
   270  
   271  		case req := <-ethash.fetchRateCh:
   272  			// Gather all hash rate submitted by remote sealer.
   273  			var total uint64
   274  			for _, rate := range rates {
   275  				// this could overflow
   276  				total += rate.rate
   277  			}
   278  			req <- total
   279  
   280  		case <-ticker.C:
   281  			// Clear stale submitted hash rate.
   282  			for id, rate := range rates {
   283  				if time.Since(rate.ping) > 10*time.Second {
   284  					delete(rates, id)
   285  				}
   286  			}
   287  
   288  		case errc := <-ethash.exitCh:
   289  			// Exit remote loop if ethash is closed and return relevant error.
   290  			errc <- nil
   291  			log.Trace("Ethash remote sealer is exiting")
   292  			return
   293  		}
   294  	}
   295  }