github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/consensus/ethash/sealer.go (about)

     1  // Copyright 2018 Wanchain Foundation Ltd
     2  // Copyright 2017 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package ethash
    19  
    20  import (
    21  	crand "crypto/rand"
    22  	"math"
    23  	"math/big"
    24  	"math/rand"
    25  	"runtime"
    26  	"sync"
    27  
    28  	"github.com/wanchain/go-wanchain/accounts"
    29  	"github.com/wanchain/go-wanchain/common"
    30  	"github.com/wanchain/go-wanchain/consensus"
    31  	"github.com/wanchain/go-wanchain/core/types"
    32  	"github.com/wanchain/go-wanchain/log"
    33  )
    34  
    35  // Seal implements consensus.Engine, attempting to find a nonce that satisfies
    36  // the block's difficulty requirements.
    37  func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
    38  	header := block.Header()
    39  	// permission signer signing the header
    40  	sighash, err := ethash.signFn(accounts.Account{Address: block.Coinbase()}, sigHash(block.Header()).Bytes())
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
    46  	block = block.WithSeal(header)
    47  
    48  	// If we're running a fake PoW, simply return a 0 nonce immediately
    49  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
    50  		header := block.Header()
    51  		header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
    52  		return block.WithSeal(header), nil
    53  	}
    54  	// If we're running a shared PoW, delegate sealing to it
    55  	if ethash.shared != nil {
    56  		return ethash.shared.Seal(chain, block, stop)
    57  	}
    58  	// Create a runner and the multiple search threads it directs
    59  	abort := make(chan struct{})
    60  	found := make(chan *types.Block)
    61  
    62  	ethash.lock.Lock()
    63  	threads := ethash.threads
    64  	if ethash.rand == nil {
    65  		seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    66  		if err != nil {
    67  			ethash.lock.Unlock()
    68  			return nil, err
    69  		}
    70  		ethash.rand = rand.New(rand.NewSource(seed.Int64()))
    71  	}
    72  	ethash.lock.Unlock()
    73  	if threads == 0 {
    74  		threads = runtime.NumCPU()
    75  	}
    76  	if threads < 0 {
    77  		threads = 0 // Allows disabling local mining without extra logic around local/remote
    78  	}
    79  	var pend sync.WaitGroup
    80  	for i := 0; i < threads; i++ {
    81  		pend.Add(1)
    82  		go func(id int, nonce uint64) {
    83  			defer pend.Done()
    84  			ethash.mine(block, id, nonce, abort, found)
    85  		}(i, uint64(ethash.rand.Int63()))
    86  	}
    87  	// Wait until sealing is terminated or a nonce is found
    88  	var result *types.Block
    89  	select {
    90  	case <-stop:
    91  		// Outside abort, stop all miner threads
    92  		close(abort)
    93  	case result = <-found:
    94  		// One of the threads found a block, abort all others
    95  		close(abort)
    96  	case <-ethash.update:
    97  		// Thread count was changed on user request, restart
    98  		close(abort)
    99  		pend.Wait()
   100  		return ethash.Seal(chain, block, stop)
   101  	}
   102  	// Wait for all miners to terminate and return the block
   103  	pend.Wait()
   104  	return result, nil
   105  }
   106  
   107  // mine is the actual proof-of-work miner that searches for a nonce starting from
   108  // seed that results in correct final block difficulty.
   109  func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) {
   110  	// Extract some data from the header
   111  	var (
   112  		header = block.Header()
   113  		hash   = header.HashNoNonce().Bytes()
   114  		target = new(big.Int).Div(maxUint256, header.Difficulty)
   115  
   116  		number  = header.Number.Uint64()
   117  		dataset = ethash.dataset(number)
   118  	)
   119  	// Start generating random nonces until we abort or find a good one
   120  	var (
   121  		attempts = int64(0)
   122  		nonce    = seed
   123  	)
   124  	logger := log.New("miner", id)
   125  	logger.Trace("Started ethash search for new nonces", "seed", seed)
   126  search:
   127  	for {
   128  		select {
   129  		case <-abort:
   130  			// Mining terminated, update stats and abort
   131  			logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
   132  			ethash.hashrate.Mark(attempts)
   133  			break search
   134  
   135  		default:
   136  			// We don't have to update hash rate on every nonce, so update after after 2^X nonces
   137  			attempts++
   138  			if (attempts % (1 << 15)) == 0 {
   139  				ethash.hashrate.Mark(attempts)
   140  				attempts = 0
   141  			}
   142  			// Compute the PoW value of this nonce
   143  			digest, result := hashimotoFull(dataset.dataset, hash, nonce)
   144  			if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
   145  				// Correct nonce found, create a new header with it
   146  				header = types.CopyHeader(header)
   147  				header.Nonce = types.EncodeNonce(nonce)
   148  				header.MixDigest = common.BytesToHash(digest)
   149  
   150  				// Seal and return a block (if still needed)
   151  				select {
   152  				case found <- block.WithSeal(header):
   153  					logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
   154  				case <-abort:
   155  					logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
   156  				}
   157  				break search
   158  			}
   159  			nonce++
   160  		}
   161  	}
   162  	// Datasets are unmapped in a finalizer. Ensure that the dataset stays live
   163  	// during sealing so it's not unmapped while being read.
   164  	runtime.KeepAlive(dataset)
   165  }