github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/consensus/ethash/consensus.go (about)

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