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