github.com/specialpowerchain/go-specialiuma@v1.9.1/consensus/ethash/consensus.go (about)

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