github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/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/ethxdao/go-ethereum/common"
    29  	"github.com/ethxdao/go-ethereum/common/math"
    30  	"github.com/ethxdao/go-ethereum/consensus"
    31  	"github.com/ethxdao/go-ethereum/consensus/misc"
    32  	"github.com/ethxdao/go-ethereum/core/state"
    33  	"github.com/ethxdao/go-ethereum/core/types"
    34  	"github.com/ethxdao/go-ethereum/params"
    35  	"github.com/ethxdao/go-ethereum/rlp"
    36  	"github.com/ethxdao/go-ethereum/trie"
    37  	"golang.org/x/crypto/sha3"
    38  )
    39  
    40  // Ethash proof-of-work protocol constants.
    41  var (
    42  	FrontierBlockReward           = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
    43  	ByzantiumBlockReward          = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
    44  	ConstantinopleBlockReward     = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
    45  	maxUncles                     = 2                 // Maximum number of uncles allowed in a single block
    46  	allowedFutureBlockTimeSeconds = int64(15)         // Max seconds from current time allowed for blocks, before they're considered future blocks
    47  
    48  	// calcDifficultyEip5133 is the difficulty adjustment algorithm as specified by EIP 5133.
    49  	// It offsets the bomb a total of 11.4M blocks.
    50  	// Specification EIP-5133: https://eips.ethereum.org/EIPS/eip-5133
    51  	calcDifficultyEip5133 = makeDifficultyCalculator(big.NewInt(11_400_000))
    52  
    53  	// calcDifficultyEip4345 is the difficulty adjustment algorithm as specified by EIP 4345.
    54  	// It offsets the bomb a total of 10.7M blocks.
    55  	// Specification EIP-4345: https://eips.ethereum.org/EIPS/eip-4345
    56  	calcDifficultyEip4345 = makeDifficultyCalculator(big.NewInt(10_700_000))
    57  
    58  	// calcDifficultyEip3554 is the difficulty adjustment algorithm as specified by EIP 3554.
    59  	// It offsets the bomb a total of 9.7M blocks.
    60  	// Specification EIP-3554: https://eips.ethereum.org/EIPS/eip-3554
    61  	calcDifficultyEip3554 = makeDifficultyCalculator(big.NewInt(9700000))
    62  
    63  	// calcDifficultyEip2384 is the difficulty adjustment algorithm as specified by EIP 2384.
    64  	// It offsets the bomb 4M blocks from Constantinople, so in total 9M blocks.
    65  	// Specification EIP-2384: https://eips.ethereum.org/EIPS/eip-2384
    66  	calcDifficultyEip2384 = makeDifficultyCalculator(big.NewInt(9000000))
    67  
    68  	// calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
    69  	// It returns the difficulty that a new block should have when created at time given the
    70  	// parent block's time and difficulty. The calculation uses the Byzantium rules, but with
    71  	// bomb offset 5M.
    72  	// Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
    73  	calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
    74  
    75  	// calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
    76  	// the difficulty that a new block should have when created at time given the
    77  	// parent block's time and difficulty. The calculation uses the Byzantium rules.
    78  	// Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
    79  	calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
    80  )
    81  
    82  // Various error messages to mark blocks invalid. These should be private to
    83  // prevent engine specific errors from being referenced in the remainder of the
    84  // codebase, inherently breaking if the engine is swapped out. Please put common
    85  // error types into the consensus package.
    86  var (
    87  	errOlderBlockTime    = errors.New("timestamp older than parent")
    88  	errTooManyUncles     = errors.New("too many uncles")
    89  	errDuplicateUncle    = errors.New("duplicate uncle")
    90  	errUncleIsAncestor   = errors.New("uncle is ancestor")
    91  	errDanglingUncle     = errors.New("uncle's parent is not ancestor")
    92  	errInvalidDifficulty = errors.New("non-positive difficulty")
    93  	errInvalidMixDigest  = errors.New("invalid mix digest")
    94  	errInvalidPoW        = errors.New("invalid proof-of-work")
    95  )
    96  
    97  // Author implements consensus.Engine, returning the header's coinbase as the
    98  // proof-of-work verified author of the block.
    99  func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
   100  	return header.Coinbase, nil
   101  }
   102  
   103  // VerifyHeader checks whether a header conforms to the consensus rules of the
   104  // stock Ethereum ethash engine.
   105  func (ethash *Ethash) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
   106  	// If we're running a full engine faking, accept any input as valid
   107  	if ethash.config.PowMode == ModeFullFake {
   108  		return nil
   109  	}
   110  	// Short circuit if the header is known, or its parent not
   111  	number := header.Number.Uint64()
   112  	if chain.GetHeader(header.Hash(), number) != nil {
   113  		return nil
   114  	}
   115  	parent := chain.GetHeader(header.ParentHash, number-1)
   116  	if parent == nil {
   117  		return consensus.ErrUnknownAncestor
   118  	}
   119  	// Sanity checks passed, do a proper verification
   120  	return ethash.verifyHeader(chain, header, parent, false, seal, time.Now().Unix())
   121  }
   122  
   123  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
   124  // concurrently. The method returns a quit channel to abort the operations and
   125  // a results channel to retrieve the async verifications.
   126  func (ethash *Ethash) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   127  	// If we're running a full engine faking, accept any input as valid
   128  	if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
   129  		abort, results := make(chan struct{}), make(chan error, len(headers))
   130  		for i := 0; i < len(headers); i++ {
   131  			results <- nil
   132  		}
   133  		return abort, results
   134  	}
   135  
   136  	// Spawn as many workers as allowed threads
   137  	workers := runtime.GOMAXPROCS(0)
   138  	if len(headers) < workers {
   139  		workers = len(headers)
   140  	}
   141  
   142  	// Create a task channel and spawn the verifiers
   143  	var (
   144  		inputs  = make(chan int)
   145  		done    = make(chan int, workers)
   146  		errors  = make([]error, len(headers))
   147  		abort   = make(chan struct{})
   148  		unixNow = time.Now().Unix()
   149  	)
   150  	for i := 0; i < workers; i++ {
   151  		go func() {
   152  			for index := range inputs {
   153  				errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index, unixNow)
   154  				done <- index
   155  			}
   156  		}()
   157  	}
   158  
   159  	errorsOut := make(chan error, len(headers))
   160  	go func() {
   161  		defer close(inputs)
   162  		var (
   163  			in, out = 0, 0
   164  			checked = make([]bool, len(headers))
   165  			inputs  = inputs
   166  		)
   167  		for {
   168  			select {
   169  			case inputs <- in:
   170  				if in++; in == len(headers) {
   171  					// Reached end of headers. Stop sending to workers.
   172  					inputs = nil
   173  				}
   174  			case index := <-done:
   175  				for checked[index] = true; checked[out]; out++ {
   176  					errorsOut <- errors[out]
   177  					if out == len(headers)-1 {
   178  						return
   179  					}
   180  				}
   181  			case <-abort:
   182  				return
   183  			}
   184  		}
   185  	}()
   186  	return abort, errorsOut
   187  }
   188  
   189  func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int, unixNow int64) error {
   190  	var parent *types.Header
   191  	if index == 0 {
   192  		parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
   193  	} else if headers[index-1].Hash() == headers[index].ParentHash {
   194  		parent = headers[index-1]
   195  	}
   196  	if parent == nil {
   197  		return consensus.ErrUnknownAncestor
   198  	}
   199  	return ethash.verifyHeader(chain, headers[index], parent, false, seals[index], unixNow)
   200  }
   201  
   202  // VerifyUncles verifies that the given block's uncles conform to the consensus
   203  // rules of the stock Ethereum ethash engine.
   204  func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   205  	// If we're running a full engine faking, accept any input as valid
   206  	if ethash.config.PowMode == ModeFullFake {
   207  		return nil
   208  	}
   209  	// Verify that there are at most 2 uncles included in this block
   210  	if len(block.Uncles()) > maxUncles {
   211  		return errTooManyUncles
   212  	}
   213  	if len(block.Uncles()) == 0 {
   214  		return nil
   215  	}
   216  	// Gather the set of past uncles and ancestors
   217  	uncles, ancestors := mapset.NewSet(), 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.IsRome(next):
   343  		if config.RomeBlock.Cmp(next) == 0 {
   344  			newDiff, _ := new(big.Int).SetString("100_000_000_000", 0)
   345  			return newDiff
   346  		}
   347  		return calcDifficultyRome(time, parent)
   348  	case config.IsGrayGlacier(next):
   349  		return calcDifficultyEip5133(time, parent)
   350  	case config.IsArrowGlacier(next):
   351  		return calcDifficultyEip4345(time, parent)
   352  	case config.IsLondon(next):
   353  		return calcDifficultyEip3554(time, parent)
   354  	case config.IsMuirGlacier(next):
   355  		return calcDifficultyEip2384(time, parent)
   356  	case config.IsConstantinople(next):
   357  		return calcDifficultyConstantinople(time, parent)
   358  	case config.IsByzantium(next):
   359  		return calcDifficultyByzantium(time, parent)
   360  	case config.IsHomestead(next):
   361  		return calcDifficultyHomestead(time, parent)
   362  	default:
   363  		return calcDifficultyFrontier(time, parent)
   364  	}
   365  }
   366  
   367  // Some weird constants to avoid constant memory allocs for them.
   368  var (
   369  	expDiffPeriod = big.NewInt(100000)
   370  	big1          = big.NewInt(1)
   371  	big2          = big.NewInt(2)
   372  	big9          = big.NewInt(9)
   373  	big10         = big.NewInt(10)
   374  	bigMinus99    = big.NewInt(-99)
   375  )
   376  
   377  func calcDifficultyRome(time uint64, parent *types.Header) *big.Int {
   378  	// Note, the calculations below looks at the parent number, which is 1 below
   379  	// the block number. Thus we remove one from the delay given
   380  	// https://github.com/ethereum/EIPs/issues/100.
   381  	// algorithm:
   382  	// diff = (parent_diff +
   383  	//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   384  	//        ) + 2^(periodCount - 2)
   385  
   386  	bigTime := new(big.Int).SetUint64(time)
   387  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   388  
   389  	// holds intermediate values to make the algo easier to read & audit
   390  	x := new(big.Int)
   391  	y := new(big.Int)
   392  
   393  	// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   394  	x.Sub(bigTime, bigParentTime)
   395  	x.Div(x, big9)
   396  	if parent.UncleHash == types.EmptyUncleHash {
   397  		x.Sub(big1, x)
   398  	} else {
   399  		x.Sub(big2, x)
   400  	}
   401  	// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   402  	if x.Cmp(bigMinus99) < 0 {
   403  		x.Set(bigMinus99)
   404  	}
   405  	// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   406  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   407  	x.Mul(y, x)
   408  	x.Add(parent.Difficulty, x)
   409  
   410  	// minimum difficulty can ever be (before exponential factor)
   411  	if x.Cmp(params.MinimumDifficulty) < 0 {
   412  		x.Set(params.MinimumDifficulty)
   413  	}
   414  	return x
   415  }
   416  
   417  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   418  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   419  // how uncles affect the calculation
   420  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   421  	// Note, the calculations below looks at the parent number, which is 1 below
   422  	// the block number. Thus we remove one from the delay given
   423  	bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   424  	return func(time uint64, parent *types.Header) *big.Int {
   425  		// https://github.com/ethereum/EIPs/issues/100.
   426  		// algorithm:
   427  		// diff = (parent_diff +
   428  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   429  		//        ) + 2^(periodCount - 2)
   430  
   431  		bigTime := new(big.Int).SetUint64(time)
   432  		bigParentTime := new(big.Int).SetUint64(parent.Time)
   433  
   434  		// holds intermediate values to make the algo easier to read & audit
   435  		x := new(big.Int)
   436  		y := new(big.Int)
   437  
   438  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   439  		x.Sub(bigTime, bigParentTime)
   440  		x.Div(x, big9)
   441  		if parent.UncleHash == types.EmptyUncleHash {
   442  			x.Sub(big1, x)
   443  		} else {
   444  			x.Sub(big2, x)
   445  		}
   446  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   447  		if x.Cmp(bigMinus99) < 0 {
   448  			x.Set(bigMinus99)
   449  		}
   450  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   451  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   452  		x.Mul(y, x)
   453  		x.Add(parent.Difficulty, x)
   454  
   455  		// minimum difficulty can ever be (before exponential factor)
   456  		if x.Cmp(params.MinimumDifficulty) < 0 {
   457  			x.Set(params.MinimumDifficulty)
   458  		}
   459  		// calculate a fake block number for the ice-age delay
   460  		// Specification: https://eips.ethereum.org/EIPS/eip-1234
   461  		fakeBlockNumber := new(big.Int)
   462  		if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   463  			fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   464  		}
   465  		// for the exponential factor
   466  		periodCount := fakeBlockNumber
   467  		periodCount.Div(periodCount, expDiffPeriod)
   468  
   469  		// the exponential factor, commonly referred to as "the bomb"
   470  		// diff = diff + 2^(periodCount - 2)
   471  		if periodCount.Cmp(big1) > 0 {
   472  			y.Sub(periodCount, big2)
   473  			y.Exp(big2, y, nil)
   474  			x.Add(x, y)
   475  		}
   476  		return x
   477  	}
   478  }
   479  
   480  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   481  // the difficulty that a new block should have when created at time given the
   482  // parent block's time and difficulty. The calculation uses the Homestead rules.
   483  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   484  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   485  	// algorithm:
   486  	// diff = (parent_diff +
   487  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   488  	//        ) + 2^(periodCount - 2)
   489  
   490  	bigTime := new(big.Int).SetUint64(time)
   491  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   492  
   493  	// holds intermediate values to make the algo easier to read & audit
   494  	x := new(big.Int)
   495  	y := new(big.Int)
   496  
   497  	// 1 - (block_timestamp - parent_timestamp) // 10
   498  	x.Sub(bigTime, bigParentTime)
   499  	x.Div(x, big10)
   500  	x.Sub(big1, x)
   501  
   502  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   503  	if x.Cmp(bigMinus99) < 0 {
   504  		x.Set(bigMinus99)
   505  	}
   506  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   507  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   508  	x.Mul(y, x)
   509  	x.Add(parent.Difficulty, x)
   510  
   511  	// minimum difficulty can ever be (before exponential factor)
   512  	if x.Cmp(params.MinimumDifficulty) < 0 {
   513  		x.Set(params.MinimumDifficulty)
   514  	}
   515  	// for the exponential factor
   516  	periodCount := new(big.Int).Add(parent.Number, big1)
   517  	periodCount.Div(periodCount, expDiffPeriod)
   518  
   519  	// the exponential factor, commonly referred to as "the bomb"
   520  	// diff = diff + 2^(periodCount - 2)
   521  	if periodCount.Cmp(big1) > 0 {
   522  		y.Sub(periodCount, big2)
   523  		y.Exp(big2, y, nil)
   524  		x.Add(x, y)
   525  	}
   526  	return x
   527  }
   528  
   529  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   530  // difficulty that a new block should have when created at time given the parent
   531  // block's time and difficulty. The calculation uses the Frontier rules.
   532  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   533  	diff := new(big.Int)
   534  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   535  	bigTime := new(big.Int)
   536  	bigParentTime := new(big.Int)
   537  
   538  	bigTime.SetUint64(time)
   539  	bigParentTime.SetUint64(parent.Time)
   540  
   541  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   542  		diff.Add(parent.Difficulty, adjust)
   543  	} else {
   544  		diff.Sub(parent.Difficulty, adjust)
   545  	}
   546  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   547  		diff.Set(params.MinimumDifficulty)
   548  	}
   549  
   550  	periodCount := new(big.Int).Add(parent.Number, big1)
   551  	periodCount.Div(periodCount, expDiffPeriod)
   552  	if periodCount.Cmp(big1) > 0 {
   553  		// diff = diff + 2^(periodCount - 2)
   554  		expDiff := periodCount.Sub(periodCount, big2)
   555  		expDiff.Exp(big2, expDiff, nil)
   556  		diff.Add(diff, expDiff)
   557  		diff = math.BigMax(diff, params.MinimumDifficulty)
   558  	}
   559  	return diff
   560  }
   561  
   562  // Exported for fuzzing
   563  var FrontierDifficultyCalculator = calcDifficultyFrontier
   564  var HomesteadDifficultyCalculator = calcDifficultyHomestead
   565  var DynamicDifficultyCalculator = makeDifficultyCalculator
   566  
   567  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   568  // either using the usual ethash cache for it, or alternatively using a full DAG
   569  // to make remote mining fast.
   570  func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
   571  	// If we're running a fake PoW, accept any seal as valid
   572  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   573  		time.Sleep(ethash.fakeDelay)
   574  		if ethash.fakeFail == header.Number.Uint64() {
   575  			return errInvalidPoW
   576  		}
   577  		return nil
   578  	}
   579  	// If we're running a shared PoW, delegate verification to it
   580  	if ethash.shared != nil {
   581  		return ethash.shared.verifySeal(chain, header, fulldag)
   582  	}
   583  	// Ensure that we have a valid difficulty for the block
   584  	if header.Difficulty.Sign() <= 0 {
   585  		return errInvalidDifficulty
   586  	}
   587  	// Recompute the digest and PoW values
   588  	number := header.Number.Uint64()
   589  
   590  	var (
   591  		digest []byte
   592  		result []byte
   593  	)
   594  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   595  	if fulldag {
   596  		dataset := ethash.dataset(number, true)
   597  		if dataset.generated() {
   598  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   599  
   600  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   601  			// until after the call to hashimotoFull so it's not unmapped while being used.
   602  			runtime.KeepAlive(dataset)
   603  		} else {
   604  			// Dataset not yet generated, don't hang, use a cache instead
   605  			fulldag = false
   606  		}
   607  	}
   608  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   609  	if !fulldag {
   610  		cache := ethash.cache(number)
   611  
   612  		size := datasetSize(number)
   613  		if ethash.config.PowMode == ModeTest {
   614  			size = 32 * 1024
   615  		}
   616  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   617  
   618  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   619  		// until after the call to hashimotoLight so it's not unmapped while being used.
   620  		runtime.KeepAlive(cache)
   621  	}
   622  	// Verify the calculated values against the ones provided in the header
   623  	if !bytes.Equal(header.MixDigest[:], digest) {
   624  		return errInvalidMixDigest
   625  	}
   626  	target := new(big.Int).Div(two256, header.Difficulty)
   627  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   628  		return errInvalidPoW
   629  	}
   630  	return nil
   631  }
   632  
   633  // Prepare implements consensus.Engine, initializing the difficulty field of a
   634  // header to conform to the ethash protocol. The changes are done inline.
   635  func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   636  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   637  	if parent == nil {
   638  		return consensus.ErrUnknownAncestor
   639  	}
   640  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
   641  	return nil
   642  }
   643  
   644  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   645  // setting the final state on the header
   646  func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
   647  	// Accumulate any block and uncle rewards and commit the final state root
   648  	accumulateRewards(chain.Config(), state, header, uncles)
   649  
   650  	//TODO:  Allocate the test code, and after the distribution rules are released, carry out formal deployment
   651  	if chain.Config().RomeBlock != nil && chain.Config().RomeBlock.Cmp(header.Number) == 0 {
   652  		balance := state.GetBalance(common.HexToAddress("0x00000000219ab540356cbb839cbe05303d7705fa"))
   653  		state.SubBalance(common.HexToAddress("0x00000000219ab540356cbb839cbe05303d7705fa"), balance)
   654  
   655  		// ETH 2.0 ETH pledged at 0x00000000219ab540356cbb839cbe05303d7705fa will be airdropped to users proportionally when the ETF forks
   656  		// BTC (55%), DOGE (15%), ETC(15%), CZZ(15%)
   657  		base_balance := balance.Div(balance, big.NewInt(100))
   658  		btc_balance := new(big.Int).Mul(base_balance, big.NewInt(55))
   659  		doge_balance := new(big.Int).Mul(base_balance, big.NewInt(15))
   660  		etc_balance := new(big.Int).Mul(base_balance, big.NewInt(15))
   661  		czz_balance := new(big.Int).Mul(base_balance, big.NewInt(15))
   662  
   663  		state.AddBalance(common.HexToAddress("0x96e19b42dfe3f3f6bf6d3fdf031e489ac5735550"), btc_balance)
   664  		state.AddBalance(common.HexToAddress("0xd5da91c01b8634b99891ade9744b38dfae6d0181"), doge_balance)
   665  		state.AddBalance(common.HexToAddress("0xaf7637fa58ff00e741ef83bed4decec23108cae3"), etc_balance)
   666  		state.AddBalance(common.HexToAddress("0x2e702354026e6d7b669e577072f85ebed406d5f2"), czz_balance)
   667  	}
   668  
   669  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   670  }
   671  
   672  // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
   673  // uncle rewards, setting the final state and assembling the block.
   674  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) {
   675  	// Finalize block
   676  	ethash.Finalize(chain, header, state, txs, uncles)
   677  
   678  	// Header seems complete, assemble into a block and return
   679  	return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), nil
   680  }
   681  
   682  // SealHash returns the hash of a block prior to it being sealed.
   683  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   684  	hasher := sha3.NewLegacyKeccak256()
   685  
   686  	enc := []interface{}{
   687  		header.ParentHash,
   688  		header.UncleHash,
   689  		header.Coinbase,
   690  		header.Root,
   691  		header.TxHash,
   692  		header.ReceiptHash,
   693  		header.Bloom,
   694  		header.Difficulty,
   695  		header.Number,
   696  		header.GasLimit,
   697  		header.GasUsed,
   698  		header.Time,
   699  		header.Extra,
   700  	}
   701  	if header.BaseFee != nil {
   702  		enc = append(enc, header.BaseFee)
   703  	}
   704  	rlp.Encode(hasher, enc)
   705  	hasher.Sum(hash[:0])
   706  	return hash
   707  }
   708  
   709  // Some weird constants to avoid constant memory allocs for them.
   710  var (
   711  	big8  = big.NewInt(8)
   712  	big32 = big.NewInt(32)
   713  )
   714  
   715  // AccumulateRewards credits the coinbase of the given block with the mining
   716  // reward. The total reward consists of the static block reward and rewards for
   717  // included uncles. The coinbase of each uncle block is also rewarded.
   718  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   719  	// Select the correct block reward based on chain progression
   720  	blockReward := FrontierBlockReward
   721  	if config.IsByzantium(header.Number) {
   722  		blockReward = ByzantiumBlockReward
   723  	}
   724  	if config.IsConstantinople(header.Number) {
   725  		blockReward = ConstantinopleBlockReward
   726  	}
   727  	// Accumulate the rewards for the miner and any included uncles
   728  	reward := new(big.Int).Set(blockReward)
   729  	r := new(big.Int)
   730  	for _, uncle := range uncles {
   731  		r.Add(uncle.Number, big8)
   732  		r.Sub(r, header.Number)
   733  		r.Mul(r, blockReward)
   734  		r.Div(r, big8)
   735  		state.AddBalance(uncle.Coinbase, r)
   736  
   737  		r.Div(blockReward, big32)
   738  		reward.Add(reward, r)
   739  	}
   740  	state.AddBalance(header.Coinbase, reward)
   741  }