github.com/aswedchain/aswed@v1.0.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/aswedchain/aswed/common"
    29  	"github.com/aswedchain/aswed/common/math"
    30  	"github.com/aswedchain/aswed/consensus"
    31  	"github.com/aswedchain/aswed/consensus/misc"
    32  	"github.com/aswedchain/aswed/core/state"
    33  	"github.com/aswedchain/aswed/core/types"
    34  	"github.com/aswedchain/aswed/params"
    35  	"github.com/aswedchain/aswed/rlp"
    36  	"github.com/aswedchain/aswed/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  	// Ensure that the header's extra-data section is of a reasonable size
   249  	if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
   250  		return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
   251  	}
   252  	// Verify the header's timestamp
   253  	if !uncle {
   254  		if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
   255  			return consensus.ErrFutureBlock
   256  		}
   257  	}
   258  	if header.Time <= parent.Time {
   259  		return errOlderBlockTime
   260  	}
   261  	// Verify the block's difficulty based on its timestamp and parent's difficulty
   262  	expected := ethash.CalcDifficulty(chain, header.Time, parent)
   263  
   264  	if expected.Cmp(header.Difficulty) != 0 {
   265  		return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
   266  	}
   267  	// Verify that the gas limit is <= 2^63-1
   268  	cap := uint64(0x7fffffffffffffff)
   269  	if header.GasLimit > cap {
   270  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   271  	}
   272  	// Verify that the gasUsed is <= gasLimit
   273  	if header.GasUsed > header.GasLimit {
   274  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   275  	}
   276  
   277  	// Verify that the gas limit remains within allowed bounds
   278  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   279  	if diff < 0 {
   280  		diff *= -1
   281  	}
   282  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   283  
   284  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   285  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   286  	}
   287  	// Verify that the block number is parent's +1
   288  	if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
   289  		return consensus.ErrInvalidNumber
   290  	}
   291  	// Verify the engine specific seal securing the block
   292  	if seal {
   293  		if err := ethash.VerifySeal(chain, header); err != nil {
   294  			return err
   295  		}
   296  	}
   297  	// If all checks passed, validate any special fields for hard forks
   298  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   299  		return err
   300  	}
   301  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   302  		return err
   303  	}
   304  	return nil
   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 (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
   311  	return CalcDifficulty(chain.Config(), time, parent)
   312  }
   313  
   314  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   315  // the difficulty that a new block should have when created at time
   316  // given the parent block's time and difficulty.
   317  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   318  	next := new(big.Int).Add(parent.Number, big1)
   319  	switch {
   320  	case config.IsMuirGlacier(next):
   321  		return calcDifficultyEip2384(time, parent)
   322  	case config.IsConstantinople(next):
   323  		return calcDifficultyConstantinople(time, parent)
   324  	case config.IsByzantium(next):
   325  		return calcDifficultyByzantium(time, parent)
   326  	case config.IsHomestead(next):
   327  		return calcDifficultyHomestead(time, parent)
   328  	default:
   329  		return calcDifficultyFrontier(time, parent)
   330  	}
   331  }
   332  
   333  // Some weird constants to avoid constant memory allocs for them.
   334  var (
   335  	expDiffPeriod = big.NewInt(100000)
   336  	big1          = big.NewInt(1)
   337  	big2          = big.NewInt(2)
   338  	big9          = big.NewInt(9)
   339  	big10         = big.NewInt(10)
   340  	bigMinus99    = big.NewInt(-99)
   341  )
   342  
   343  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   344  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   345  // how uncles affect the calculation
   346  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   347  	// Note, the calculations below looks at the parent number, which is 1 below
   348  	// the block number. Thus we remove one from the delay given
   349  	bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   350  	return func(time uint64, parent *types.Header) *big.Int {
   351  		// https://github.com/ethereum/EIPs/issues/100.
   352  		// algorithm:
   353  		// diff = (parent_diff +
   354  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   355  		//        ) + 2^(periodCount - 2)
   356  
   357  		bigTime := new(big.Int).SetUint64(time)
   358  		bigParentTime := new(big.Int).SetUint64(parent.Time)
   359  
   360  		// holds intermediate values to make the algo easier to read & audit
   361  		x := new(big.Int)
   362  		y := new(big.Int)
   363  
   364  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   365  		x.Sub(bigTime, bigParentTime)
   366  		x.Div(x, big9)
   367  		if parent.UncleHash == types.EmptyUncleHash {
   368  			x.Sub(big1, x)
   369  		} else {
   370  			x.Sub(big2, x)
   371  		}
   372  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   373  		if x.Cmp(bigMinus99) < 0 {
   374  			x.Set(bigMinus99)
   375  		}
   376  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   377  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   378  		x.Mul(y, x)
   379  		x.Add(parent.Difficulty, x)
   380  
   381  		// minimum difficulty can ever be (before exponential factor)
   382  		if x.Cmp(params.MinimumDifficulty) < 0 {
   383  			x.Set(params.MinimumDifficulty)
   384  		}
   385  		// calculate a fake block number for the ice-age delay
   386  		// Specification: https://eips.ethereum.org/EIPS/eip-1234
   387  		fakeBlockNumber := new(big.Int)
   388  		if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   389  			fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   390  		}
   391  		// for the exponential factor
   392  		periodCount := fakeBlockNumber
   393  		periodCount.Div(periodCount, expDiffPeriod)
   394  
   395  		// the exponential factor, commonly referred to as "the bomb"
   396  		// diff = diff + 2^(periodCount - 2)
   397  		if periodCount.Cmp(big1) > 0 {
   398  			y.Sub(periodCount, big2)
   399  			y.Exp(big2, y, nil)
   400  			x.Add(x, y)
   401  		}
   402  		return x
   403  	}
   404  }
   405  
   406  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   407  // the difficulty that a new block should have when created at time given the
   408  // parent block's time and difficulty. The calculation uses the Homestead rules.
   409  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   410  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   411  	// algorithm:
   412  	// diff = (parent_diff +
   413  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   414  	//        ) + 2^(periodCount - 2)
   415  
   416  	bigTime := new(big.Int).SetUint64(time)
   417  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   418  
   419  	// holds intermediate values to make the algo easier to read & audit
   420  	x := new(big.Int)
   421  	y := new(big.Int)
   422  
   423  	// 1 - (block_timestamp - parent_timestamp) // 10
   424  	x.Sub(bigTime, bigParentTime)
   425  	x.Div(x, big10)
   426  	x.Sub(big1, x)
   427  
   428  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   429  	if x.Cmp(bigMinus99) < 0 {
   430  		x.Set(bigMinus99)
   431  	}
   432  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   433  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   434  	x.Mul(y, x)
   435  	x.Add(parent.Difficulty, x)
   436  
   437  	// minimum difficulty can ever be (before exponential factor)
   438  	if x.Cmp(params.MinimumDifficulty) < 0 {
   439  		x.Set(params.MinimumDifficulty)
   440  	}
   441  	// for the exponential factor
   442  	periodCount := new(big.Int).Add(parent.Number, big1)
   443  	periodCount.Div(periodCount, expDiffPeriod)
   444  
   445  	// the exponential factor, commonly referred to as "the bomb"
   446  	// diff = diff + 2^(periodCount - 2)
   447  	if periodCount.Cmp(big1) > 0 {
   448  		y.Sub(periodCount, big2)
   449  		y.Exp(big2, y, nil)
   450  		x.Add(x, y)
   451  	}
   452  	return x
   453  }
   454  
   455  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   456  // difficulty that a new block should have when created at time given the parent
   457  // block's time and difficulty. The calculation uses the Frontier rules.
   458  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   459  	diff := new(big.Int)
   460  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   461  	bigTime := new(big.Int)
   462  	bigParentTime := new(big.Int)
   463  
   464  	bigTime.SetUint64(time)
   465  	bigParentTime.SetUint64(parent.Time)
   466  
   467  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   468  		diff.Add(parent.Difficulty, adjust)
   469  	} else {
   470  		diff.Sub(parent.Difficulty, adjust)
   471  	}
   472  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   473  		diff.Set(params.MinimumDifficulty)
   474  	}
   475  
   476  	periodCount := new(big.Int).Add(parent.Number, big1)
   477  	periodCount.Div(periodCount, expDiffPeriod)
   478  	if periodCount.Cmp(big1) > 0 {
   479  		// diff = diff + 2^(periodCount - 2)
   480  		expDiff := periodCount.Sub(periodCount, big2)
   481  		expDiff.Exp(big2, expDiff, nil)
   482  		diff.Add(diff, expDiff)
   483  		diff = math.BigMax(diff, params.MinimumDifficulty)
   484  	}
   485  	return diff
   486  }
   487  
   488  // VerifySeal implements consensus.Engine, checking whether the given block satisfies
   489  // the PoW difficulty requirements.
   490  func (ethash *Ethash) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error {
   491  	return ethash.verifySeal(chain, header, false)
   492  }
   493  
   494  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   495  // either using the usual ethash cache for it, or alternatively using a full DAG
   496  // to make remote mining fast.
   497  func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
   498  	// If we're running a fake PoW, accept any seal as valid
   499  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   500  		time.Sleep(ethash.fakeDelay)
   501  		if ethash.fakeFail == header.Number.Uint64() {
   502  			return errInvalidPoW
   503  		}
   504  		return nil
   505  	}
   506  	// If we're running a shared PoW, delegate verification to it
   507  	if ethash.shared != nil {
   508  		return ethash.shared.verifySeal(chain, header, fulldag)
   509  	}
   510  	// Ensure that we have a valid difficulty for the block
   511  	if header.Difficulty.Sign() <= 0 {
   512  		return errInvalidDifficulty
   513  	}
   514  	// Recompute the digest and PoW values
   515  	number := header.Number.Uint64()
   516  
   517  	var (
   518  		digest []byte
   519  		result []byte
   520  	)
   521  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   522  	if fulldag {
   523  		dataset := ethash.dataset(number, true)
   524  		if dataset.generated() {
   525  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   526  
   527  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   528  			// until after the call to hashimotoFull so it's not unmapped while being used.
   529  			runtime.KeepAlive(dataset)
   530  		} else {
   531  			// Dataset not yet generated, don't hang, use a cache instead
   532  			fulldag = false
   533  		}
   534  	}
   535  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   536  	if !fulldag {
   537  		cache := ethash.cache(number)
   538  
   539  		size := datasetSize(number)
   540  		if ethash.config.PowMode == ModeTest {
   541  			size = 32 * 1024
   542  		}
   543  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   544  
   545  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   546  		// until after the call to hashimotoLight so it's not unmapped while being used.
   547  		runtime.KeepAlive(cache)
   548  	}
   549  	// Verify the calculated values against the ones provided in the header
   550  	if !bytes.Equal(header.MixDigest[:], digest) {
   551  		return errInvalidMixDigest
   552  	}
   553  	target := new(big.Int).Div(two256, header.Difficulty)
   554  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   555  		return errInvalidPoW
   556  	}
   557  	return nil
   558  }
   559  
   560  // Prepare implements consensus.Engine, initializing the difficulty field of a
   561  // header to conform to the ethash protocol. The changes are done inline.
   562  func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
   563  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   564  	if parent == nil {
   565  		return consensus.ErrUnknownAncestor
   566  	}
   567  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
   568  	return nil
   569  }
   570  
   571  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   572  // setting the final state on the header
   573  func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs *[]*types.Transaction, uncles []*types.Header, receipts *[]*types.Receipt, systemTxs []*types.Transaction) error {
   574  	// Accumulate any block and uncle rewards and commit the final state root
   575  	accumulateRewards(chain.Config(), state, header, uncles)
   576  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   577  
   578  	return nil
   579  }
   580  
   581  // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
   582  // uncle rewards, setting the final state and assembling the block.
   583  func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, []*types.Receipt, error) {
   584  	// Accumulate any block and uncle rewards and commit the final state root
   585  	accumulateRewards(chain.Config(), state, header, uncles)
   586  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   587  
   588  	// Header seems complete, assemble into a block and return
   589  	return types.NewBlock(header, txs, uncles, receipts, new(trie.Trie)), receipts, nil
   590  }
   591  
   592  // SealHash returns the hash of a block prior to it being sealed.
   593  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   594  	hasher := sha3.NewLegacyKeccak256()
   595  
   596  	rlp.Encode(hasher, []interface{}{
   597  		header.ParentHash,
   598  		header.UncleHash,
   599  		header.Coinbase,
   600  		header.Root,
   601  		header.TxHash,
   602  		header.ReceiptHash,
   603  		header.Bloom,
   604  		header.Difficulty,
   605  		header.Number,
   606  		header.GasLimit,
   607  		header.GasUsed,
   608  		header.Time,
   609  		header.Extra,
   610  	})
   611  	hasher.Sum(hash[:0])
   612  	return hash
   613  }
   614  
   615  // Some weird constants to avoid constant memory allocs for them.
   616  var (
   617  	big8  = big.NewInt(8)
   618  	big32 = big.NewInt(32)
   619  )
   620  
   621  // AccumulateRewards credits the coinbase of the given block with the mining
   622  // reward. The total reward consists of the static block reward and rewards for
   623  // included uncles. The coinbase of each uncle block is also rewarded.
   624  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   625  	// Select the correct block reward based on chain progression
   626  	blockReward := FrontierBlockReward
   627  	if config.IsByzantium(header.Number) {
   628  		blockReward = ByzantiumBlockReward
   629  	}
   630  	if config.IsConstantinople(header.Number) {
   631  		blockReward = ConstantinopleBlockReward
   632  	}
   633  	// Accumulate the rewards for the miner and any included uncles
   634  	reward := new(big.Int).Set(blockReward)
   635  	r := new(big.Int)
   636  	for _, uncle := range uncles {
   637  		r.Add(uncle.Number, big8)
   638  		r.Sub(r, header.Number)
   639  		r.Mul(r, blockReward)
   640  		r.Div(r, big8)
   641  		state.AddBalance(uncle.Coinbase, r)
   642  
   643  		r.Div(blockReward, big32)
   644  		reward.Add(reward, r)
   645  	}
   646  	state.AddBalance(header.Coinbase, reward)
   647  }