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