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