github.com/janotchain/janota@v0.0.0-20220824112012-93ea4c5dee78/consensus/ethash/consensus.go (about)

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