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