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