github.com/marconiprotocol/go-methereum-lite@v0.0.0-20190918214227-3cd8b06fcf99/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  	"bytes"
    21  	crand "crypto/rand"
    22  	"encoding/json"
    23  	"errors"
    24  	"math"
    25  	"math/big"
    26  	"math/rand"
    27  	"net/http"
    28  	"runtime"
    29  	"sync"
    30  	"time"
    31  
    32  	"github.com/MarconiProtocol/go-methereum-lite/common"
    33  	"github.com/MarconiProtocol/go-methereum-lite/common/hexutil"
    34  	"github.com/MarconiProtocol/go-methereum-lite/consensus"
    35  	"github.com/MarconiProtocol/go-methereum-lite/core/types"
    36  	"github.com/MarconiProtocol/go-methereum-lite/log"
    37  	"github.com/MarconiProtocol/marconi-cryptonight"
    38  )
    39  
    40  const (
    41  	// staleThreshold is the maximum depth of the acceptable stale but valid ethash solution.
    42  	staleThreshold = 7
    43  )
    44  
    45  var (
    46  	errNoMiningWork      = errors.New("no mining work available yet")
    47  	errInvalidSealResult = errors.New("invalid or stale proof-of-work solution")
    48  )
    49  
    50  // Seal implements consensus.Engine, attempting to find a nonce that satisfies
    51  // the block's difficulty requirements.
    52  func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
    53  	// If we're running a fake PoW, simply return a 0 nonce immediately
    54  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
    55  		header := block.Header()
    56  		header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
    57  		select {
    58  		case results <- block.WithSeal(header):
    59  		default:
    60  			log.Warn("Sealing result is not read by miner", "mode", "fake", "sealhash", ethash.SealHash(block.Header()))
    61  		}
    62  		return nil
    63  	}
    64  	// If we're running a shared PoW, delegate sealing to it
    65  	if ethash.shared != nil {
    66  		return ethash.shared.Seal(chain, block, results, stop)
    67  	}
    68  	// Create a runner and the multiple search threads it directs
    69  	abort := make(chan struct{})
    70  
    71  	ethash.lock.Lock()
    72  	threads := ethash.threads
    73  	if ethash.rand == nil {
    74  		seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    75  		if err != nil {
    76  			ethash.lock.Unlock()
    77  			return err
    78  		}
    79  		ethash.rand = rand.New(rand.NewSource(seed.Int64()))
    80  	}
    81  	ethash.lock.Unlock()
    82  	if threads == 0 {
    83  		threads = runtime.NumCPU()
    84  	}
    85  	if threads < 0 {
    86  		threads = 0 // Allows disabling local mining without extra logic around local/remote
    87  	}
    88  	// Push new work to remote sealer
    89  	if ethash.workCh != nil {
    90  		ethash.workCh <- &sealTask{block: block, results: results}
    91  	}
    92  	var (
    93  		pend   sync.WaitGroup
    94  		locals = make(chan *types.Block)
    95  	)
    96  	for i := 0; i < threads; i++ {
    97  		pend.Add(1)
    98  		go func(id int, nonce uint64) {
    99  			defer pend.Done()
   100  			ethash.mine(block, id, nonce, ethash.config.PowMode, abort, locals)
   101  		}(i, uint64(ethash.rand.Int63()))
   102  	}
   103  	// Wait until sealing is terminated or a nonce is found
   104  	go func() {
   105  		var result *types.Block
   106  		select {
   107  		case <-stop:
   108  			// Outside abort, stop all miner threads
   109  			close(abort)
   110  		case result = <-locals:
   111  			// One of the threads found a block, abort all others
   112  			select {
   113  			case results <- result:
   114  			default:
   115  				log.Warn("Sealing result is not read by miner", "mode", "local", "sealhash", ethash.SealHash(block.Header()))
   116  			}
   117  			close(abort)
   118  		case <-ethash.update:
   119  			// Thread count was changed on user request, restart
   120  			close(abort)
   121  			if err := ethash.Seal(chain, block, results, stop); err != nil {
   122  				log.Error("Failed to restart sealing after update", "err", err)
   123  			}
   124  		}
   125  		// Wait for all miners to terminate and return the block
   126  		pend.Wait()
   127  	}()
   128  	return nil
   129  }
   130  
   131  // mine is the actual proof-of-work miner that searches for a nonce starting from
   132  // seed that results in correct final block difficulty.
   133  func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, pow_mode Mode, abort chan struct{}, found chan *types.Block) {
   134  	// Extract some data from the header
   135  	var (
   136  		header  = block.Header()
   137  		hash    = ethash.SealHash(header).Bytes()
   138  		target  = new(big.Int).Div(two256, header.Difficulty)
   139  		number  = header.Number.Uint64()
   140  		dataset *dataset = nil
   141  	)
   142  	if pow_mode != ModeQuickTest && pow_mode != ModeCryptonight {
   143  		dataset = ethash.dataset(number, false)
   144  	}
   145  	// Start generating random nonces until we abort or find a good one
   146  	var (
   147  		attempts = int64(0)
   148  		nonce    = seed
   149  	)
   150  	logger := log.New("miner", id)
   151  	logger.Trace("Started ethash search for new nonces", "seed", seed)
   152  search:
   153  	for {
   154  		select {
   155  		case <-abort:
   156  			// Mining terminated, update stats and abort
   157  			logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
   158  			ethash.hashrate.Mark(attempts)
   159  			break search
   160  
   161  		default:
   162  			// We don't have to update hash rate on every nonce, so update after after 2^X nonces
   163  			attempts++
   164  			if (attempts % (1 << 15)) == 0 {
   165  				ethash.hashrate.Mark(attempts)
   166  				attempts = 0
   167  			}
   168  			// Compute the PoW value of this nonce
   169  			var digest []byte
   170  			var result []byte
   171  			if pow_mode == ModeQuickTest {
   172  				digest, result = quickHash(hash, nonce)
   173  			} else if pow_mode == ModeCryptonight {
   174  				digest, result = cryptonight.HashVariant4ForEthereumHeader(hash, nonce, number)
   175  			} else {
   176  				digest, result = hashimotoFull(dataset.dataset, hash, nonce)
   177  			}
   178  			if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
   179  				// Correct nonce found, create a new header with it
   180  				header = types.CopyHeader(header)
   181  				header.Nonce = types.EncodeNonce(nonce)
   182  				header.MixDigest = common.BytesToHash(digest)
   183  
   184  				// Seal and return a block (if still needed)
   185  				select {
   186  				case found <- block.WithSeal(header):
   187  					logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
   188  				case <-abort:
   189  					logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
   190  				}
   191  				break search
   192  			}
   193  			nonce++
   194  		}
   195  	}
   196  	// Datasets are unmapped in a finalizer. Ensure that the dataset stays live
   197  	// during sealing so it's not unmapped while being read.
   198  	if pow_mode != ModeQuickTest && pow_mode != ModeCryptonight {
   199  		runtime.KeepAlive(dataset)
   200  	}
   201  }
   202  
   203  // remote is a standalone goroutine to handle remote mining related stuff.
   204  func (ethash *Ethash) remote(notify []string, noverify bool) {
   205  	var (
   206  		works = make(map[common.Hash]*types.Block)
   207  		rates = make(map[common.Hash]hashrate)
   208  
   209  		results      chan<- *types.Block
   210  		currentBlock *types.Block
   211  		// this is the work to be sent miner, based on geth's extraData
   212  		currentWork  [4]string
   213  
   214  		notifyTransport = &http.Transport{}
   215  		notifyClient    = &http.Client{
   216  			Transport: notifyTransport,
   217  			Timeout:   time.Second,
   218  		}
   219  		notifyReqs = make([]*http.Request, len(notify))
   220  	)
   221  	// notifyWork notifies all the specified mining endpoints of the availability of
   222  	// new work to be processed.
   223  	notifyWork := func() {
   224  		work := currentWork
   225  		blob, _ := json.Marshal(work)
   226  
   227  		for i, url := range notify {
   228  			// Terminate any previously pending request and create the new work
   229  			if notifyReqs[i] != nil {
   230  				notifyTransport.CancelRequest(notifyReqs[i])
   231  			}
   232  			notifyReqs[i], _ = http.NewRequest("POST", url, bytes.NewReader(blob))
   233  			notifyReqs[i].Header.Set("Content-Type", "application/json")
   234  
   235  			// Push the new work concurrently to all the remote nodes
   236  			go func(req *http.Request, url string) {
   237  				res, err := notifyClient.Do(req)
   238  				if err != nil {
   239  					log.Warn("Failed to notify remote miner", "err", err)
   240  				} else {
   241  					log.Trace("Notified remote miner", "miner", url, "hash", log.Lazy{Fn: func() common.Hash { return common.HexToHash(work[0]) }}, "target", work[2])
   242  					res.Body.Close()
   243  				}
   244  			}(notifyReqs[i], url)
   245  		}
   246  	}
   247  	// makeWork creates a work package for external miner.
   248  	//
   249  	// The work package consists of 3 strings:
   250  	//   result[0], 32 bytes hex encoded current block header pow-hash
   251  	//   result[1], 32 bytes hex encoded seed hash used for DAG
   252  	//   result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
   253  	//   result[3], hex encoded block number
   254  	makeWork := func(block *types.Block) {
   255  		hash := ethash.SealHash(block.Header())
   256  
   257  		currentWork[0] = hash.Hex()
   258  		currentWork[1] = common.BytesToHash(SeedHash(block.NumberU64())).Hex()
   259  		currentWork[2] = common.BytesToHash(new(big.Int).Div(two256, block.Difficulty()).Bytes()).Hex()
   260  		currentWork[3] = hexutil.EncodeBig(block.Number())
   261  
   262  		// Trace the seal work fetched by remote sealer.
   263  		currentBlock = block
   264  		works[hash] = block
   265  	}
   266  	// submitWork verifies the submitted pow solution, returning
   267  	// whether the solution was accepted or not (not can be both a bad pow as well as
   268  	// any other error, like no pending work or stale mining result).
   269  	submitWork := func(nonce types.BlockNonce, mixDigest common.Hash, sealhash common.Hash) bool {
   270  		if currentBlock == nil {
   271  			log.Error("Pending work without block", "sealhash", sealhash)
   272  			return false
   273  		}
   274  		// Make sure the work submitted is present
   275  		block := works[sealhash]
   276  		if block == nil {
   277  			log.Warn("Work submitted but none pending", "sealhash", sealhash, "curnumber", currentBlock.NumberU64())
   278  			return false
   279  		}
   280  		// Verify the correctness of submitted result.
   281  		header := block.Header()
   282  		header.Nonce = nonce
   283  		header.MixDigest = mixDigest
   284  
   285  		start := time.Now()
   286  		if !noverify {
   287  			if err := ethash.verifySeal(nil, header, true); err != nil {
   288  				log.Warn("Invalid proof-of-work submitted", "sealhash", sealhash, "elapsed", time.Since(start), "err", err)
   289  				return false
   290  			}
   291  		}
   292  		// Make sure the result channel is assigned.
   293  		if results == nil {
   294  			log.Warn("Ethash result channel is empty, submitted mining result is rejected")
   295  			return false
   296  		}
   297  		log.Trace("Verified correct proof-of-work", "sealhash", sealhash, "elapsed", time.Since(start))
   298  
   299  		// Solutions seems to be valid, return to the miner and notify acceptance.
   300  		solution := block.WithSeal(header)
   301  
   302  		// The submitted solution is within the scope of acceptance.
   303  		if solution.NumberU64()+staleThreshold > currentBlock.NumberU64() {
   304  			select {
   305  			case results <- solution:
   306  				log.Debug("Work submitted is acceptable", "number", solution.NumberU64(), "sealhash", sealhash, "hash", solution.Hash())
   307  				return true
   308  			default:
   309  				log.Warn("Sealing result is not read by miner", "mode", "remote", "sealhash", sealhash)
   310  				return false
   311  			}
   312  		}
   313  		// The submitted block is too old to accept, drop it.
   314  		log.Warn("Work submitted is too old", "number", solution.NumberU64(), "sealhash", sealhash, "hash", solution.Hash())
   315  		return false
   316  	}
   317  
   318  	ticker := time.NewTicker(5 * time.Second)
   319  	defer ticker.Stop()
   320  
   321  	for {
   322  		select {
   323  		case work := <-ethash.workCh:
   324  			// Update current work with new received block.
   325  			// Note same work can be past twice, happens when changing CPU threads.
   326  			results = work.results
   327  
   328  			makeWork(work.block)
   329  
   330  			// Notify and requested URLs of the new work availability
   331  			notifyWork()
   332  
   333  		case work := <-ethash.fetchWorkCh:
   334  			// Return current mining work to remote miner.
   335  			if currentBlock == nil {
   336  				work.errc <- errNoMiningWork
   337  			} else {
   338  				work.res <- currentWork
   339  			}
   340  
   341  		case result := <-ethash.submitWorkCh:
   342  			// Verify submitted PoW solution based on maintained mining blocks.
   343  			if submitWork(result.nonce, result.mixDigest, result.hash) {
   344  				result.errc <- nil
   345  			} else {
   346  				result.errc <- errInvalidSealResult
   347  			}
   348  
   349  		case result := <-ethash.submitRateCh:
   350  			// Trace remote sealer's hash rate by submitted value.
   351  			rates[result.id] = hashrate{rate: result.rate, ping: time.Now()}
   352  			close(result.done)
   353  
   354  		case req := <-ethash.fetchRateCh:
   355  			// Gather all hash rate submitted by remote sealer.
   356  			var total uint64
   357  			for _, rate := range rates {
   358  				// this could overflow
   359  				total += rate.rate
   360  			}
   361  			req <- total
   362  
   363  		case <-ticker.C:
   364  			// Clear stale submitted hash rate.
   365  			for id, rate := range rates {
   366  				if time.Since(rate.ping) > 10*time.Second {
   367  					delete(rates, id)
   368  				}
   369  			}
   370  			// Clear stale pending blocks
   371  			if currentBlock != nil {
   372  				for hash, block := range works {
   373  					if block.NumberU64()+staleThreshold <= currentBlock.NumberU64() {
   374  						delete(works, hash)
   375  					}
   376  				}
   377  			}
   378  
   379  		case errc := <-ethash.exitCh:
   380  			// Exit remote loop if ethash is closed and return relevant error.
   381  			errc <- nil
   382  			log.Trace("Ethash remote sealer is exiting")
   383  			return
   384  		}
   385  	}
   386  }