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