github.com/gilgames000/kcc-geth@v1.0.6/consensus/ethash/consensus.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  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"runtime"
    25  	"time"
    26  
    27  	mapset "github.com/deckarep/golang-set"
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/common/math"
    30  	"github.com/ethereum/go-ethereum/consensus"
    31  	"github.com/ethereum/go-ethereum/consensus/misc"
    32  	"github.com/ethereum/go-ethereum/core/state"
    33  	"github.com/ethereum/go-ethereum/core/types"
    34  	"github.com/ethereum/go-ethereum/params"
    35  	"github.com/ethereum/go-ethereum/rlp"
    36  	"github.com/ethereum/go-ethereum/trie"
    37  	"golang.org/x/crypto/sha3"
    38  )
    39  
    40  // Ethash proof-of-work protocol constants.
    41  var (
    42  	FrontierBlockReward           = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
    43  	ByzantiumBlockReward          = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
    44  	ConstantinopleBlockReward     = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
    45  	maxUncles                     = 2                 // Maximum number of uncles allowed in a single block
    46  	allowedFutureBlockTimeSeconds = int64(15)         // Max seconds from current time allowed for blocks, before they're considered future blocks
    47  
    48  	// calcDifficultyEip2384 is the difficulty adjustment algorithm as specified by EIP 2384.
    49  	// It offsets the bomb 4M blocks from Constantinople, so in total 9M blocks.
    50  	// Specification EIP-2384: https://eips.ethereum.org/EIPS/eip-2384
    51  	calcDifficultyEip2384 = makeDifficultyCalculator(big.NewInt(9000000))
    52  
    53  	// calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
    54  	// It returns the difficulty that a new block should have when created at time given the
    55  	// parent block's time and difficulty. The calculation uses the Byzantium rules, but with
    56  	// bomb offset 5M.
    57  	// Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
    58  	calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
    59  
    60  	// calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
    61  	// the difficulty that a new block should have when created at time given the
    62  	// parent block's time and difficulty. The calculation uses the Byzantium rules.
    63  	// Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
    64  	calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
    65  )
    66  
    67  // Various error messages to mark blocks invalid. These should be private to
    68  // prevent engine specific errors from being referenced in the remainder of the
    69  // codebase, inherently breaking if the engine is swapped out. Please put common
    70  // error types into the consensus package.
    71  var (
    72  	errOlderBlockTime    = errors.New("timestamp older than parent")
    73  	errTooManyUncles     = errors.New("too many uncles")
    74  	errDuplicateUncle    = errors.New("duplicate uncle")
    75  	errUncleIsAncestor   = errors.New("uncle is ancestor")
    76  	errDanglingUncle     = errors.New("uncle's parent is not ancestor")
    77  	errInvalidDifficulty = errors.New("non-positive difficulty")
    78  	errInvalidMixDigest  = errors.New("invalid mix digest")
    79  	errInvalidPoW        = errors.New("invalid proof-of-work")
    80  )
    81  
    82  // Author implements consensus.Engine, returning the header's coinbase as the
    83  // proof-of-work verified author of the block.
    84  func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
    85  	return header.Coinbase, nil
    86  }
    87  
    88  // VerifyHeader checks whether a header conforms to the consensus rules of the
    89  // stock Ethereum ethash engine.
    90  func (ethash *Ethash) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
    91  	// If we're running a full engine faking, accept any input as valid
    92  	if ethash.config.PowMode == ModeFullFake {
    93  		return nil
    94  	}
    95  	// Short circuit if the header is known, or its parent not
    96  	number := header.Number.Uint64()
    97  	if chain.GetHeader(header.Hash(), number) != nil {
    98  		return nil
    99  	}
   100  	parent := chain.GetHeader(header.ParentHash, number-1)
   101  	if parent == nil {
   102  		return consensus.ErrUnknownAncestor
   103  	}
   104  	// Sanity checks passed, do a proper verification
   105  	return ethash.verifyHeader(chain, header, parent, false, seal, time.Now().Unix())
   106  }
   107  
   108  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
   109  // concurrently. The method returns a quit channel to abort the operations and
   110  // a results channel to retrieve the async verifications.
   111  func (ethash *Ethash) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   112  	// If we're running a full engine faking, accept any input as valid
   113  	if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
   114  		abort, results := make(chan struct{}), make(chan error, len(headers))
   115  		for i := 0; i < len(headers); i++ {
   116  			results <- nil
   117  		}
   118  		return abort, results
   119  	}
   120  
   121  	// Spawn as many workers as allowed threads
   122  	workers := runtime.GOMAXPROCS(0)
   123  	if len(headers) < workers {
   124  		workers = len(headers)
   125  	}
   126  
   127  	// Create a task channel and spawn the verifiers
   128  	var (
   129  		inputs  = make(chan int)
   130  		done    = make(chan int, workers)
   131  		errors  = make([]error, len(headers))
   132  		abort   = make(chan struct{})
   133  		unixNow = time.Now().Unix()
   134  	)
   135  	for i := 0; i < workers; i++ {
   136  		go func() {
   137  			for index := range inputs {
   138  				errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index, unixNow)
   139  				done <- index
   140  			}
   141  		}()
   142  	}
   143  
   144  	errorsOut := make(chan error, len(headers))
   145  	go func() {
   146  		defer close(inputs)
   147  		var (
   148  			in, out = 0, 0
   149  			checked = make([]bool, len(headers))
   150  			inputs  = inputs
   151  		)
   152  		for {
   153  			select {
   154  			case inputs <- in:
   155  				if in++; in == len(headers) {
   156  					// Reached end of headers. Stop sending to workers.
   157  					inputs = nil
   158  				}
   159  			case index := <-done:
   160  				for checked[index] = true; checked[out]; out++ {
   161  					errorsOut <- errors[out]
   162  					if out == len(headers)-1 {
   163  						return
   164  					}
   165  				}
   166  			case <-abort:
   167  				return
   168  			}
   169  		}
   170  	}()
   171  	return abort, errorsOut
   172  }
   173  
   174  func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int, unixNow int64) error {
   175  	var parent *types.Header
   176  	if index == 0 {
   177  		parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
   178  	} else if headers[index-1].Hash() == headers[index].ParentHash {
   179  		parent = headers[index-1]
   180  	}
   181  	if parent == nil {
   182  		return consensus.ErrUnknownAncestor
   183  	}
   184  	return ethash.verifyHeader(chain, headers[index], parent, false, seals[index], unixNow)
   185  }
   186  
   187  // VerifyUncles verifies that the given block's uncles conform to the consensus
   188  // rules of the stock Ethereum ethash engine.
   189  func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   190  	// If we're running a full engine faking, accept any input as valid
   191  	if ethash.config.PowMode == ModeFullFake {
   192  		return nil
   193  	}
   194  	// Verify that there are at most 2 uncles included in this block
   195  	if len(block.Uncles()) > maxUncles {
   196  		return errTooManyUncles
   197  	}
   198  	if len(block.Uncles()) == 0 {
   199  		return nil
   200  	}
   201  	// Gather the set of past uncles and ancestors
   202  	uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
   203  
   204  	number, parent := block.NumberU64()-1, block.ParentHash()
   205  	for i := 0; i < 7; i++ {
   206  		ancestor := chain.GetBlock(parent, number)
   207  		if ancestor == nil {
   208  			break
   209  		}
   210  		ancestors[ancestor.Hash()] = ancestor.Header()
   211  		for _, uncle := range ancestor.Uncles() {
   212  			uncles.Add(uncle.Hash())
   213  		}
   214  		parent, number = ancestor.ParentHash(), number-1
   215  	}
   216  	ancestors[block.Hash()] = block.Header()
   217  	uncles.Add(block.Hash())
   218  
   219  	// Verify each of the uncles that it's recent, but not an ancestor
   220  	for _, uncle := range block.Uncles() {
   221  		// Make sure every uncle is rewarded only once
   222  		hash := uncle.Hash()
   223  		if uncles.Contains(hash) {
   224  			return errDuplicateUncle
   225  		}
   226  		uncles.Add(hash)
   227  
   228  		// Make sure the uncle has a valid ancestry
   229  		if ancestors[hash] != nil {
   230  			return errUncleIsAncestor
   231  		}
   232  		if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
   233  			return errDanglingUncle
   234  		}
   235  		if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true, time.Now().Unix()); err != nil {
   236  			return err
   237  		}
   238  	}
   239  	return nil
   240  }
   241  
   242  // verifyHeader checks whether a header conforms to the consensus rules of the
   243  // stock Ethereum ethash engine.
   244  // See YP section 4.3.4. "Block Header Validity"
   245  func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool, unixNow int64) error {
   246  	// Ensure that the header's extra-data section is of a reasonable size
   247  	if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
   248  		return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
   249  	}
   250  	// Verify the header's timestamp
   251  	if !uncle {
   252  		if header.Time > uint64(unixNow+allowedFutureBlockTimeSeconds) {
   253  			return consensus.ErrFutureBlock
   254  		}
   255  	}
   256  	if header.Time <= parent.Time {
   257  		return errOlderBlockTime
   258  	}
   259  	// Verify the block's difficulty based on its timestamp and parent's difficulty
   260  	expected := ethash.CalcDifficulty(chain, header.Time, parent)
   261  
   262  	if expected.Cmp(header.Difficulty) != 0 {
   263  		return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
   264  	}
   265  	// Verify that the gas limit is <= 2^63-1
   266  	cap := uint64(0x7fffffffffffffff)
   267  	if header.GasLimit > cap {
   268  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   269  	}
   270  	// Verify that the gasUsed is <= gasLimit
   271  	if header.GasUsed > header.GasLimit {
   272  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   273  	}
   274  
   275  	// Verify that the gas limit remains within allowed bounds
   276  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   277  	if diff < 0 {
   278  		diff *= -1
   279  	}
   280  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   281  
   282  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   283  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   284  	}
   285  	// Verify that the block number is parent's +1
   286  	if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
   287  		return consensus.ErrInvalidNumber
   288  	}
   289  	// Verify the engine specific seal securing the block
   290  	if seal {
   291  		if err := ethash.verifySeal(chain, header, false); err != nil {
   292  			return err
   293  		}
   294  	}
   295  	// If all checks passed, validate any special fields for hard forks
   296  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   297  		return err
   298  	}
   299  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   300  		return err
   301  	}
   302  	return nil
   303  }
   304  
   305  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   306  // the difficulty that a new block should have when created at time
   307  // given the parent block's time and difficulty.
   308  func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   309  	return CalcDifficulty(chain.Config(), time, parent)
   310  }
   311  
   312  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   313  // the difficulty that a new block should have when created at time
   314  // given the parent block's time and difficulty.
   315  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   316  	next := new(big.Int).Add(parent.Number, big1)
   317  	switch {
   318  	case config.IsMuirGlacier(next):
   319  		return calcDifficultyEip2384(time, parent)
   320  	case config.IsConstantinople(next):
   321  		return calcDifficultyConstantinople(time, parent)
   322  	case config.IsByzantium(next):
   323  		return calcDifficultyByzantium(time, parent)
   324  	case config.IsHomestead(next):
   325  		return calcDifficultyHomestead(time, parent)
   326  	default:
   327  		return calcDifficultyFrontier(time, parent)
   328  	}
   329  }
   330  
   331  // Some weird constants to avoid constant memory allocs for them.
   332  var (
   333  	expDiffPeriod = big.NewInt(100000)
   334  	big1          = big.NewInt(1)
   335  	big2          = big.NewInt(2)
   336  	big9          = big.NewInt(9)
   337  	big10         = big.NewInt(10)
   338  	bigMinus99    = big.NewInt(-99)
   339  )
   340  
   341  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   342  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   343  // how uncles affect the calculation
   344  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   345  	// Note, the calculations below looks at the parent number, which is 1 below
   346  	// the block number. Thus we remove one from the delay given
   347  	bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   348  	return func(time uint64, parent *types.Header) *big.Int {
   349  		// https://github.com/ethereum/EIPs/issues/100.
   350  		// algorithm:
   351  		// diff = (parent_diff +
   352  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   353  		//        ) + 2^(periodCount - 2)
   354  
   355  		bigTime := new(big.Int).SetUint64(time)
   356  		bigParentTime := new(big.Int).SetUint64(parent.Time)
   357  
   358  		// holds intermediate values to make the algo easier to read & audit
   359  		x := new(big.Int)
   360  		y := new(big.Int)
   361  
   362  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   363  		x.Sub(bigTime, bigParentTime)
   364  		x.Div(x, big9)
   365  		if parent.UncleHash == types.EmptyUncleHash {
   366  			x.Sub(big1, x)
   367  		} else {
   368  			x.Sub(big2, x)
   369  		}
   370  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   371  		if x.Cmp(bigMinus99) < 0 {
   372  			x.Set(bigMinus99)
   373  		}
   374  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   375  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   376  		x.Mul(y, x)
   377  		x.Add(parent.Difficulty, x)
   378  
   379  		// minimum difficulty can ever be (before exponential factor)
   380  		if x.Cmp(params.MinimumDifficulty) < 0 {
   381  			x.Set(params.MinimumDifficulty)
   382  		}
   383  		// calculate a fake block number for the ice-age delay
   384  		// Specification: https://eips.ethereum.org/EIPS/eip-1234
   385  		fakeBlockNumber := new(big.Int)
   386  		if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   387  			fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   388  		}
   389  		// for the exponential factor
   390  		periodCount := fakeBlockNumber
   391  		periodCount.Div(periodCount, expDiffPeriod)
   392  
   393  		// the exponential factor, commonly referred to as "the bomb"
   394  		// diff = diff + 2^(periodCount - 2)
   395  		if periodCount.Cmp(big1) > 0 {
   396  			y.Sub(periodCount, big2)
   397  			y.Exp(big2, y, nil)
   398  			x.Add(x, y)
   399  		}
   400  		return x
   401  	}
   402  }
   403  
   404  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   405  // the difficulty that a new block should have when created at time given the
   406  // parent block's time and difficulty. The calculation uses the Homestead rules.
   407  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   408  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   409  	// algorithm:
   410  	// diff = (parent_diff +
   411  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   412  	//        ) + 2^(periodCount - 2)
   413  
   414  	bigTime := new(big.Int).SetUint64(time)
   415  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   416  
   417  	// holds intermediate values to make the algo easier to read & audit
   418  	x := new(big.Int)
   419  	y := new(big.Int)
   420  
   421  	// 1 - (block_timestamp - parent_timestamp) // 10
   422  	x.Sub(bigTime, bigParentTime)
   423  	x.Div(x, big10)
   424  	x.Sub(big1, x)
   425  
   426  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   427  	if x.Cmp(bigMinus99) < 0 {
   428  		x.Set(bigMinus99)
   429  	}
   430  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   431  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   432  	x.Mul(y, x)
   433  	x.Add(parent.Difficulty, x)
   434  
   435  	// minimum difficulty can ever be (before exponential factor)
   436  	if x.Cmp(params.MinimumDifficulty) < 0 {
   437  		x.Set(params.MinimumDifficulty)
   438  	}
   439  	// for the exponential factor
   440  	periodCount := new(big.Int).Add(parent.Number, big1)
   441  	periodCount.Div(periodCount, expDiffPeriod)
   442  
   443  	// the exponential factor, commonly referred to as "the bomb"
   444  	// diff = diff + 2^(periodCount - 2)
   445  	if periodCount.Cmp(big1) > 0 {
   446  		y.Sub(periodCount, big2)
   447  		y.Exp(big2, y, nil)
   448  		x.Add(x, y)
   449  	}
   450  	return x
   451  }
   452  
   453  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   454  // difficulty that a new block should have when created at time given the parent
   455  // block's time and difficulty. The calculation uses the Frontier rules.
   456  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   457  	diff := new(big.Int)
   458  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   459  	bigTime := new(big.Int)
   460  	bigParentTime := new(big.Int)
   461  
   462  	bigTime.SetUint64(time)
   463  	bigParentTime.SetUint64(parent.Time)
   464  
   465  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   466  		diff.Add(parent.Difficulty, adjust)
   467  	} else {
   468  		diff.Sub(parent.Difficulty, adjust)
   469  	}
   470  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   471  		diff.Set(params.MinimumDifficulty)
   472  	}
   473  
   474  	periodCount := new(big.Int).Add(parent.Number, big1)
   475  	periodCount.Div(periodCount, expDiffPeriod)
   476  	if periodCount.Cmp(big1) > 0 {
   477  		// diff = diff + 2^(periodCount - 2)
   478  		expDiff := periodCount.Sub(periodCount, big2)
   479  		expDiff.Exp(big2, expDiff, nil)
   480  		diff.Add(diff, expDiff)
   481  		diff = math.BigMax(diff, params.MinimumDifficulty)
   482  	}
   483  	return diff
   484  }
   485  
   486  // Exported for fuzzing
   487  var FrontierDifficultyCalulator = calcDifficultyFrontier
   488  var HomesteadDifficultyCalulator = calcDifficultyHomestead
   489  var DynamicDifficultyCalculator = makeDifficultyCalculator
   490  
   491  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   492  // either using the usual ethash cache for it, or alternatively using a full DAG
   493  // to make remote mining fast.
   494  func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
   495  	// If we're running a fake PoW, accept any seal as valid
   496  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   497  		time.Sleep(ethash.fakeDelay)
   498  		if ethash.fakeFail == header.Number.Uint64() {
   499  			return errInvalidPoW
   500  		}
   501  		return nil
   502  	}
   503  	// If we're running a shared PoW, delegate verification to it
   504  	if ethash.shared != nil {
   505  		return ethash.shared.verifySeal(chain, header, fulldag)
   506  	}
   507  	// Ensure that we have a valid difficulty for the block
   508  	if header.Difficulty.Sign() <= 0 {
   509  		return errInvalidDifficulty
   510  	}
   511  	// Recompute the digest and PoW values
   512  	number := header.Number.Uint64()
   513  
   514  	var (
   515  		digest []byte
   516  		result []byte
   517  	)
   518  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   519  	if fulldag {
   520  		dataset := ethash.dataset(number, true)
   521  		if dataset.generated() {
   522  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   523  
   524  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   525  			// until after the call to hashimotoFull so it's not unmapped while being used.
   526  			runtime.KeepAlive(dataset)
   527  		} else {
   528  			// Dataset not yet generated, don't hang, use a cache instead
   529  			fulldag = false
   530  		}
   531  	}
   532  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   533  	if !fulldag {
   534  		cache := ethash.cache(number)
   535  
   536  		size := datasetSize(number)
   537  		if ethash.config.PowMode == ModeTest {
   538  			size = 32 * 1024
   539  		}
   540  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   541  
   542  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   543  		// until after the call to hashimotoLight so it's not unmapped while being used.
   544  		runtime.KeepAlive(cache)
   545  	}
   546  	// Verify the calculated values against the ones provided in the header
   547  	if !bytes.Equal(header.MixDigest[:], digest) {
   548  		return errInvalidMixDigest
   549  	}
   550  	target := new(big.Int).Div(two256, header.Difficulty)
   551  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   552  		return errInvalidPoW
   553  	}
   554  	return nil
   555  }
   556  
   557  // Prepare implements consensus.Engine, initializing the difficulty field of a
   558  // header to conform to the ethash protocol. The changes are done inline.
   559  func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   560  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   561  	if parent == nil {
   562  		return consensus.ErrUnknownAncestor
   563  	}
   564  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
   565  	return nil
   566  }
   567  
   568  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   569  // setting the final state on the header
   570  func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) error {
   571  	// Accumulate any block and uncle rewards and commit the final state root
   572  	accumulateRewards(chain.Config(), state, header, uncles)
   573  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   574  
   575  	return nil
   576  }
   577  
   578  // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
   579  // uncle rewards, setting the final state and assembling the block.
   580  func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
   581  	// Finalize block
   582  	ethash.Finalize(chain, header, state, txs, uncles)
   583  
   584  	// Header seems complete, assemble into a block and return
   585  	return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), nil
   586  }
   587  
   588  // SealHash returns the hash of a block prior to it being sealed.
   589  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   590  	hasher := sha3.NewLegacyKeccak256()
   591  
   592  	rlp.Encode(hasher, []interface{}{
   593  		header.ParentHash,
   594  		header.UncleHash,
   595  		header.Coinbase,
   596  		header.Root,
   597  		header.TxHash,
   598  		header.ReceiptHash,
   599  		header.Bloom,
   600  		header.Difficulty,
   601  		header.Number,
   602  		header.GasLimit,
   603  		header.GasUsed,
   604  		header.Time,
   605  		header.Extra,
   606  	})
   607  	hasher.Sum(hash[:0])
   608  	return hash
   609  }
   610  
   611  // Some weird constants to avoid constant memory allocs for them.
   612  var (
   613  	big8  = big.NewInt(8)
   614  	big32 = big.NewInt(32)
   615  )
   616  
   617  // AccumulateRewards credits the coinbase of the given block with the mining
   618  // reward. The total reward consists of the static block reward and rewards for
   619  // included uncles. The coinbase of each uncle block is also rewarded.
   620  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   621  	// Select the correct block reward based on chain progression
   622  	blockReward := FrontierBlockReward
   623  	if config.IsByzantium(header.Number) {
   624  		blockReward = ByzantiumBlockReward
   625  	}
   626  	if config.IsConstantinople(header.Number) {
   627  		blockReward = ConstantinopleBlockReward
   628  	}
   629  	// Accumulate the rewards for the miner and any included uncles
   630  	reward := new(big.Int).Set(blockReward)
   631  	r := new(big.Int)
   632  	for _, uncle := range uncles {
   633  		r.Add(uncle.Number, big8)
   634  		r.Sub(r, header.Number)
   635  		r.Mul(r, blockReward)
   636  		r.Div(r, big8)
   637  		state.AddBalance(uncle.Coinbase, r)
   638  
   639  		r.Div(blockReward, big32)
   640  		reward.Add(reward, r)
   641  	}
   642  	state.AddBalance(header.Coinbase, reward)
   643  }