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