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