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