github.com/umbrellaKitties/go-ethereum@v0.0.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  	"bytes"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"runtime"
    25  	"time"
    26  
    27  	mapset "github.com/deckarep/golang-set/v2"
    28  	"github.com/umbrellaKitties/go-ethereum/common"
    29  	"github.com/umbrellaKitties/go-ethereum/common/math"
    30  	"github.com/umbrellaKitties/go-ethereum/consensus"
    31  	"github.com/umbrellaKitties/go-ethereum/consensus/misc"
    32  	"github.com/umbrellaKitties/go-ethereum/core/state"
    33  	"github.com/umbrellaKitties/go-ethereum/core/types"
    34  	"github.com/umbrellaKitties/go-ethereum/params"
    35  	"github.com/umbrellaKitties/go-ethereum/rlp"
    36  	"github.com/umbrellaKitties/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  	// Verify the engine specific seal securing the block
   314  	if seal {
   315  		if err := ethash.verifySeal(chain, header, false); err != nil {
   316  			return err
   317  		}
   318  	}
   319  	// If all checks passed, validate any special fields for hard forks
   320  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   321  		return err
   322  	}
   323  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   324  		return err
   325  	}
   326  	return nil
   327  }
   328  
   329  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   330  // the difficulty that a new block should have when created at time
   331  // given the parent block's time and difficulty.
   332  func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   333  	return CalcDifficulty(chain.Config(), time, parent)
   334  }
   335  
   336  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   337  // the difficulty that a new block should have when created at time
   338  // given the parent block's time and difficulty.
   339  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   340  	next := new(big.Int).Add(parent.Number, big1)
   341  	switch {
   342  	case config.IsGrayGlacier(next):
   343  		return calcDifficultyEip5133(time, parent)
   344  	case config.IsArrowGlacier(next):
   345  		return calcDifficultyEip4345(time, parent)
   346  	case config.IsLondon(next):
   347  		return calcDifficultyEip3554(time, parent)
   348  	case config.IsMuirGlacier(next):
   349  		return calcDifficultyEip2384(time, parent)
   350  	case config.IsConstantinople(next):
   351  		return calcDifficultyConstantinople(time, parent)
   352  	case config.IsByzantium(next):
   353  		return calcDifficultyByzantium(time, parent)
   354  	case config.IsHomestead(next):
   355  		return calcDifficultyHomestead(time, parent)
   356  	default:
   357  		return calcDifficultyFrontier(time, parent)
   358  	}
   359  }
   360  
   361  // Some weird constants to avoid constant memory allocs for them.
   362  var (
   363  	expDiffPeriod = big.NewInt(100000)
   364  	big1          = big.NewInt(1)
   365  	big2          = big.NewInt(2)
   366  	big9          = big.NewInt(9)
   367  	big10         = big.NewInt(10)
   368  	bigMinus99    = big.NewInt(-99)
   369  )
   370  
   371  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   372  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   373  // how uncles affect the calculation
   374  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   375  	// Note, the calculations below looks at the parent number, which is 1 below
   376  	// the block number. Thus we remove one from the delay given
   377  	bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   378  	return func(time uint64, parent *types.Header) *big.Int {
   379  		// https://github.com/ethereum/EIPs/issues/100.
   380  		// algorithm:
   381  		// diff = (parent_diff +
   382  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   383  		//        ) + 2^(periodCount - 2)
   384  
   385  		bigTime := new(big.Int).SetUint64(time)
   386  		bigParentTime := new(big.Int).SetUint64(parent.Time)
   387  
   388  		// holds intermediate values to make the algo easier to read & audit
   389  		x := new(big.Int)
   390  		y := new(big.Int)
   391  
   392  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   393  		x.Sub(bigTime, bigParentTime)
   394  		x.Div(x, big9)
   395  		if parent.UncleHash == types.EmptyUncleHash {
   396  			x.Sub(big1, x)
   397  		} else {
   398  			x.Sub(big2, x)
   399  		}
   400  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   401  		if x.Cmp(bigMinus99) < 0 {
   402  			x.Set(bigMinus99)
   403  		}
   404  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   405  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   406  		x.Mul(y, x)
   407  		x.Add(parent.Difficulty, x)
   408  
   409  		// minimum difficulty can ever be (before exponential factor)
   410  		if x.Cmp(params.MinimumDifficulty) < 0 {
   411  			x.Set(params.MinimumDifficulty)
   412  		}
   413  		// calculate a fake block number for the ice-age delay
   414  		// Specification: https://eips.ethereum.org/EIPS/eip-1234
   415  		fakeBlockNumber := new(big.Int)
   416  		if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   417  			fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   418  		}
   419  		// for the exponential factor
   420  		periodCount := fakeBlockNumber
   421  		periodCount.Div(periodCount, expDiffPeriod)
   422  
   423  		// the exponential factor, commonly referred to as "the bomb"
   424  		// diff = diff + 2^(periodCount - 2)
   425  		if periodCount.Cmp(big1) > 0 {
   426  			y.Sub(periodCount, big2)
   427  			y.Exp(big2, y, nil)
   428  			x.Add(x, y)
   429  		}
   430  		return x
   431  	}
   432  }
   433  
   434  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   435  // the difficulty that a new block should have when created at time given the
   436  // parent block's time and difficulty. The calculation uses the Homestead rules.
   437  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   438  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   439  	// algorithm:
   440  	// diff = (parent_diff +
   441  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   442  	//        ) + 2^(periodCount - 2)
   443  
   444  	bigTime := new(big.Int).SetUint64(time)
   445  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   446  
   447  	// holds intermediate values to make the algo easier to read & audit
   448  	x := new(big.Int)
   449  	y := new(big.Int)
   450  
   451  	// 1 - (block_timestamp - parent_timestamp) // 10
   452  	x.Sub(bigTime, bigParentTime)
   453  	x.Div(x, big10)
   454  	x.Sub(big1, x)
   455  
   456  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   457  	if x.Cmp(bigMinus99) < 0 {
   458  		x.Set(bigMinus99)
   459  	}
   460  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   461  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   462  	x.Mul(y, x)
   463  	x.Add(parent.Difficulty, x)
   464  
   465  	// minimum difficulty can ever be (before exponential factor)
   466  	if x.Cmp(params.MinimumDifficulty) < 0 {
   467  		x.Set(params.MinimumDifficulty)
   468  	}
   469  	// for the exponential factor
   470  	periodCount := new(big.Int).Add(parent.Number, big1)
   471  	periodCount.Div(periodCount, expDiffPeriod)
   472  
   473  	// the exponential factor, commonly referred to as "the bomb"
   474  	// diff = diff + 2^(periodCount - 2)
   475  	if periodCount.Cmp(big1) > 0 {
   476  		y.Sub(periodCount, big2)
   477  		y.Exp(big2, y, nil)
   478  		x.Add(x, y)
   479  	}
   480  	return x
   481  }
   482  
   483  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   484  // difficulty that a new block should have when created at time given the parent
   485  // block's time and difficulty. The calculation uses the Frontier rules.
   486  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   487  	diff := new(big.Int)
   488  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   489  	bigTime := new(big.Int)
   490  	bigParentTime := new(big.Int)
   491  
   492  	bigTime.SetUint64(time)
   493  	bigParentTime.SetUint64(parent.Time)
   494  
   495  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   496  		diff.Add(parent.Difficulty, adjust)
   497  	} else {
   498  		diff.Sub(parent.Difficulty, adjust)
   499  	}
   500  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   501  		diff.Set(params.MinimumDifficulty)
   502  	}
   503  
   504  	periodCount := new(big.Int).Add(parent.Number, big1)
   505  	periodCount.Div(periodCount, expDiffPeriod)
   506  	if periodCount.Cmp(big1) > 0 {
   507  		// diff = diff + 2^(periodCount - 2)
   508  		expDiff := periodCount.Sub(periodCount, big2)
   509  		expDiff.Exp(big2, expDiff, nil)
   510  		diff.Add(diff, expDiff)
   511  		diff = math.BigMax(diff, params.MinimumDifficulty)
   512  	}
   513  	return diff
   514  }
   515  
   516  // Exported for fuzzing
   517  var FrontierDifficultyCalculator = calcDifficultyFrontier
   518  var HomesteadDifficultyCalculator = calcDifficultyHomestead
   519  var DynamicDifficultyCalculator = makeDifficultyCalculator
   520  
   521  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   522  // either using the usual ethash cache for it, or alternatively using a full DAG
   523  // to make remote mining fast.
   524  func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
   525  	// If we're running a fake PoW, accept any seal as valid
   526  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   527  		time.Sleep(ethash.fakeDelay)
   528  		if ethash.fakeFail == header.Number.Uint64() {
   529  			return errInvalidPoW
   530  		}
   531  		return nil
   532  	}
   533  	// If we're running a shared PoW, delegate verification to it
   534  	if ethash.shared != nil {
   535  		return ethash.shared.verifySeal(chain, header, fulldag)
   536  	}
   537  	// Ensure that we have a valid difficulty for the block
   538  	if header.Difficulty.Sign() <= 0 {
   539  		return errInvalidDifficulty
   540  	}
   541  	// Recompute the digest and PoW values
   542  	number := header.Number.Uint64()
   543  
   544  	var (
   545  		digest []byte
   546  		result []byte
   547  	)
   548  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   549  	if fulldag {
   550  		dataset := ethash.dataset(number, true)
   551  		if dataset.generated() {
   552  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   553  
   554  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   555  			// until after the call to hashimotoFull so it's not unmapped while being used.
   556  			runtime.KeepAlive(dataset)
   557  		} else {
   558  			// Dataset not yet generated, don't hang, use a cache instead
   559  			fulldag = false
   560  		}
   561  	}
   562  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   563  	if !fulldag {
   564  		cache := ethash.cache(number)
   565  
   566  		size := datasetSize(number)
   567  		if ethash.config.PowMode == ModeTest {
   568  			size = 32 * 1024
   569  		}
   570  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   571  
   572  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   573  		// until after the call to hashimotoLight so it's not unmapped while being used.
   574  		runtime.KeepAlive(cache)
   575  	}
   576  	// Verify the calculated values against the ones provided in the header
   577  	if !bytes.Equal(header.MixDigest[:], digest) {
   578  		return errInvalidMixDigest
   579  	}
   580  	target := new(big.Int).Div(two256, header.Difficulty)
   581  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   582  		return errInvalidPoW
   583  	}
   584  	return nil
   585  }
   586  
   587  // Prepare implements consensus.Engine, initializing the difficulty field of a
   588  // header to conform to the ethash protocol. The changes are done inline.
   589  func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   590  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   591  	if parent == nil {
   592  		return consensus.ErrUnknownAncestor
   593  	}
   594  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
   595  	return nil
   596  }
   597  
   598  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   599  // setting the final state on the header
   600  func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
   601  	// Accumulate any block and uncle rewards and commit the final state root
   602  	accumulateRewards(chain.Config(), state, header, uncles)
   603  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   604  }
   605  
   606  // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
   607  // uncle rewards, setting the final state and assembling the block.
   608  func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
   609  	// Finalize block
   610  	ethash.Finalize(chain, header, state, txs, uncles)
   611  
   612  	// Header seems complete, assemble into a block and return
   613  	return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), nil
   614  }
   615  
   616  // SealHash returns the hash of a block prior to it being sealed.
   617  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   618  	hasher := sha3.NewLegacyKeccak256()
   619  
   620  	enc := []interface{}{
   621  		header.ParentHash,
   622  		header.UncleHash,
   623  		header.Coinbase,
   624  		header.Root,
   625  		header.TxHash,
   626  		header.ReceiptHash,
   627  		header.Bloom,
   628  		header.Difficulty,
   629  		header.Number,
   630  		header.GasLimit,
   631  		header.GasUsed,
   632  		header.Time,
   633  		header.Extra,
   634  	}
   635  	if header.BaseFee != nil {
   636  		enc = append(enc, header.BaseFee)
   637  	}
   638  	rlp.Encode(hasher, enc)
   639  	hasher.Sum(hash[:0])
   640  	return hash
   641  }
   642  
   643  // Some weird constants to avoid constant memory allocs for them.
   644  var (
   645  	big8  = big.NewInt(8)
   646  	big32 = big.NewInt(32)
   647  )
   648  
   649  // AccumulateRewards credits the coinbase of the given block with the mining
   650  // reward. The total reward consists of the static block reward and rewards for
   651  // included uncles. The coinbase of each uncle block is also rewarded.
   652  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   653  	// Select the correct block reward based on chain progression
   654  	blockReward := FrontierBlockReward
   655  	if config.IsByzantium(header.Number) {
   656  		blockReward = ByzantiumBlockReward
   657  	}
   658  	if config.IsConstantinople(header.Number) {
   659  		blockReward = ConstantinopleBlockReward
   660  	}
   661  	// Accumulate the rewards for the miner and any included uncles
   662  	reward := new(big.Int).Set(blockReward)
   663  	r := new(big.Int)
   664  	for _, uncle := range uncles {
   665  		r.Add(uncle.Number, big8)
   666  		r.Sub(r, header.Number)
   667  		r.Mul(r, blockReward)
   668  		r.Div(r, big8)
   669  		state.AddBalance(uncle.Coinbase, r)
   670  
   671  		r.Div(blockReward, big32)
   672  		reward.Add(reward, r)
   673  	}
   674  	state.AddBalance(header.Coinbase, reward)
   675  }