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