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