github.com/niluplatform/go-nilu@v1.7.4-0.20200912082737-a0cb0776d52c/consensus/ethash/consensus.go (about)

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