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