github.com/ImPedro29/bor@v0.2.7/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  		ancestorHeader := chain.GetHeader(parent, number)
   207  		if ancestorHeader == nil {
   208  			break
   209  		}
   210  		ancestors[parent] = ancestorHeader
   211  		// If the ancestor doesn't have any uncles, we don't have to iterate them
   212  		if ancestorHeader.UncleHash != types.EmptyUncleHash {
   213  			// Need to add those uncles to the blacklist too
   214  			ancestor := chain.GetBlock(parent, number)
   215  			if ancestor == nil {
   216  				break
   217  			}
   218  			for _, uncle := range ancestor.Uncles() {
   219  				uncles.Add(uncle.Hash())
   220  			}
   221  		}
   222  		parent, number = ancestorHeader.ParentHash, number-1
   223  	}
   224  	ancestors[block.Hash()] = block.Header()
   225  	uncles.Add(block.Hash())
   226  
   227  	// Verify each of the uncles that it's recent, but not an ancestor
   228  	for _, uncle := range block.Uncles() {
   229  		// Make sure every uncle is rewarded only once
   230  		hash := uncle.Hash()
   231  		if uncles.Contains(hash) {
   232  			return errDuplicateUncle
   233  		}
   234  		uncles.Add(hash)
   235  
   236  		// Make sure the uncle has a valid ancestry
   237  		if ancestors[hash] != nil {
   238  			return errUncleIsAncestor
   239  		}
   240  		if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
   241  			return errDanglingUncle
   242  		}
   243  		if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true, time.Now().Unix()); err != nil {
   244  			return err
   245  		}
   246  	}
   247  	return nil
   248  }
   249  
   250  // verifyHeader checks whether a header conforms to the consensus rules of the
   251  // stock Ethereum ethash engine.
   252  // See YP section 4.3.4. "Block Header Validity"
   253  func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool, unixNow int64) error {
   254  	// Ensure that the header's extra-data section is of a reasonable size
   255  	if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
   256  		return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
   257  	}
   258  	// Verify the header's timestamp
   259  	if !uncle {
   260  		if header.Time > uint64(unixNow+allowedFutureBlockTimeSeconds) {
   261  			return consensus.ErrFutureBlock
   262  		}
   263  	}
   264  	if header.Time <= parent.Time {
   265  		return errOlderBlockTime
   266  	}
   267  	// Verify the block's difficulty based on its timestamp and parent's difficulty
   268  	expected := ethash.CalcDifficulty(chain, header.Time, parent)
   269  
   270  	if expected.Cmp(header.Difficulty) != 0 {
   271  		return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
   272  	}
   273  	// Verify that the gas limit is <= 2^63-1
   274  	cap := uint64(0x7fffffffffffffff)
   275  	if header.GasLimit > cap {
   276  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   277  	}
   278  	// Verify that the gasUsed is <= gasLimit
   279  	if header.GasUsed > header.GasLimit {
   280  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   281  	}
   282  
   283  	// Verify that the gas limit remains within allowed bounds
   284  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   285  	if diff < 0 {
   286  		diff *= -1
   287  	}
   288  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   289  
   290  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   291  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   292  	}
   293  	// Verify that the block number is parent's +1
   294  	if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
   295  		return consensus.ErrInvalidNumber
   296  	}
   297  	// Verify the engine specific seal securing the block
   298  	if seal {
   299  		if err := ethash.verifySeal(chain, header, false); err != nil {
   300  			return err
   301  		}
   302  	}
   303  	// If all checks passed, validate any special fields for hard forks
   304  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   305  		return err
   306  	}
   307  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   308  		return err
   309  	}
   310  	return nil
   311  }
   312  
   313  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   314  // the difficulty that a new block should have when created at time
   315  // given the parent block's time and difficulty.
   316  func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   317  	return CalcDifficulty(chain.Config(), time, parent)
   318  }
   319  
   320  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   321  // the difficulty that a new block should have when created at time
   322  // given the parent block's time and difficulty.
   323  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   324  	next := new(big.Int).Add(parent.Number, big1)
   325  	switch {
   326  	case config.IsCatalyst(next):
   327  		return big.NewInt(1)
   328  	case config.IsMuirGlacier(next):
   329  		return calcDifficultyEip2384(time, parent)
   330  	case config.IsConstantinople(next):
   331  		return calcDifficultyConstantinople(time, parent)
   332  	case config.IsByzantium(next):
   333  		return calcDifficultyByzantium(time, parent)
   334  	case config.IsHomestead(next):
   335  		return calcDifficultyHomestead(time, parent)
   336  	default:
   337  		return calcDifficultyFrontier(time, parent)
   338  	}
   339  }
   340  
   341  // Some weird constants to avoid constant memory allocs for them.
   342  var (
   343  	expDiffPeriod = big.NewInt(100000)
   344  	big1          = big.NewInt(1)
   345  	big2          = big.NewInt(2)
   346  	big9          = big.NewInt(9)
   347  	big10         = big.NewInt(10)
   348  	bigMinus99    = big.NewInt(-99)
   349  )
   350  
   351  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   352  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   353  // how uncles affect the calculation
   354  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   355  	// Note, the calculations below looks at the parent number, which is 1 below
   356  	// the block number. Thus we remove one from the delay given
   357  	bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   358  	return func(time uint64, parent *types.Header) *big.Int {
   359  		// https://github.com/ethereum/EIPs/issues/100.
   360  		// algorithm:
   361  		// diff = (parent_diff +
   362  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   363  		//        ) + 2^(periodCount - 2)
   364  
   365  		bigTime := new(big.Int).SetUint64(time)
   366  		bigParentTime := new(big.Int).SetUint64(parent.Time)
   367  
   368  		// holds intermediate values to make the algo easier to read & audit
   369  		x := new(big.Int)
   370  		y := new(big.Int)
   371  
   372  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   373  		x.Sub(bigTime, bigParentTime)
   374  		x.Div(x, big9)
   375  		if parent.UncleHash == types.EmptyUncleHash {
   376  			x.Sub(big1, x)
   377  		} else {
   378  			x.Sub(big2, x)
   379  		}
   380  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   381  		if x.Cmp(bigMinus99) < 0 {
   382  			x.Set(bigMinus99)
   383  		}
   384  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   385  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   386  		x.Mul(y, x)
   387  		x.Add(parent.Difficulty, x)
   388  
   389  		// minimum difficulty can ever be (before exponential factor)
   390  		if x.Cmp(params.MinimumDifficulty) < 0 {
   391  			x.Set(params.MinimumDifficulty)
   392  		}
   393  		// calculate a fake block number for the ice-age delay
   394  		// Specification: https://eips.ethereum.org/EIPS/eip-1234
   395  		fakeBlockNumber := new(big.Int)
   396  		if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   397  			fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   398  		}
   399  		// for the exponential factor
   400  		periodCount := fakeBlockNumber
   401  		periodCount.Div(periodCount, expDiffPeriod)
   402  
   403  		// the exponential factor, commonly referred to as "the bomb"
   404  		// diff = diff + 2^(periodCount - 2)
   405  		if periodCount.Cmp(big1) > 0 {
   406  			y.Sub(periodCount, big2)
   407  			y.Exp(big2, y, nil)
   408  			x.Add(x, y)
   409  		}
   410  		return x
   411  	}
   412  }
   413  
   414  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   415  // the difficulty that a new block should have when created at time given the
   416  // parent block's time and difficulty. The calculation uses the Homestead rules.
   417  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   418  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   419  	// algorithm:
   420  	// diff = (parent_diff +
   421  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   422  	//        ) + 2^(periodCount - 2)
   423  
   424  	bigTime := new(big.Int).SetUint64(time)
   425  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   426  
   427  	// holds intermediate values to make the algo easier to read & audit
   428  	x := new(big.Int)
   429  	y := new(big.Int)
   430  
   431  	// 1 - (block_timestamp - parent_timestamp) // 10
   432  	x.Sub(bigTime, bigParentTime)
   433  	x.Div(x, big10)
   434  	x.Sub(big1, x)
   435  
   436  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   437  	if x.Cmp(bigMinus99) < 0 {
   438  		x.Set(bigMinus99)
   439  	}
   440  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   441  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   442  	x.Mul(y, x)
   443  	x.Add(parent.Difficulty, x)
   444  
   445  	// minimum difficulty can ever be (before exponential factor)
   446  	if x.Cmp(params.MinimumDifficulty) < 0 {
   447  		x.Set(params.MinimumDifficulty)
   448  	}
   449  	// for the exponential factor
   450  	periodCount := new(big.Int).Add(parent.Number, big1)
   451  	periodCount.Div(periodCount, expDiffPeriod)
   452  
   453  	// the exponential factor, commonly referred to as "the bomb"
   454  	// diff = diff + 2^(periodCount - 2)
   455  	if periodCount.Cmp(big1) > 0 {
   456  		y.Sub(periodCount, big2)
   457  		y.Exp(big2, y, nil)
   458  		x.Add(x, y)
   459  	}
   460  	return x
   461  }
   462  
   463  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   464  // difficulty that a new block should have when created at time given the parent
   465  // block's time and difficulty. The calculation uses the Frontier rules.
   466  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   467  	diff := new(big.Int)
   468  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   469  	bigTime := new(big.Int)
   470  	bigParentTime := new(big.Int)
   471  
   472  	bigTime.SetUint64(time)
   473  	bigParentTime.SetUint64(parent.Time)
   474  
   475  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   476  		diff.Add(parent.Difficulty, adjust)
   477  	} else {
   478  		diff.Sub(parent.Difficulty, adjust)
   479  	}
   480  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   481  		diff.Set(params.MinimumDifficulty)
   482  	}
   483  
   484  	periodCount := new(big.Int).Add(parent.Number, big1)
   485  	periodCount.Div(periodCount, expDiffPeriod)
   486  	if periodCount.Cmp(big1) > 0 {
   487  		// diff = diff + 2^(periodCount - 2)
   488  		expDiff := periodCount.Sub(periodCount, big2)
   489  		expDiff.Exp(big2, expDiff, nil)
   490  		diff.Add(diff, expDiff)
   491  		diff = math.BigMax(diff, params.MinimumDifficulty)
   492  	}
   493  	return diff
   494  }
   495  
   496  // Exported for fuzzing
   497  var FrontierDifficultyCalulator = calcDifficultyFrontier
   498  var HomesteadDifficultyCalulator = calcDifficultyHomestead
   499  var DynamicDifficultyCalculator = makeDifficultyCalculator
   500  
   501  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   502  // either using the usual ethash cache for it, or alternatively using a full DAG
   503  // to make remote mining fast.
   504  func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
   505  	// If we're running a fake PoW, accept any seal as valid
   506  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   507  		time.Sleep(ethash.fakeDelay)
   508  		if ethash.fakeFail == header.Number.Uint64() {
   509  			return errInvalidPoW
   510  		}
   511  		return nil
   512  	}
   513  	// If we're running a shared PoW, delegate verification to it
   514  	if ethash.shared != nil {
   515  		return ethash.shared.verifySeal(chain, header, fulldag)
   516  	}
   517  	// Ensure that we have a valid difficulty for the block
   518  	if header.Difficulty.Sign() <= 0 {
   519  		return errInvalidDifficulty
   520  	}
   521  	// Recompute the digest and PoW values
   522  	number := header.Number.Uint64()
   523  
   524  	var (
   525  		digest []byte
   526  		result []byte
   527  	)
   528  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   529  	if fulldag {
   530  		dataset := ethash.dataset(number, true)
   531  		if dataset.generated() {
   532  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   533  
   534  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   535  			// until after the call to hashimotoFull so it's not unmapped while being used.
   536  			runtime.KeepAlive(dataset)
   537  		} else {
   538  			// Dataset not yet generated, don't hang, use a cache instead
   539  			fulldag = false
   540  		}
   541  	}
   542  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   543  	if !fulldag {
   544  		cache := ethash.cache(number)
   545  
   546  		size := datasetSize(number)
   547  		if ethash.config.PowMode == ModeTest {
   548  			size = 32 * 1024
   549  		}
   550  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   551  
   552  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   553  		// until after the call to hashimotoLight so it's not unmapped while being used.
   554  		runtime.KeepAlive(cache)
   555  	}
   556  	// Verify the calculated values against the ones provided in the header
   557  	if !bytes.Equal(header.MixDigest[:], digest) {
   558  		return errInvalidMixDigest
   559  	}
   560  	target := new(big.Int).Div(two256, header.Difficulty)
   561  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   562  		return errInvalidPoW
   563  	}
   564  	return nil
   565  }
   566  
   567  // Prepare implements consensus.Engine, initializing the difficulty field of a
   568  // header to conform to the ethash protocol. The changes are done inline.
   569  func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   570  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   571  	if parent == nil {
   572  		return consensus.ErrUnknownAncestor
   573  	}
   574  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
   575  	return nil
   576  }
   577  
   578  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   579  // setting the final state on the header
   580  func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
   581  	// Accumulate any block and uncle rewards and commit the final state root
   582  	accumulateRewards(chain.Config(), state, header, uncles)
   583  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   584  }
   585  
   586  // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
   587  // uncle rewards, setting the final state and assembling the block.
   588  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) {
   589  	// Finalize block
   590  	ethash.Finalize(chain, header, state, txs, uncles)
   591  
   592  	// Header seems complete, assemble into a block and return
   593  	return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), nil
   594  }
   595  
   596  // SealHash returns the hash of a block prior to it being sealed.
   597  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   598  	hasher := sha3.NewLegacyKeccak256()
   599  
   600  	rlp.Encode(hasher, []interface{}{
   601  		header.ParentHash,
   602  		header.UncleHash,
   603  		header.Coinbase,
   604  		header.Root,
   605  		header.TxHash,
   606  		header.ReceiptHash,
   607  		header.Bloom,
   608  		header.Difficulty,
   609  		header.Number,
   610  		header.GasLimit,
   611  		header.GasUsed,
   612  		header.Time,
   613  		header.Extra,
   614  	})
   615  	hasher.Sum(hash[:0])
   616  	return hash
   617  }
   618  
   619  // Some weird constants to avoid constant memory allocs for them.
   620  var (
   621  	big8  = big.NewInt(8)
   622  	big32 = big.NewInt(32)
   623  )
   624  
   625  // AccumulateRewards credits the coinbase of the given block with the mining
   626  // reward. The total reward consists of the static block reward and rewards for
   627  // included uncles. The coinbase of each uncle block is also rewarded.
   628  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   629  	// Skip block reward in catalyst mode
   630  	if config.IsCatalyst(header.Number) {
   631  		return
   632  	}
   633  	// Select the correct block reward based on chain progression
   634  	blockReward := FrontierBlockReward
   635  	if config.IsByzantium(header.Number) {
   636  		blockReward = ByzantiumBlockReward
   637  	}
   638  	if config.IsConstantinople(header.Number) {
   639  		blockReward = ConstantinopleBlockReward
   640  	}
   641  	// Accumulate the rewards for the miner and any included uncles
   642  	reward := new(big.Int).Set(blockReward)
   643  	r := new(big.Int)
   644  	for _, uncle := range uncles {
   645  		r.Add(uncle.Number, big8)
   646  		r.Sub(r, header.Number)
   647  		r.Mul(r, blockReward)
   648  		r.Div(r, big8)
   649  		state.AddBalance(uncle.Coinbase, r)
   650  
   651  		r.Div(blockReward, big32)
   652  		reward.Add(reward, r)
   653  	}
   654  	state.AddBalance(header.Coinbase, reward)
   655  }