github.com/valorbit/go-ethereum@v1.9.11-rc4/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/valorbit/go-ethereum/common"
    29  	"github.com/valorbit/go-ethereum/common/math"
    30  	"github.com/valorbit/go-ethereum/consensus"
    31  	"github.com/valorbit/go-ethereum/consensus/misc"
    32  	"github.com/valorbit/go-ethereum/core/state"
    33  	"github.com/valorbit/go-ethereum/core/types"
    34  	"github.com/valorbit/go-ethereum/params"
    35  	"github.com/valorbit/go-ethereum/rlp"
    36  	"golang.org/x/crypto/sha3"
    37  )
    38  
    39  // Ethash proof-of-work protocol constants.
    40  var (
    41  	FrontierBlockReward       = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
    42  	ByzantiumBlockReward      = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
    43  	ConstantinopleBlockReward = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
    44  	// Block reward in wei for successfully mining a block for Valorbit chain
    45  	ValorbitBlockReward, _ = new(big.Int).SetString("5000000000000000000000", 10)
    46  
    47  	maxUncles                = 2                // Maximum number of uncles allowed in a single block
    48  	allowedFutureBlockTime   = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks
    49  	DisinflationRateQuotient = big.NewInt(11)   // Disinflation rate quotient for ECIP1017
    50  	DisinflationRateDivisor  = big.NewInt(10)   // Disinflation rate divisor for ECIP1017
    51  	BlockRewardGrowthEras    = big.NewInt(12)   // (Dis)inflation runs for this many eras
    52  
    53  	// calcDifficultyEip2384 is the difficulty adjustment algorithm as specified by EIP 2384.
    54  	// It offsets the bomb 4M blocks from Constantinople, so in total 9M blocks.
    55  	// Specification EIP-2384: https://eips.ethereum.org/EIPS/eip-2384
    56  	calcDifficultyEip2384 = makeDifficultyCalculator(big.NewInt(9000000))
    57  
    58  	// calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
    59  	// It returns 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, but with
    61  	// bomb offset 5M.
    62  	// Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
    63  	calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
    64  
    65  	// calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
    66  	// the difficulty that a new block should have when created at time given the
    67  	// parent block's time and difficulty. The calculation uses the Byzantium rules.
    68  	// Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
    69  	calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
    70  )
    71  
    72  // Various error messages to mark blocks invalid. These should be private to
    73  // prevent engine specific errors from being referenced in the remainder of the
    74  // codebase, inherently breaking if the engine is swapped out. Please put common
    75  // error types into the consensus package.
    76  var (
    77  	errOlderBlockTime    = errors.New("timestamp older than parent")
    78  	errTooManyUncles     = errors.New("too many uncles")
    79  	errDuplicateUncle    = errors.New("duplicate uncle")
    80  	errUncleIsAncestor   = errors.New("uncle is ancestor")
    81  	errDanglingUncle     = errors.New("uncle's parent is not ancestor")
    82  	errInvalidDifficulty = errors.New("non-positive difficulty")
    83  	errInvalidMixDigest  = errors.New("invalid mix digest")
    84  	errInvalidPoW        = errors.New("invalid proof-of-work")
    85  )
    86  
    87  // Author implements consensus.Engine, returning the header's coinbase as the
    88  // proof-of-work verified author of the block.
    89  func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
    90  	return header.Coinbase, nil
    91  }
    92  
    93  // VerifyHeader checks whether a header conforms to the consensus rules of the
    94  // stock Ethereum ethash engine.
    95  func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
    96  	// If we're running a full engine faking, accept any input as valid
    97  	if ethash.config.PowMode == ModeFullFake {
    98  		return nil
    99  	}
   100  	// Short circuit if the header is known, or its parent not
   101  	number := header.Number.Uint64()
   102  	if chain.GetHeader(header.Hash(), number) != nil {
   103  		return nil
   104  	}
   105  	parent := chain.GetHeader(header.ParentHash, number-1)
   106  	if parent == nil {
   107  		return consensus.ErrUnknownAncestor
   108  	}
   109  	// Sanity checks passed, do a proper verification
   110  	return ethash.verifyHeader(chain, header, parent, false, seal)
   111  }
   112  
   113  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
   114  // concurrently. The method returns a quit channel to abort the operations and
   115  // a results channel to retrieve the async verifications.
   116  func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   117  	// If we're running a full engine faking, accept any input as valid
   118  	if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
   119  		abort, results := make(chan struct{}), make(chan error, len(headers))
   120  		for i := 0; i < len(headers); i++ {
   121  			results <- nil
   122  		}
   123  		return abort, results
   124  	}
   125  
   126  	// Spawn as many workers as allowed threads
   127  	workers := runtime.GOMAXPROCS(0)
   128  	if len(headers) < workers {
   129  		workers = len(headers)
   130  	}
   131  
   132  	// Create a task channel and spawn the verifiers
   133  	var (
   134  		inputs = make(chan int)
   135  		done   = make(chan int, workers)
   136  		errors = make([]error, len(headers))
   137  		abort  = make(chan struct{})
   138  	)
   139  	for i := 0; i < workers; i++ {
   140  		go func() {
   141  			for index := range inputs {
   142  				errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index)
   143  				done <- index
   144  			}
   145  		}()
   146  	}
   147  
   148  	errorsOut := make(chan error, len(headers))
   149  	go func() {
   150  		defer close(inputs)
   151  		var (
   152  			in, out = 0, 0
   153  			checked = make([]bool, len(headers))
   154  			inputs  = inputs
   155  		)
   156  		for {
   157  			select {
   158  			case inputs <- in:
   159  				if in++; in == len(headers) {
   160  					// Reached end of headers. Stop sending to workers.
   161  					inputs = nil
   162  				}
   163  			case index := <-done:
   164  				for checked[index] = true; checked[out]; out++ {
   165  					errorsOut <- errors[out]
   166  					if out == len(headers)-1 {
   167  						return
   168  					}
   169  				}
   170  			case <-abort:
   171  				return
   172  			}
   173  		}
   174  	}()
   175  	return abort, errorsOut
   176  }
   177  
   178  func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainReader, headers []*types.Header, seals []bool, index int) error {
   179  	var parent *types.Header
   180  	if index == 0 {
   181  		parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
   182  	} else if headers[index-1].Hash() == headers[index].ParentHash {
   183  		parent = headers[index-1]
   184  	}
   185  	if parent == nil {
   186  		return consensus.ErrUnknownAncestor
   187  	}
   188  	if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil {
   189  		return nil // known block
   190  	}
   191  	return ethash.verifyHeader(chain, headers[index], parent, false, seals[index])
   192  }
   193  
   194  // VerifyUncles verifies that the given block's uncles conform to the consensus
   195  // rules of the stock Ethereum ethash engine.
   196  func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   197  	// If we're running a full engine faking, accept any input as valid
   198  	if ethash.config.PowMode == ModeFullFake {
   199  		return nil
   200  	}
   201  	// Verify that there are at most 2 uncles included in this block
   202  	if len(block.Uncles()) > maxUncles {
   203  		return errTooManyUncles
   204  	}
   205  	if len(block.Uncles()) == 0 {
   206  		return nil
   207  	}
   208  	// Gather the set of past uncles and ancestors
   209  	uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
   210  
   211  	number, parent := block.NumberU64()-1, block.ParentHash()
   212  	for i := 0; i < 7; i++ {
   213  		ancestor := chain.GetBlock(parent, number)
   214  		if ancestor == nil {
   215  			break
   216  		}
   217  		ancestors[ancestor.Hash()] = ancestor.Header()
   218  		for _, uncle := range ancestor.Uncles() {
   219  			uncles.Add(uncle.Hash())
   220  		}
   221  		parent, number = ancestor.ParentHash(), number-1
   222  	}
   223  	ancestors[block.Hash()] = block.Header()
   224  	uncles.Add(block.Hash())
   225  
   226  	// Verify each of the uncles that it's recent, but not an ancestor
   227  	for _, uncle := range block.Uncles() {
   228  		// Make sure every uncle is rewarded only once
   229  		hash := uncle.Hash()
   230  		if uncles.Contains(hash) {
   231  			return errDuplicateUncle
   232  		}
   233  		uncles.Add(hash)
   234  
   235  		// Make sure the uncle has a valid ancestry
   236  		if ancestors[hash] != nil {
   237  			return errUncleIsAncestor
   238  		}
   239  		if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
   240  			return errDanglingUncle
   241  		}
   242  		if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
   243  			return err
   244  		}
   245  	}
   246  	return nil
   247  }
   248  
   249  // verifyHeader checks whether a header conforms to the consensus rules of the
   250  // stock Ethereum ethash engine.
   251  // See YP section 4.3.4. "Block Header Validity"
   252  func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error {
   253  	// Ensure that the header's extra-data section is of a reasonable size
   254  	if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
   255  		return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
   256  	}
   257  	// Verify the header's timestamp
   258  	if !uncle {
   259  		if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
   260  			return consensus.ErrFutureBlock
   261  		}
   262  	}
   263  	if header.Time <= parent.Time {
   264  		return errOlderBlockTime
   265  	}
   266  	// Verify the block's difficulty based on its timestamp and parent's difficulty
   267  	expected := ethash.CalcDifficulty(chain, header.Time, parent)
   268  
   269  	if expected.Cmp(header.Difficulty) != 0 {
   270  		return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
   271  	}
   272  	// Verify that the gas limit is <= 2^63-1
   273  	cap := uint64(0x7fffffffffffffff)
   274  	if header.GasLimit > cap {
   275  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   276  	}
   277  	// Verify that the gasUsed is <= gasLimit
   278  	if header.GasUsed > header.GasLimit {
   279  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   280  	}
   281  
   282  	// Verify that the gas limit remains within allowed bounds
   283  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   284  	if diff < 0 {
   285  		diff *= -1
   286  	}
   287  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   288  
   289  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   290  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   291  	}
   292  	// Verify that the block number is parent's +1
   293  	if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
   294  		return consensus.ErrInvalidNumber
   295  	}
   296  	// Verify the engine specific seal securing the block
   297  	if seal {
   298  		if err := ethash.VerifySeal(chain, header); err != nil {
   299  			return err
   300  		}
   301  	}
   302  	// If all checks passed, validate any special fields for hard forks
   303  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   304  		return err
   305  	}
   306  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   307  		return err
   308  	}
   309  	return nil
   310  }
   311  
   312  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   313  // the difficulty that a new block should have when created at time
   314  // given the parent block's time and difficulty.
   315  func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   316  	return CalcDifficulty(chain.Config(), time, parent)
   317  }
   318  
   319  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   320  // the difficulty that a new block should have when created at time
   321  // given the parent block's time and difficulty.
   322  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   323  	next := new(big.Int).Add(parent.Number, big1)
   324  	switch {
   325  	case config.IsMuirGlacier(next):
   326  		return calcDifficultyEip2384(time, parent)
   327  	case config.IsConstantinople(next):
   328  		return calcDifficultyConstantinople(time, parent)
   329  	case config.IsByzantium(next):
   330  		return calcDifficultyByzantium(time, parent)
   331  	case config.IsHomestead(next):
   332  		return calcDifficultyHomestead(time, parent)
   333  	default:
   334  		return calcDifficultyFrontier(time, parent)
   335  	}
   336  }
   337  
   338  // Some weird constants to avoid constant memory allocs for them.
   339  var (
   340  	expDiffPeriod = big.NewInt(100000)
   341  	big1          = big.NewInt(1)
   342  	big2          = big.NewInt(2)
   343  	big9          = big.NewInt(9)
   344  	big10         = big.NewInt(10)
   345  	bigMinus99    = big.NewInt(-99)
   346  )
   347  
   348  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   349  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   350  // how uncles affect the calculation
   351  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   352  	// Note, the calculations below looks at the parent number, which is 1 below
   353  	// the block number. Thus we remove one from the delay given
   354  	// bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   355  	return func(time uint64, parent *types.Header) *big.Int {
   356  		// https://github.com/valorbit/EIPs/issues/100.
   357  		// algorithm:
   358  		// diff = (parent_diff +
   359  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   360  		//        ) + 2^(periodCount - 2)
   361  
   362  		bigTime := new(big.Int).SetUint64(time)
   363  		bigParentTime := new(big.Int).SetUint64(parent.Time)
   364  
   365  		// holds intermediate values to make the algo easier to read & audit
   366  		x := new(big.Int)
   367  		y := new(big.Int)
   368  
   369  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   370  		x.Sub(bigTime, bigParentTime)
   371  		x.Div(x, big9)
   372  		if parent.UncleHash == types.EmptyUncleHash {
   373  			x.Sub(big1, x)
   374  		} else {
   375  			x.Sub(big2, x)
   376  		}
   377  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   378  		if x.Cmp(bigMinus99) < 0 {
   379  			x.Set(bigMinus99)
   380  		}
   381  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   382  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   383  		x.Mul(y, x)
   384  		x.Add(parent.Difficulty, x)
   385  
   386  		// minimum difficulty can ever be (before exponential factor)
   387  		if x.Cmp(params.MinimumDifficulty) < 0 {
   388  			x.Set(params.MinimumDifficulty)
   389  		}
   390  		/*
   391  			// calculate a fake block number for the ice-age delay
   392  			// Specification: https://eips.ethereum.org/EIPS/eip-1234
   393  			fakeBlockNumber := new(big.Int)
   394  			if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   395  				fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   396  			}
   397  			// for the exponential factor
   398  			periodCount := fakeBlockNumber
   399  			periodCount.Div(periodCount, expDiffPeriod)
   400  
   401  			// the exponential factor, commonly referred to as "the bomb"
   402  			diff = diff + 2^(periodCount - 2)
   403  			if periodCount.Cmp(big1) > 0 {
   404  				y.Sub(periodCount, big2)
   405  				y.Exp(big2, y, nil)
   406  				x.Add(x, y)
   407  			}
   408  		*/
   409  		return x
   410  	}
   411  }
   412  
   413  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   414  // the difficulty that a new block should have when created at time given the
   415  // parent block's time and difficulty. The calculation uses the Homestead rules.
   416  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   417  	// https://github.com/valorbit/EIPs/blob/master/EIPS/eip-2.md
   418  	// algorithm:
   419  	// diff = (parent_diff +
   420  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   421  	//        ) + 2^(periodCount - 2)
   422  
   423  	bigTime := new(big.Int).SetUint64(time)
   424  	bigParentTime := new(big.Int).SetUint64(parent.Time)
   425  
   426  	// holds intermediate values to make the algo easier to read & audit
   427  	x := new(big.Int)
   428  	y := new(big.Int)
   429  
   430  	// 1 - (block_timestamp - parent_timestamp) // 10
   431  	x.Sub(bigTime, bigParentTime)
   432  	x.Div(x, big10)
   433  	x.Sub(big1, x)
   434  
   435  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   436  	if x.Cmp(bigMinus99) < 0 {
   437  		x.Set(bigMinus99)
   438  	}
   439  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   440  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   441  	x.Mul(y, x)
   442  	x.Add(parent.Difficulty, x)
   443  
   444  	// minimum difficulty can ever be (before exponential factor)
   445  	if x.Cmp(params.MinimumDifficulty) < 0 {
   446  		x.Set(params.MinimumDifficulty)
   447  	}
   448  	// for the exponential factor
   449  	periodCount := new(big.Int).Add(parent.Number, big1)
   450  	periodCount.Div(periodCount, expDiffPeriod)
   451  
   452  	// the exponential factor, commonly referred to as "the bomb"
   453  	// diff = diff + 2^(periodCount - 2)
   454  	if periodCount.Cmp(big1) > 0 {
   455  		y.Sub(periodCount, big2)
   456  		y.Exp(big2, y, nil)
   457  		x.Add(x, y)
   458  	}
   459  	return x
   460  }
   461  
   462  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   463  // difficulty that a new block should have when created at time given the parent
   464  // block's time and difficulty. The calculation uses the Frontier rules.
   465  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   466  	diff := new(big.Int)
   467  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   468  	bigTime := new(big.Int)
   469  	bigParentTime := new(big.Int)
   470  
   471  	bigTime.SetUint64(time)
   472  	bigParentTime.SetUint64(parent.Time)
   473  
   474  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   475  		diff.Add(parent.Difficulty, adjust)
   476  	} else {
   477  		diff.Sub(parent.Difficulty, adjust)
   478  	}
   479  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   480  		diff.Set(params.MinimumDifficulty)
   481  	}
   482  
   483  	periodCount := new(big.Int).Add(parent.Number, big1)
   484  	periodCount.Div(periodCount, expDiffPeriod)
   485  	if periodCount.Cmp(big1) > 0 {
   486  		//	// diff = diff + 2^(periodCount - 2)
   487  		//	expDiff := periodCount.Sub(periodCount, big2)
   488  		//	expDiff.Exp(big2, expDiff, nil)
   489  		//	diff.Add(diff, expDiff)
   490  		diff = math.BigMax(diff, params.MinimumDifficulty)
   491  	}
   492  	return diff
   493  }
   494  
   495  // VerifySeal implements consensus.Engine, checking whether the given block satisfies
   496  // the PoW difficulty requirements.
   497  func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   498  	return ethash.verifySeal(chain, header, false)
   499  }
   500  
   501  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   502  // either using the usual ethash cache for it, or alternatively using a full DAG
   503  // to make remote mining fast.
   504  func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Header, fulldag bool) error {
   505  	// If we're running a fake PoW, accept any seal as valid
   506  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   507  		time.Sleep(ethash.fakeDelay)
   508  		if ethash.fakeFail == header.Number.Uint64() {
   509  			return errInvalidPoW
   510  		}
   511  		return nil
   512  	}
   513  	// If we're running a shared PoW, delegate verification to it
   514  	if ethash.shared != nil {
   515  		return ethash.shared.verifySeal(chain, header, fulldag)
   516  	}
   517  	// Ensure that we have a valid difficulty for the block
   518  	if header.Difficulty.Sign() <= 0 {
   519  		return errInvalidDifficulty
   520  	}
   521  	// Recompute the digest and PoW values
   522  	number := header.Number.Uint64()
   523  
   524  	var (
   525  		digest []byte
   526  		result []byte
   527  	)
   528  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   529  	if fulldag {
   530  		dataset := ethash.dataset(number, true)
   531  		if dataset.generated() {
   532  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   533  
   534  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   535  			// until after the call to hashimotoFull so it's not unmapped while being used.
   536  			runtime.KeepAlive(dataset)
   537  		} else {
   538  			// Dataset not yet generated, don't hang, use a cache instead
   539  			fulldag = false
   540  		}
   541  	}
   542  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   543  	if !fulldag {
   544  		cache := ethash.cache(number)
   545  
   546  		size := datasetSize(number)
   547  		if ethash.config.PowMode == ModeTest {
   548  			size = 32 * 1024
   549  		}
   550  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   551  
   552  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   553  		// until after the call to hashimotoLight so it's not unmapped while being used.
   554  		runtime.KeepAlive(cache)
   555  	}
   556  	// Verify the calculated values against the ones provided in the header
   557  	if !bytes.Equal(header.MixDigest[:], digest) {
   558  		return errInvalidMixDigest
   559  	}
   560  	target := new(big.Int).Div(two256, header.Difficulty)
   561  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   562  		return errInvalidPoW
   563  	}
   564  	return nil
   565  }
   566  
   567  // TODO : use ethereum rewards by default
   568  // default accumulateRewards()
   569  var accumulateRewards func(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) = accumulateValorbitRewards
   570  
   571  // Prepare implements consensus.Engine, initializing the difficulty field of a
   572  // header to conform to the ethash protocol. The changes are done inline.
   573  func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
   574  
   575  	// setup accumulateRewards
   576  	rootHash := chain.GetHeaderByNumber(0).Hash()
   577  
   578  	if rootHash == params.ValorbitGenesisHash || rootHash == params.GranvilleGenesisHash {
   579  		accumulateRewards = accumulateValorbitRewards
   580  	}
   581  
   582  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   583  	if parent == nil {
   584  		return consensus.ErrUnknownAncestor
   585  	}
   586  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
   587  	return nil
   588  }
   589  
   590  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   591  // setting the final state on the header
   592  func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
   593  	// Accumulate any block and uncle rewards and commit the final state root
   594  	accumulateRewards(chain.Config(), state, header, uncles)
   595  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   596  }
   597  
   598  // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
   599  // uncle rewards, setting the final state and assembling the block.
   600  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) {
   601  	// Accumulate any block and uncle rewards and commit the final state root
   602  	accumulateRewards(chain.Config(), state, header, uncles)
   603  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   604  
   605  	// Header seems complete, assemble into a block and return
   606  	return types.NewBlock(header, txs, uncles, receipts), nil
   607  }
   608  
   609  // SealHash returns the hash of a block prior to it being sealed.
   610  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   611  	hasher := sha3.NewLegacyKeccak256()
   612  
   613  	rlp.Encode(hasher, []interface{}{
   614  		header.ParentHash,
   615  		header.UncleHash,
   616  		header.Coinbase,
   617  		header.Root,
   618  		header.TxHash,
   619  		header.ReceiptHash,
   620  		header.Bloom,
   621  		header.Difficulty,
   622  		header.Number,
   623  		header.GasLimit,
   624  		header.GasUsed,
   625  		header.Time,
   626  		header.Extra,
   627  	})
   628  	hasher.Sum(hash[:0])
   629  	return hash
   630  }
   631  
   632  // Some weird constants to avoid constant memory allocs for them.
   633  var (
   634  	big8  = big.NewInt(8)
   635  	big32 = big.NewInt(32)
   636  )
   637  
   638  // AccumulateRewards credits the coinbase of the given block with the mining
   639  // reward. The total reward consists of the static block reward and rewards for
   640  // included uncles. The coinbase of each uncle block is also rewarded.
   641  func accumulateEthereumRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   642  	// Select the correct block reward based on chain progression
   643  	blockReward := FrontierBlockReward
   644  	if config.IsByzantium(header.Number) {
   645  		blockReward = ByzantiumBlockReward
   646  	}
   647  	if config.IsConstantinople(header.Number) {
   648  		blockReward = ConstantinopleBlockReward
   649  	}
   650  	// Accumulate the rewards for the miner and any included uncles
   651  	reward := new(big.Int).Set(blockReward)
   652  	r := new(big.Int)
   653  	for _, uncle := range uncles {
   654  		r.Add(uncle.Number, big8)
   655  		r.Sub(r, header.Number)
   656  		r.Mul(r, blockReward)
   657  		r.Div(r, big8)
   658  		state.AddBalance(uncle.Coinbase, r)
   659  
   660  		r.Div(blockReward, big32)
   661  		reward.Add(reward, r)
   662  	}
   663  	state.AddBalance(header.Coinbase, reward)
   664  }
   665  
   666  // AccumulateRewards credits the coinbase of the given block with the mining
   667  // reward. The total reward consists of the static block reward and rewards for
   668  // included uncles. The coinbase of each uncle block is also rewarded.
   669  func accumulateValorbitRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   670  
   671  	blockReward := ValorbitBlockReward
   672  
   673  	if config.HasECIP1017() {
   674  		// Ensure value 'era' is configured.
   675  		eraLen := config.ECIP1017EraRounds
   676  
   677  		era := GetBlockEra(header.Number, eraLen)
   678  
   679  		if era.Cmp(BlockRewardGrowthEras) == 1 {
   680  			era = BlockRewardGrowthEras
   681  		}
   682  
   683  		wr := GetBlockWinnerRewardByEra(era, blockReward) // wr "winner reward". 5, 4, 3.2, 2.56, ...
   684  
   685  		wurs := GetBlockWinnerRewardForUnclesByEra(era, uncles, blockReward) // wurs "winner uncle rewards"
   686  		wr.Add(wr, wurs)
   687  
   688  		state.AddBalance(header.Coinbase, wr) // $$
   689  
   690  		// Reward uncle miners.
   691  		for _, uncle := range uncles {
   692  			ur := GetBlockUncleRewardByEra(era, header, uncle, blockReward)
   693  			state.AddBalance(uncle.Coinbase, ur) // $$
   694  		}
   695  	} else {
   696  		// Accumulate the rewards for the miner and any included uncles
   697  		reward := new(big.Int).Set(blockReward)
   698  		r := new(big.Int)
   699  		for _, uncle := range uncles {
   700  			r.Add(uncle.Number, big8)
   701  			r.Sub(r, header.Number)
   702  			r.Mul(r, blockReward)
   703  			r.Div(r, big8)
   704  			state.AddBalance(uncle.Coinbase, r)
   705  
   706  			r.Div(blockReward, big32)
   707  			reward.Add(reward, r)
   708  		}
   709  		state.AddBalance(header.Coinbase, reward)
   710  	}
   711  }
   712  
   713  // As of "Era 2" (zero-index era 1), uncle miners and winners are rewarded equally for each included block.
   714  // So they share this function.
   715  func getEraUncleBlockReward(era *big.Int, blockReward *big.Int) *big.Int {
   716  	return new(big.Int).Div(GetBlockWinnerRewardByEra(era, blockReward), big32)
   717  }
   718  
   719  // GetBlockUncleRewardByEra gets called _for each uncle miner_ associated with a winner block's uncles.
   720  func GetBlockUncleRewardByEra(era *big.Int, header, uncle *types.Header, blockReward *big.Int) *big.Int {
   721  	// Era 1 (index 0):
   722  	//   An extra reward to the winning miner for including uncles as part of the block, in the form of an extra 1/32 (0.15625ETC) per uncle included, up to a maximum of two (2) uncles.
   723  	if era.Cmp(big.NewInt(0)) == 0 {
   724  		r := new(big.Int)
   725  		r.Add(uncle.Number, big8) // 2,534,998 + 8              = 2,535,006
   726  		r.Sub(r, header.Number)   // 2,535,006 - 2,534,999        = 7
   727  		r.Mul(r, blockReward)     // 7 * 5e+18               = 35e+18
   728  		r.Div(r, big8)            // 35e+18 / 8                            = 7/8 * 5e+18
   729  
   730  		return r
   731  	}
   732  	return getEraUncleBlockReward(era, blockReward)
   733  }
   734  
   735  // GetBlockWinnerRewardForUnclesByEra gets called _per winner_, and accumulates rewards for each included uncle.
   736  // Assumes uncles have been validated and limited (@ func (v *BlockValidator) VerifyUncles).
   737  func GetBlockWinnerRewardForUnclesByEra(era *big.Int, uncles []*types.Header, blockReward *big.Int) *big.Int {
   738  	r := big.NewInt(0)
   739  
   740  	for range uncles {
   741  		r.Add(r, getEraUncleBlockReward(era, blockReward)) // can reuse this, since 1/32 for winner's uncles remain unchanged from "Era 1"
   742  	}
   743  	return r
   744  }
   745  
   746  // GetBlockWinnerRewardByEra gets a block reward at disinflation rate.
   747  // Constants MaxBlockReward, DisinflationRateQuotient, and DisinflationRateDivisor assumed.
   748  func GetBlockWinnerRewardByEra(era *big.Int, blockReward *big.Int) *big.Int {
   749  	if era.Cmp(big.NewInt(0)) == 0 {
   750  		return new(big.Int).Set(blockReward)
   751  	}
   752  
   753  	// MaxBlockReward _r_ * (4/5)**era == MaxBlockReward * (4**era) / (5**era)
   754  	// since (q/d)**n == q**n / d**n
   755  	// qed
   756  	var q, d, r *big.Int = new(big.Int), new(big.Int), new(big.Int)
   757  
   758  	q.Exp(DisinflationRateQuotient, era, nil)
   759  	d.Exp(DisinflationRateDivisor, era, nil)
   760  
   761  	r.Mul(blockReward, q)
   762  	r.Div(r, d)
   763  
   764  	return r
   765  }
   766  
   767  // GetBlockEra gets which "Era" a given block is within, given an era length (ecip-1017 has era=5,000,000 blocks)
   768  // Returns a zero-index era number, so "Era 1": 0, "Era 2": 1, "Era 3": 2 ...
   769  func GetBlockEra(blockNum, eraLength *big.Int) *big.Int {
   770  	// If genesis block or impossible negative-numbered block, return zero-val.
   771  	if blockNum.Sign() < 1 {
   772  		return new(big.Int)
   773  	}
   774  
   775  	remainder := big.NewInt(0).Mod(big.NewInt(0).Sub(blockNum, big.NewInt(1)), eraLength)
   776  	base := big.NewInt(0).Sub(blockNum, remainder)
   777  
   778  	d := big.NewInt(0).Div(base, eraLength)
   779  	dremainder := big.NewInt(0).Mod(d, big.NewInt(1))
   780  
   781  	return new(big.Int).Sub(d, dremainder)
   782  }