github.com/quinndk/ethereum_read@v0.0.0-20181211143958-29c55eec3237/go-ethereum-master_read/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/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/math"
    29  	"github.com/ethereum/go-ethereum/consensus"
    30  	"github.com/ethereum/go-ethereum/consensus/misc"
    31  	"github.com/ethereum/go-ethereum/core/state"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/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(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
    41  	maxUncles                       = 2                 // Maximum number of uncles allowed in a single block
    42  	allowedFutureBlockTime          = 15 * time.Second  // Max time from current time allowed for blocks, before they're considered future blocks
    43  )
    44  
    45  // Various error messages to mark blocks invalid. These should be private to
    46  // prevent engine specific errors from being referenced in the remainder of the
    47  // codebase, inherently breaking if the engine is swapped out. Please put common
    48  // error types into the consensus package.
    49  var (
    50  	errLargeBlockTime    = errors.New("timestamp too big")
    51  	errZeroBlockTime     = errors.New("timestamp equals parent's")
    52  	errTooManyUncles     = errors.New("too many uncles")
    53  	errDuplicateUncle    = errors.New("duplicate uncle")
    54  	errUncleIsAncestor   = errors.New("uncle is ancestor")
    55  	errDanglingUncle     = errors.New("uncle's parent is not ancestor")
    56  	errInvalidDifficulty = errors.New("non-positive difficulty")
    57  	errInvalidMixDigest  = errors.New("invalid mix digest")
    58  	errInvalidPoW        = errors.New("invalid proof-of-work")
    59  )
    60  
    61  // Author implements consensus.Engine, returning the header's coinbase as the
    62  // proof-of-work verified author of the block.
    63  func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
    64  	return header.Coinbase, nil
    65  }
    66  
    67  // VerifyHeader checks whether a header conforms to the consensus rules of the
    68  // stock Ethereum ethash engine.
    69  func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
    70  	// If we're running a full engine faking, accept any input as valid
    71  	if ethash.config.PowMode == ModeFullFake {
    72  		return nil
    73  	}
    74  	// Short circuit if the header is known, or it's parent not
    75  	number := header.Number.Uint64()
    76  	if chain.GetHeader(header.Hash(), number) != nil {
    77  		return nil
    78  	}
    79  	parent := chain.GetHeader(header.ParentHash, number-1)
    80  	if parent == nil {
    81  		return consensus.ErrUnknownAncestor
    82  	}
    83  	// Sanity checks passed, do a proper verification
    84  	return ethash.verifyHeader(chain, header, parent, false, seal)
    85  }
    86  
    87  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
    88  // concurrently. The method returns a quit channel to abort the operations and
    89  // a results channel to retrieve the async verifications.
    90  func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
    91  	// If we're running a full engine faking, accept any input as valid
    92  	if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
    93  		abort, results := make(chan struct{}), make(chan error, len(headers))
    94  		for i := 0; i < len(headers); i++ {
    95  			results <- nil
    96  		}
    97  		return abort, results
    98  	}
    99  
   100  	// Spawn as many workers as allowed threads
   101  	workers := runtime.GOMAXPROCS(0)
   102  	if len(headers) < workers {
   103  		workers = len(headers)
   104  	}
   105  
   106  	// Create a task channel and spawn the verifiers
   107  	var (
   108  		inputs = make(chan int)
   109  		done   = make(chan int, workers)
   110  		errors = make([]error, len(headers))
   111  		abort  = make(chan struct{})
   112  	)
   113  	for i := 0; i < workers; i++ {
   114  		go func() {
   115  			for index := range inputs {
   116  				errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index)
   117  				done <- index
   118  			}
   119  		}()
   120  	}
   121  
   122  	errorsOut := make(chan error, len(headers))
   123  	go func() {
   124  		defer close(inputs)
   125  		var (
   126  			in, out = 0, 0
   127  			checked = make([]bool, len(headers))
   128  			inputs  = inputs
   129  		)
   130  		for {
   131  			select {
   132  			case inputs <- in:
   133  				if in++; in == len(headers) {
   134  					// Reached end of headers. Stop sending to workers.
   135  					inputs = nil
   136  				}
   137  			case index := <-done:
   138  				for checked[index] = true; checked[out]; out++ {
   139  					errorsOut <- errors[out]
   140  					if out == len(headers)-1 {
   141  						return
   142  					}
   143  				}
   144  			case <-abort:
   145  				return
   146  			}
   147  		}
   148  	}()
   149  	return abort, errorsOut
   150  }
   151  
   152  func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainReader, headers []*types.Header, seals []bool, index int) error {
   153  	var parent *types.Header
   154  	if index == 0 {
   155  		parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
   156  	} else if headers[index-1].Hash() == headers[index].ParentHash {
   157  		parent = headers[index-1]
   158  	}
   159  	if parent == nil {
   160  		return consensus.ErrUnknownAncestor
   161  	}
   162  	if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil {
   163  		return nil // known block
   164  	}
   165  	return ethash.verifyHeader(chain, headers[index], parent, false, seals[index])
   166  }
   167  
   168  // VerifyUncles verifies that the given block's uncles conform to the consensus
   169  // rules of the stock Ethereum ethash engine.
   170  func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   171  	// If we're running a full engine faking, accept any input as valid
   172  	if ethash.config.PowMode == ModeFullFake {
   173  		return nil
   174  	}
   175  	// Verify that there are at most 2 uncles included in this block
   176  	if len(block.Uncles()) > maxUncles {
   177  		return errTooManyUncles
   178  	}
   179  	// Gather the set of past uncles and ancestors
   180  	uncles, ancestors := set.New(), make(map[common.Hash]*types.Header)
   181  
   182  	number, parent := block.NumberU64()-1, block.ParentHash()
   183  	for i := 0; i < 7; i++ {
   184  		ancestor := chain.GetBlock(parent, number)
   185  		if ancestor == nil {
   186  			break
   187  		}
   188  		ancestors[ancestor.Hash()] = ancestor.Header()
   189  		for _, uncle := range ancestor.Uncles() {
   190  			uncles.Add(uncle.Hash())
   191  		}
   192  		parent, number = ancestor.ParentHash(), number-1
   193  	}
   194  	ancestors[block.Hash()] = block.Header()
   195  	uncles.Add(block.Hash())
   196  
   197  	// Verify each of the uncles that it's recent, but not an ancestor
   198  	for _, uncle := range block.Uncles() {
   199  		// Make sure every uncle is rewarded only once
   200  		hash := uncle.Hash()
   201  		if uncles.Has(hash) {
   202  			return errDuplicateUncle
   203  		}
   204  		uncles.Add(hash)
   205  
   206  		// Make sure the uncle has a valid ancestry
   207  		if ancestors[hash] != nil {
   208  			return errUncleIsAncestor
   209  		}
   210  		if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
   211  			return errDanglingUncle
   212  		}
   213  		if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
   214  			return err
   215  		}
   216  	}
   217  	return nil
   218  }
   219  
   220  // verifyHeader checks whether a header conforms to the consensus rules of the
   221  // stock Ethereum ethash engine.
   222  // See YP section 4.3.4. "Block Header Validity"
   223  func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error {
   224  	// Ensure that the header's extra-data section is of a reasonable size
   225  	if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
   226  		return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
   227  	}
   228  	// Verify the header's timestamp
   229  	if uncle {
   230  		if header.Time.Cmp(math.MaxBig256) > 0 {
   231  			return errLargeBlockTime
   232  		}
   233  	} else {
   234  		if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 {
   235  			return consensus.ErrFutureBlock
   236  		}
   237  	}
   238  	if header.Time.Cmp(parent.Time) <= 0 {
   239  		return errZeroBlockTime
   240  	}
   241  	// Verify the block's difficulty based in it's timestamp and parent's difficulty
   242  	expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent)
   243  
   244  	if expected.Cmp(header.Difficulty) != 0 {
   245  		return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
   246  	}
   247  	// Verify that the gas limit is <= 2^63-1
   248  	cap := uint64(0x7fffffffffffffff)
   249  	if header.GasLimit > cap {
   250  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   251  	}
   252  	// Verify that the gasUsed is <= gasLimit
   253  	if header.GasUsed > header.GasLimit {
   254  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   255  	}
   256  
   257  	// Verify that the gas limit remains within allowed bounds
   258  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   259  	if diff < 0 {
   260  		diff *= -1
   261  	}
   262  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   263  
   264  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   265  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   266  	}
   267  	// Verify that the block number is parent's +1
   268  	if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
   269  		return consensus.ErrInvalidNumber
   270  	}
   271  	// Verify the engine specific seal securing the block
   272  	if seal {
   273  		if err := ethash.VerifySeal(chain, header); err != nil {
   274  			return err
   275  		}
   276  	}
   277  	// If all checks passed, validate any special fields for hard forks
   278  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   279  		return err
   280  	}
   281  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   282  		return err
   283  	}
   284  	return nil
   285  }
   286  
   287  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   288  // the difficulty that a new block should have when created at time
   289  // given the parent block's time and difficulty.
   290  // 难度调整算法,用来保障出块时间在一个固定值上下波动
   291  func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   292  	return CalcDifficulty(chain.Config(), time, parent)
   293  }
   294  
   295  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   296  // the difficulty that a new block should have when created at time
   297  // given the parent block's time and difficulty.
   298  // 计算在给定父块时间和难度下当前块应该具有的难度
   299  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   300  	next := new(big.Int).Add(parent.Number, big1)
   301  	switch {
   302  	// 以太坊不同阶段难度调整算法不同
   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 = min(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  // Homestead阶段的区块难度调整算法
   386  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   387  	//这里给出了Homestead阶段的当前难度计算规则
   388  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   389  	// algorithm:
   390  	// diff = (parent_diff +
   391  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   392  	//        ) + 2^(periodCount - 2)
   393  	// 2^(periodCount - 2)表示指数难度调整组件
   394  
   395  	// 当前时间
   396  	bigTime := new(big.Int).SetUint64(time)
   397  	// 父块出块时间
   398  	bigParentTime := new(big.Int).Set(parent.Time)
   399  
   400  	// holds intermediate values to make the algo easier to read & audit
   401  	x := new(big.Int)
   402  	y := new(big.Int)
   403  
   404  	// 1 - (block_timestamp - parent_timestamp) // 10
   405  	x.Sub(bigTime, bigParentTime)
   406  	x.Div(x, big10)
   407  	x.Sub(big1, x)
   408  
   409  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   410  	if x.Cmp(bigMinus99) < 0 {
   411  		x.Set(bigMinus99)
   412  	}
   413  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   414  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   415  	x.Mul(y, x)
   416  	x.Add(parent.Difficulty, x)
   417  
   418  	// minimum difficulty can ever be (before exponential factor)
   419  	if x.Cmp(params.MinimumDifficulty) < 0 {
   420  		x.Set(params.MinimumDifficulty)
   421  	}
   422  	// for the exponential factor
   423  	periodCount := new(big.Int).Add(parent.Number, big1)
   424  	periodCount.Div(periodCount, expDiffPeriod)
   425  
   426  	// the exponential factor, commonly referred to as "the bomb"
   427  	// diff = diff + 2^(periodCount - 2)
   428  	if periodCount.Cmp(big1) > 0 {
   429  		y.Sub(periodCount, big2)
   430  		y.Exp(big2, y, nil)
   431  		x.Add(x, y)
   432  	}
   433  	return x
   434  }
   435  
   436  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   437  // difficulty that a new block should have when created at time given the parent
   438  // block's time and difficulty. The calculation uses the Frontier rules.
   439  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   440  	diff := new(big.Int)
   441  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   442  	bigTime := new(big.Int)
   443  	bigParentTime := new(big.Int)
   444  
   445  	bigTime.SetUint64(time)
   446  	bigParentTime.Set(parent.Time)
   447  
   448  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   449  		diff.Add(parent.Difficulty, adjust)
   450  	} else {
   451  		diff.Sub(parent.Difficulty, adjust)
   452  	}
   453  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   454  		diff.Set(params.MinimumDifficulty)
   455  	}
   456  
   457  	periodCount := new(big.Int).Add(parent.Number, big1)
   458  	periodCount.Div(periodCount, expDiffPeriod)
   459  	if periodCount.Cmp(big1) > 0 {
   460  		// diff = diff + 2^(periodCount - 2)
   461  		expDiff := periodCount.Sub(periodCount, big2)
   462  		expDiff.Exp(big2, expDiff, nil)
   463  		diff.Add(diff, expDiff)
   464  		diff = math.BigMax(diff, params.MinimumDifficulty)
   465  	}
   466  	return diff
   467  }
   468  
   469  // VerifySeal implements consensus.Engine, checking whether the given block satisfies
   470  // the PoW difficulty requirements.
   471  func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   472  	// If we're running a fake PoW, accept any seal as valid
   473  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   474  		time.Sleep(ethash.fakeDelay)
   475  		if ethash.fakeFail == header.Number.Uint64() {
   476  			return errInvalidPoW
   477  		}
   478  		return nil
   479  	}
   480  	// If we're running a shared PoW, delegate verification to it
   481  	if ethash.shared != nil {
   482  		return ethash.shared.VerifySeal(chain, header)
   483  	}
   484  	// Ensure that we have a valid difficulty for the block
   485  	if header.Difficulty.Sign() <= 0 {
   486  		return errInvalidDifficulty
   487  	}
   488  	// Recompute the digest and PoW value and verify against the header
   489  	number := header.Number.Uint64()
   490  
   491  	cache := ethash.cache(number)
   492  	size := datasetSize(number)
   493  	if ethash.config.PowMode == ModeTest {
   494  		size = 32 * 1024
   495  	}
   496  	digest, result := hashimotoLight(size, cache.cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64())
   497  	// Caches are unmapped in a finalizer. Ensure that the cache stays live
   498  	// until after the call to hashimotoLight so it's not unmapped while being used.
   499  	runtime.KeepAlive(cache)
   500  
   501  	if !bytes.Equal(header.MixDigest[:], digest) {
   502  		return errInvalidMixDigest
   503  	}
   504  	target := new(big.Int).Div(maxUint256, header.Difficulty)
   505  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   506  		return errInvalidPoW
   507  	}
   508  	return nil
   509  }
   510  
   511  // Prepare implements consensus.Engine, initializing the difficulty field of a
   512  // header to conform to the ethash protocol. The changes are done inline.
   513  // 实现共识引擎的准备阶段
   514  func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
   515  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   516  	if parent == nil {
   517  		return consensus.ErrUnknownAncestor
   518  	}
   519  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent)
   520  	return nil
   521  }
   522  
   523  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   524  // setting the final state and assembling the block.
   525  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) {
   526  	// Accumulate any block and uncle rewards and commit the final state root
   527  	accumulateRewards(chain.Config(), state, header, uncles)
   528  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   529  
   530  	// Header seems complete, assemble into a block and return
   531  	return types.NewBlock(header, txs, uncles, receipts), nil
   532  }
   533  
   534  // Some weird constants to avoid constant memory allocs for them.
   535  var (
   536  	big8  = big.NewInt(8)
   537  	big32 = big.NewInt(32)
   538  )
   539  
   540  // AccumulateRewards credits the coinbase of the given block with the mining
   541  // reward. The total reward consists of the static block reward and rewards for
   542  // included uncles. The coinbase of each uncle block is also rewarded.
   543  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   544  	// Select the correct block reward based on chain progression
   545  	blockReward := FrontierBlockReward
   546  	if config.IsByzantium(header.Number) {
   547  		blockReward = ByzantiumBlockReward
   548  	}
   549  	// Accumulate the rewards for the miner and any included uncles
   550  	reward := new(big.Int).Set(blockReward)
   551  	r := new(big.Int)
   552  	for _, uncle := range uncles {
   553  		r.Add(uncle.Number, big8)
   554  		r.Sub(r, header.Number)
   555  		r.Mul(r, blockReward)
   556  		r.Div(r, big8)
   557  		state.AddBalance(uncle.Coinbase, r)
   558  
   559  		r.Div(blockReward, big32)
   560  		reward.Add(reward, r)
   561  	}
   562  	state.AddBalance(header.Coinbase, reward)
   563  }