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