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