github.com/aquanetwork/aquachain@v1.7.8/consensus/aquahash/sealer.go (about)

     1  // Copyright 2017 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package aquahash
    18  
    19  import (
    20  	crand "crypto/rand"
    21  	"encoding/binary"
    22  	"math"
    23  	"math/big"
    24  	"math/rand"
    25  	"runtime"
    26  	"sync"
    27  
    28  	"gitlab.com/aquachain/aquachain/common"
    29  	"gitlab.com/aquachain/aquachain/common/log"
    30  	"gitlab.com/aquachain/aquachain/consensus"
    31  	"gitlab.com/aquachain/aquachain/core/types"
    32  	"gitlab.com/aquachain/aquachain/crypto"
    33  	"gitlab.com/aquachain/aquachain/params"
    34  )
    35  
    36  // Seal implements consensus.Engine, attempting to find a nonce that satisfies
    37  // the block's difficulty requirements.
    38  func (aquahash *Aquahash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
    39  	// If we're running a fake PoW, simply return a 0 nonce immediately
    40  	chaincfg := params.TestChainConfig
    41  	if chain != nil {
    42  		chaincfg = chain.Config()
    43  	}
    44  	if aquahash.config.PowMode == ModeFake || aquahash.config.PowMode == ModeFullFake {
    45  		header := block.Header()
    46  		header.Version = chaincfg.GetBlockVersion(header.Number)
    47  		header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
    48  		return block.WithSeal(header), nil
    49  	}
    50  	// If we're running a shared PoW, delegate sealing to it
    51  	if aquahash.shared != nil {
    52  		return aquahash.shared.Seal(chain, block, stop)
    53  	}
    54  	// Create a runner and the multiple search threads it directs
    55  	abort := make(chan struct{})
    56  	found := make(chan *types.Block)
    57  
    58  	aquahash.lock.Lock()
    59  	threads := aquahash.threads
    60  	if aquahash.rand == nil {
    61  		seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    62  		if err != nil {
    63  			aquahash.lock.Unlock()
    64  			return nil, err
    65  		}
    66  		aquahash.rand = rand.New(rand.NewSource(seed.Int64()))
    67  	}
    68  	aquahash.lock.Unlock()
    69  	if threads == 0 {
    70  		threads = runtime.NumCPU()
    71  	}
    72  	if threads < 0 {
    73  		threads = 0 // Allows disabling local mining without extra logic around local/remote
    74  	}
    75  	var pend sync.WaitGroup
    76  	version := chaincfg.GetBlockVersion(block.Number())
    77  	for i := 0; i < threads; i++ {
    78  		pend.Add(1)
    79  		go func(id int, nonce uint64) {
    80  			defer pend.Done()
    81  			aquahash.mine(version, block, id, nonce, abort, found)
    82  		}(i, uint64(aquahash.rand.Int63()))
    83  	}
    84  	// Wait until sealing is terminated or a nonce is found
    85  	var result *types.Block
    86  	select {
    87  	case <-stop:
    88  		// Outside abort, stop all miner threads
    89  		close(abort)
    90  	case result = <-found:
    91  		// One of the threads found a block, abort all others
    92  		close(abort)
    93  	case <-aquahash.update:
    94  		// Thread count was changed on user request, restart
    95  		close(abort)
    96  		pend.Wait()
    97  		return aquahash.Seal(chain, block, stop)
    98  	}
    99  	// Wait for all miners to terminate and return the block
   100  	pend.Wait()
   101  	return result, nil
   102  }
   103  
   104  // mine is the actual proof-of-work miner that searches for a nonce starting from
   105  // seed that results in correct final block difficulty.
   106  func (aquahash *Aquahash) mine(version params.HeaderVersion, block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) {
   107  	// Extract some data from the header
   108  	var (
   109  		header  = block.Header()
   110  		hash    = header.HashNoNonce().Bytes()
   111  		target  = new(big.Int).Div(maxUint256, header.Difficulty)
   112  		number  = header.Number.Uint64()
   113  		dataset *dataset
   114  	)
   115  	header.Version = version
   116  	if header.Version == 0 || header.Version > crypto.KnownVersion {
   117  		common.Report("Mining incorrect version")
   118  		return
   119  	}
   120  	if header.Version < 2 {
   121  		dataset = aquahash.dataset(number)
   122  	}
   123  
   124  	// Start generating random nonces until we abort or find a good one
   125  	var (
   126  		attempts = int64(0)
   127  		nonce    = seed
   128  	)
   129  	logger := log.New("miner", id)
   130  	logger.Trace("Started aquahash search for new nonces", "seed", seed, "algo", version)
   131  search:
   132  	for {
   133  
   134  		select {
   135  		case <-abort:
   136  			// Mining terminated, update stats and abort
   137  			logger.Trace("Aquahash nonce search aborted", "attempts", nonce-seed)
   138  			aquahash.hashrate.Mark(attempts)
   139  			break search
   140  
   141  		default:
   142  			// We don't have to update hash rate on every nonce, so update after after 2^X nonces
   143  			attempts++
   144  			if (attempts % (1 << 15)) == 0 {
   145  				aquahash.hashrate.Mark(attempts)
   146  				attempts = 0
   147  			}
   148  
   149  			// Compute the PoW value of this nonce
   150  			var (
   151  				digest []byte
   152  				result []byte
   153  			)
   154  
   155  			switch header.Version {
   156  			case 1:
   157  				digest, result = hashimotoFull(dataset.dataset, hash, nonce)
   158  			default:
   159  				seed := make([]byte, 40)
   160  				copy(seed, hash)
   161  				binary.LittleEndian.PutUint64(seed[32:], nonce)
   162  				result = crypto.VersionHash(byte(header.Version), seed)
   163  				digest = make([]byte, common.HashLength)
   164  			}
   165  
   166  			if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
   167  				// Correct nonce found, create a new header with it
   168  				header = types.CopyHeader(header)
   169  				header.Nonce = types.EncodeNonce(nonce)
   170  				header.MixDigest = common.BytesToHash(digest)
   171  
   172  				// Seal and return a block (if still needed)
   173  				select {
   174  				case found <- block.WithSeal(header):
   175  					logger.Trace("Aquahash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
   176  				case <-abort:
   177  					logger.Trace("Aquahash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
   178  				}
   179  				break search
   180  			}
   181  			nonce++
   182  		}
   183  	}
   184  	// Datasets are unmapped in a finalizer. Ensure that the dataset stays live
   185  	// during sealing so it's not unmapped while being read.
   186  	if dataset != nil {
   187  		runtime.KeepAlive(dataset)
   188  	}
   189  }