gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/consensus/aquahash/sealer.go (about)

     1  // Copyright 2018 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  		log.Trace("[sealer] Using aquahash engine", "chaincfg", chaincfg.String())
    44  	}
    45  	if aquahash.config.PowMode == ModeFake || aquahash.config.PowMode == ModeFullFake {
    46  		log.Trace("[sealer] aquahash engine using fake POW")
    47  		header := block.Header()
    48  		header.Version = chaincfg.GetBlockVersion(header.Number)
    49  		header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
    50  		return block.WithSeal(header), nil
    51  	}
    52  	// If we're running a shared PoW, delegate sealing to it
    53  	if aquahash.shared != nil {
    54  		return aquahash.shared.Seal(chain, block, stop)
    55  	}
    56  	// Create a runner and the multiple search threads it directs
    57  	abort := make(chan struct{})
    58  	found := make(chan *types.Block)
    59  
    60  	aquahash.lock.Lock()
    61  	threads := aquahash.threads
    62  	if aquahash.rand == nil {
    63  		seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    64  		if err != nil {
    65  			aquahash.lock.Unlock()
    66  			return nil, err
    67  		}
    68  		aquahash.rand = rand.New(rand.NewSource(seed.Int64()))
    69  	}
    70  	aquahash.lock.Unlock()
    71  	if threads == 0 {
    72  		threads = runtime.NumCPU()
    73  	}
    74  	if threads < 0 {
    75  		threads = 0 // Allows disabling local mining without extra logic around local/remote
    76  	}
    77  	var pend sync.WaitGroup
    78  	version := chaincfg.GetBlockVersion(block.Number())
    79  	for i := 0; i < threads; i++ {
    80  		pend.Add(1)
    81  		go func(id int, nonce uint64) {
    82  			defer pend.Done()
    83  			log.Trace("launching miner", "algoVersion", version)
    84  			aquahash.mine(version, block, id, nonce, abort, found)
    85  		}(i, uint64(aquahash.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 <-aquahash.update:
    97  		// Thread count was changed on user request, restart
    98  		close(abort)
    99  		pend.Wait()
   100  		return aquahash.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 (aquahash *Aquahash) mine(version params.HeaderVersion, 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  		number  = header.Number.Uint64()
   116  		dataset *dataset
   117  	)
   118  	header.Version = version
   119  	if header.Version == 0 || header.Version > crypto.KnownVersion {
   120  		common.Report("Mining incorrect version")
   121  		return
   122  	}
   123  	if header.Version == 1 {
   124  		dataset = aquahash.dataset(number)
   125  	}
   126  
   127  	// Start generating random nonces until we abort or find a good one
   128  	var (
   129  		attempts = int64(0)
   130  		nonce    = seed
   131  	)
   132  	logger := log.New("miner", id)
   133  	logger.Trace("Started aquahash search for new nonces", "seed", seed, "algo", version)
   134  search:
   135  	for {
   136  
   137  		select {
   138  		case <-abort:
   139  			// Mining terminated, update stats and abort
   140  			logger.Trace("Aquahash nonce search aborted", "attempts", nonce-seed)
   141  			aquahash.hashrate.Mark(attempts)
   142  			break search
   143  
   144  		default:
   145  			// We don't have to update hash rate on every nonce, so update after after 2^X nonces
   146  			attempts++
   147  			if (attempts % (1 << 15)) == 0 {
   148  				aquahash.hashrate.Mark(attempts)
   149  				attempts = 0
   150  			}
   151  
   152  			// Compute the PoW value of this nonce
   153  			var (
   154  				digest []byte
   155  				result []byte
   156  			)
   157  
   158  			switch header.Version {
   159  			case 1:
   160  				digest, result = hashimotoFull(dataset.dataset, hash, nonce)
   161  			default:
   162  				seed := make([]byte, 40)
   163  				copy(seed, hash)
   164  				binary.LittleEndian.PutUint64(seed[32:], nonce)
   165  				result = crypto.VersionHash(byte(header.Version), seed)
   166  				digest = make([]byte, common.HashLength)
   167  			}
   168  
   169  			if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
   170  				// Correct nonce found, create a new header with it
   171  				header = types.CopyHeader(header)
   172  				header.Nonce = types.EncodeNonce(nonce)
   173  				header.MixDigest = common.BytesToHash(digest)
   174  
   175  				// Seal and return a block (if still needed)
   176  				select {
   177  				case found <- block.WithSeal(header):
   178  					logger.Trace("Aquahash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
   179  				case <-abort:
   180  					logger.Trace("Aquahash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
   181  				}
   182  				break search
   183  			}
   184  			nonce++
   185  		}
   186  	}
   187  	// Datasets are unmapped in a finalizer. Ensure that the dataset stays live
   188  	// during sealing so it's not unmapped while being read.
   189  	if dataset != nil {
   190  		runtime.KeepAlive(dataset)
   191  	}
   192  }