github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/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/ShyftNetwork/go-empyrean/common"
    28  	"github.com/ShyftNetwork/go-empyrean/common/math"
    29  	"github.com/ShyftNetwork/go-empyrean/consensus"
    30  	"github.com/ShyftNetwork/go-empyrean/consensus/misc"
    31  	"github.com/ShyftNetwork/go-empyrean/core/state"
    32  	"github.com/ShyftNetwork/go-empyrean/core/types"
    33  	"github.com/ShyftNetwork/go-empyrean/params"
    34  	"github.com/ShyftNetwork/go-empyrean/rlp"
    35  	mapset "github.com/deckarep/golang-set"
    36  	"golang.org/x/crypto/sha3"
    37  )
    38  
    39  // Ethash proof-of-work protocol constants.
    40  var (
    41  	FrontierBlockReward       = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
    42  	ByzantiumBlockReward      = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
    43  	ConstantinopleBlockReward = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
    44  	maxUncles                 = 2                 // Maximum number of uncles allowed in a single block
    45  	allowedFutureBlockTime    = 15 * time.Second  // Max time from current time allowed for blocks, before they're considered future blocks
    46  	//@Shyft Note: This is the Shyft block reward numbers.
    47  	//
    48  	//
    49  	//								The "Shyft Token Universe" :: The initial and total supply of Shyft Network tokens.
    50  	//
    51  	//								- The total token supply of the Shyft Network is 2,520,000,000 tokens.
    52  	//
    53  	//                              - There is a 5% inflation year over year (initial supply as baseline) to account for both POW mining and network "runtime" (node incentives et al.).
    54  	//								- This is a 2.5% / 2.5% split.
    55  	//								- This results in 28 shyft tokens released per block for the miners and 28 shyft tokens for the network "runtime".
    56  	//
    57  	//								- There is also a 2% inflation year over year (initial supply as baseline) to account for the staking model. This model effectively removes tokens
    58  	//								- from supply over a number of years before the sum total tokens on the market is effectively greater than without this.
    59  	//								- It's purpose is to incentivize new and future participants into the Shyft Network's upper layers.
    60  	//
    61  	//
    62  	// ShyftMinerBlockReward      = Block reward for the miner.
    63  	// ShyftNetworkBlockReward    = Block reward for the shyft conduit contract.
    64  	// ShyftNetworkConduitAddress = Shyft conduit contract
    65  	//								This contract is responsible for distributing Shyft Network tokens to the appropriate places within network as incentives,
    66  	//                              for the node/protocol/wallet interaction space, as well as subsidizing new features, community groups with their own
    67  	//								governance models, bug bounties, marketing initiatives, airdrops etc. :) This will generally point to an instance of
    68  	//								"ShyftConduit.sol" within the network.
    69  	//
    70  	//
    71  	//
    72  	//
    73  	// note: could also be structured as a variable from an "extradata" field in the genesis file, but the most minimal changes is to hardcode it here.
    74  	ShyftMinerBlockReward_v1, _   = new(big.Int).SetString("28000000000000000000", 10) // Block reward component in wei for successfully mining a block, for the miner
    75  	ShyftNetworkBlockReward_v1, _ = new(big.Int).SetString("28000000000000000000", 10) // Block reward component in wei for successfully mining a block, for the Shyft Network
    76  	ShyftBridgeSecurityBlockReward_v1, _   = new(big.Int).SetString("23000000000000000000", 10) // Block reward component in wei for the Shyft Bridge security fee
    77  	//[@note: this is a placeholder address before launch.]
    78  	ShyftNetworkConduitAddress_v1 = common.HexToAddress("9db76b4bbaea76dfda4552b7b9d4e9d43abc55fd") // Smart contract address where the output of this channel leads, for distribution throughout the network
    79  	//[@note: this is a placeholder address before launch.]
    80  	ShyftNetworkBridgeSecurityAddress_v1 = common.HexToAddress("9db76b4bbaea76dfda4552b7b9d4e9d43abc55fd") // Smart contract address where the output of the Shyft Bridge security fee goes. Pointing to the Conduit at the moment
    81  	// calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
    82  	// It returns the difficulty that a new block should have when created at time given the
    83  	// parent block's time and difficulty. The calculation uses the Byzantium rules, but with
    84  	// bomb offset 5M.
    85  	// Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
    86  	calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
    87  
    88  	// calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
    89  	// the difficulty that a new block should have when created at time given the
    90  	// parent block's time and difficulty. The calculation uses the Byzantium rules.
    91  	// Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
    92  	calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
    93  )
    94  
    95  // Various error messages to mark blocks invalid. These should be private to
    96  // prevent engine specific errors from being referenced in the remainder of the
    97  // codebase, inherently breaking if the engine is swapped out. Please put common
    98  // error types into the consensus package.
    99  var (
   100  	errLargeBlockTime    = errors.New("timestamp too big")
   101  	errZeroBlockTime     = errors.New("timestamp equals parent's")
   102  	errTooManyUncles     = errors.New("too many uncles")
   103  	errDuplicateUncle    = errors.New("duplicate uncle")
   104  	errUncleIsAncestor   = errors.New("uncle is ancestor")
   105  	errDanglingUncle     = errors.New("uncle's parent is not ancestor")
   106  	errInvalidDifficulty = errors.New("non-positive difficulty")
   107  	errInvalidMixDigest  = errors.New("invalid mix digest")
   108  	errInvalidPoW        = errors.New("invalid proof-of-work")
   109  )
   110  
   111  // Author implements consensus.Engine, returning the header's coinbase as the
   112  // proof-of-work verified author of the block.
   113  func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
   114  	return header.Coinbase, nil
   115  }
   116  
   117  // VerifyHeader checks whether a header conforms to the consensus rules of the
   118  // stock Ethereum ethash engine.
   119  func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
   120  	// If we're running a full engine faking, accept any input as valid
   121  	if ethash.config.PowMode == ModeFullFake {
   122  		return nil
   123  	}
   124  	// Short circuit if the header is known, or it's parent not
   125  	number := header.Number.Uint64()
   126  	if chain.GetHeader(header.Hash(), number) != nil {
   127  		return nil
   128  	}
   129  	parent := chain.GetHeader(header.ParentHash, number-1)
   130  	if parent == nil {
   131  		return consensus.ErrUnknownAncestor
   132  	}
   133  	// Sanity checks passed, do a proper verification
   134  	return ethash.verifyHeader(chain, header, parent, false, seal)
   135  }
   136  
   137  // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
   138  // concurrently. The method returns a quit channel to abort the operations and
   139  // a results channel to retrieve the async verifications.
   140  func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
   141  	// If we're running a full engine faking, accept any input as valid
   142  	if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
   143  		abort, results := make(chan struct{}), make(chan error, len(headers))
   144  		for i := 0; i < len(headers); i++ {
   145  			results <- nil
   146  		}
   147  		return abort, results
   148  	}
   149  
   150  	// Spawn as many workers as allowed threads
   151  	workers := runtime.GOMAXPROCS(0)
   152  	if len(headers) < workers {
   153  		workers = len(headers)
   154  	}
   155  
   156  	// Create a task channel and spawn the verifiers
   157  	var (
   158  		inputs = make(chan int)
   159  		done   = make(chan int, workers)
   160  		errors = make([]error, len(headers))
   161  		abort  = make(chan struct{})
   162  	)
   163  	for i := 0; i < workers; i++ {
   164  		go func() {
   165  			for index := range inputs {
   166  				errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index)
   167  				done <- index
   168  			}
   169  		}()
   170  	}
   171  
   172  	errorsOut := make(chan error, len(headers))
   173  	go func() {
   174  		defer close(inputs)
   175  		var (
   176  			in, out = 0, 0
   177  			checked = make([]bool, len(headers))
   178  			inputs  = inputs
   179  		)
   180  		for {
   181  			select {
   182  			case inputs <- in:
   183  				if in++; in == len(headers) {
   184  					// Reached end of headers. Stop sending to workers.
   185  					inputs = nil
   186  				}
   187  			case index := <-done:
   188  				for checked[index] = true; checked[out]; out++ {
   189  					errorsOut <- errors[out]
   190  					if out == len(headers)-1 {
   191  						return
   192  					}
   193  				}
   194  			case <-abort:
   195  				return
   196  			}
   197  		}
   198  	}()
   199  	return abort, errorsOut
   200  }
   201  
   202  func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainReader, headers []*types.Header, seals []bool, index int) error {
   203  	var parent *types.Header
   204  	if index == 0 {
   205  		parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
   206  	} else if headers[index-1].Hash() == headers[index].ParentHash {
   207  		parent = headers[index-1]
   208  	}
   209  	if parent == nil {
   210  		return consensus.ErrUnknownAncestor
   211  	}
   212  	if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil {
   213  		return nil // known block
   214  	}
   215  	return ethash.verifyHeader(chain, headers[index], parent, false, seals[index])
   216  }
   217  
   218  // VerifyUncles verifies that the given block's uncles conform to the consensus
   219  // rules of the stock Ethereum ethash engine.
   220  func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
   221  	// If we're running a full engine faking, accept any input as valid
   222  	if ethash.config.PowMode == ModeFullFake {
   223  		return nil
   224  	}
   225  	// Verify that there are at most 2 uncles included in this block
   226  	if len(block.Uncles()) > maxUncles {
   227  		return errTooManyUncles
   228  	}
   229  	// Gather the set of past uncles and ancestors
   230  	uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
   231  
   232  	number, parent := block.NumberU64()-1, block.ParentHash()
   233  	for i := 0; i < 7; i++ {
   234  		ancestor := chain.GetBlock(parent, number)
   235  		if ancestor == nil {
   236  			break
   237  		}
   238  		ancestors[ancestor.Hash()] = ancestor.Header()
   239  		for _, uncle := range ancestor.Uncles() {
   240  			uncles.Add(uncle.Hash())
   241  		}
   242  		parent, number = ancestor.ParentHash(), number-1
   243  	}
   244  	ancestors[block.Hash()] = block.Header()
   245  	uncles.Add(block.Hash())
   246  
   247  	// Verify each of the uncles that it's recent, but not an ancestor
   248  	for _, uncle := range block.Uncles() {
   249  		// Make sure every uncle is rewarded only once
   250  		hash := uncle.Hash()
   251  		if uncles.Contains(hash) {
   252  			return errDuplicateUncle
   253  		}
   254  		uncles.Add(hash)
   255  
   256  		// Make sure the uncle has a valid ancestry
   257  		if ancestors[hash] != nil {
   258  			return errUncleIsAncestor
   259  		}
   260  		if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
   261  			return errDanglingUncle
   262  		}
   263  		if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
   264  			return err
   265  		}
   266  	}
   267  	return nil
   268  }
   269  
   270  // verifyHeader checks whether a header conforms to the consensus rules of the
   271  // stock Ethereum ethash engine.
   272  // See YP section 4.3.4. "Block Header Validity"
   273  func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error {
   274  	// Ensure that the header's extra-data section is of a reasonable size
   275  	if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
   276  		return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
   277  	}
   278  	// Verify the header's timestamp
   279  	if uncle {
   280  		if header.Time.Cmp(math.MaxBig256) > 0 {
   281  			return errLargeBlockTime
   282  		}
   283  	} else {
   284  		if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 {
   285  			return consensus.ErrFutureBlock
   286  		}
   287  	}
   288  	if header.Time.Cmp(parent.Time) <= 0 {
   289  		return errZeroBlockTime
   290  	}
   291  	// Verify the block's difficulty based in it's timestamp and parent's difficulty
   292  	expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent)
   293  
   294  	if expected.Cmp(header.Difficulty) != 0 {
   295  		return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
   296  	}
   297  	// Verify that the gas limit is <= 2^63-1
   298  	cap := uint64(0x7fffffffffffffff)
   299  	if header.GasLimit > cap {
   300  		return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
   301  	}
   302  	// Verify that the gasUsed is <= gasLimit
   303  	if header.GasUsed > header.GasLimit {
   304  		return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
   305  	}
   306  
   307  	// Verify that the gas limit remains within allowed bounds
   308  	diff := int64(parent.GasLimit) - int64(header.GasLimit)
   309  	if diff < 0 {
   310  		diff *= -1
   311  	}
   312  	limit := parent.GasLimit / params.GasLimitBoundDivisor
   313  
   314  	if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
   315  		return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
   316  	}
   317  	// Verify that the block number is parent's +1
   318  	if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
   319  		return consensus.ErrInvalidNumber
   320  	}
   321  	// Verify the engine specific seal securing the block
   322  	if seal {
   323  		if err := ethash.VerifySeal(chain, header); err != nil {
   324  			return err
   325  		}
   326  	}
   327  	// If all checks passed, validate any special fields for hard forks
   328  	if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
   329  		return err
   330  	}
   331  	if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
   332  		return err
   333  	}
   334  	return nil
   335  }
   336  
   337  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   338  // the difficulty that a new block should have when created at time
   339  // given the parent block's time and difficulty.
   340  func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   341  	return CalcDifficulty(chain.Config(), time, parent)
   342  }
   343  
   344  // CalcDifficulty is the difficulty adjustment algorithm. It returns
   345  // the difficulty that a new block should have when created at time
   346  // given the parent block's time and difficulty.
   347  func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
   348  	next := new(big.Int).Add(parent.Number, big1)
   349  	switch {
   350  	case config.IsConstantinople(next):
   351  		return calcDifficultyConstantinople(time, parent)
   352  	case config.IsByzantium(next):
   353  		return calcDifficultyByzantium(time, parent)
   354  	case config.IsHomestead(next):
   355  		return calcDifficultyHomestead(time, parent)
   356  	default:
   357  		return calcDifficultyFrontier(time, parent)
   358  	}
   359  }
   360  
   361  // Some weird constants to avoid constant memory allocs for them.
   362  var (
   363  	expDiffPeriod = big.NewInt(100000)
   364  	big1          = big.NewInt(1)
   365  	big2          = big.NewInt(2)
   366  	big9          = big.NewInt(9)
   367  	big10         = big.NewInt(10)
   368  	bigMinus99    = big.NewInt(-99)
   369  )
   370  
   371  // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
   372  // the difficulty is calculated with Byzantium rules, which differs from Homestead in
   373  // how uncles affect the calculation
   374  func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
   375  	// Note, the calculations below looks at the parent number, which is 1 below
   376  	// the block number. Thus we remove one from the delay given
   377  	bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
   378  	return func(time uint64, parent *types.Header) *big.Int {
   379  		// https://github.com/ethereum/EIPs/issues/100.
   380  		// algorithm:
   381  		// diff = (parent_diff +
   382  		//         (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   383  		//        ) + 2^(periodCount - 2)
   384  
   385  		bigTime := new(big.Int).SetUint64(time)
   386  		bigParentTime := new(big.Int).Set(parent.Time)
   387  
   388  		// holds intermediate values to make the algo easier to read & audit
   389  		x := new(big.Int)
   390  		y := new(big.Int)
   391  
   392  		// (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
   393  		x.Sub(bigTime, bigParentTime)
   394  		x.Div(x, big9)
   395  		if parent.UncleHash == types.EmptyUncleHash {
   396  			x.Sub(big1, x)
   397  		} else {
   398  			x.Sub(big2, x)
   399  		}
   400  		// max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
   401  		if x.Cmp(bigMinus99) < 0 {
   402  			x.Set(bigMinus99)
   403  		}
   404  		// parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
   405  		y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   406  		x.Mul(y, x)
   407  		x.Add(parent.Difficulty, x)
   408  
   409  		// minimum difficulty can ever be (before exponential factor)
   410  		if x.Cmp(params.MinimumDifficulty) < 0 {
   411  			x.Set(params.MinimumDifficulty)
   412  		}
   413  		// calculate a fake block number for the ice-age delay
   414  		// Specification: https://eips.ethereum.org/EIPS/eip-1234
   415  		fakeBlockNumber := new(big.Int)
   416  		if parent.Number.Cmp(bombDelayFromParent) >= 0 {
   417  			fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
   418  		}
   419  		// for the exponential factor
   420  		periodCount := fakeBlockNumber
   421  		periodCount.Div(periodCount, expDiffPeriod)
   422  
   423  		// the exponential factor, commonly referred to as "the bomb"
   424  		// diff = diff + 2^(periodCount - 2)
   425  		if periodCount.Cmp(big1) > 0 {
   426  			y.Sub(periodCount, big2)
   427  			y.Exp(big2, y, nil)
   428  			x.Add(x, y)
   429  		}
   430  		return x
   431  	}
   432  }
   433  
   434  // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
   435  // the difficulty that a new block should have when created at time given the
   436  // parent block's time and difficulty. The calculation uses the Homestead rules.
   437  func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
   438  	// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
   439  	// algorithm:
   440  	// diff = (parent_diff +
   441  	//         (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   442  	//        ) + 2^(periodCount - 2)
   443  
   444  	bigTime := new(big.Int).SetUint64(time)
   445  	bigParentTime := new(big.Int).Set(parent.Time)
   446  
   447  	// holds intermediate values to make the algo easier to read & audit
   448  	x := new(big.Int)
   449  	y := new(big.Int)
   450  
   451  	// 1 - (block_timestamp - parent_timestamp) // 10
   452  	x.Sub(bigTime, bigParentTime)
   453  	x.Div(x, big10)
   454  	x.Sub(big1, x)
   455  
   456  	// max(1 - (block_timestamp - parent_timestamp) // 10, -99)
   457  	if x.Cmp(bigMinus99) < 0 {
   458  		x.Set(bigMinus99)
   459  	}
   460  	// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
   461  	y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
   462  	x.Mul(y, x)
   463  	x.Add(parent.Difficulty, x)
   464  
   465  	// minimum difficulty can ever be (before exponential factor)
   466  	if x.Cmp(params.MinimumDifficulty) < 0 {
   467  		x.Set(params.MinimumDifficulty)
   468  	}
   469  	// for the exponential factor
   470  	periodCount := new(big.Int).Add(parent.Number, big1)
   471  	periodCount.Div(periodCount, expDiffPeriod)
   472  
   473  	// the exponential factor, commonly referred to as "the bomb"
   474  	// diff = diff + 2^(periodCount - 2)
   475  	if periodCount.Cmp(big1) > 0 {
   476  		y.Sub(periodCount, big2)
   477  		y.Exp(big2, y, nil)
   478  		x.Add(x, y)
   479  	}
   480  	return x
   481  }
   482  
   483  // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
   484  // difficulty that a new block should have when created at time given the parent
   485  // block's time and difficulty. The calculation uses the Frontier rules.
   486  func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
   487  	diff := new(big.Int)
   488  	adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
   489  	bigTime := new(big.Int)
   490  	bigParentTime := new(big.Int)
   491  
   492  	bigTime.SetUint64(time)
   493  	bigParentTime.Set(parent.Time)
   494  
   495  	if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
   496  		diff.Add(parent.Difficulty, adjust)
   497  	} else {
   498  		diff.Sub(parent.Difficulty, adjust)
   499  	}
   500  	if diff.Cmp(params.MinimumDifficulty) < 0 {
   501  		diff.Set(params.MinimumDifficulty)
   502  	}
   503  
   504  	periodCount := new(big.Int).Add(parent.Number, big1)
   505  	periodCount.Div(periodCount, expDiffPeriod)
   506  	if periodCount.Cmp(big1) > 0 {
   507  		// diff = diff + 2^(periodCount - 2)
   508  		expDiff := periodCount.Sub(periodCount, big2)
   509  		expDiff.Exp(big2, expDiff, nil)
   510  		diff.Add(diff, expDiff)
   511  		diff = math.BigMax(diff, params.MinimumDifficulty)
   512  	}
   513  	return diff
   514  }
   515  
   516  // VerifySeal implements consensus.Engine, checking whether the given block satisfies
   517  // the PoW difficulty requirements.
   518  func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
   519  	return ethash.verifySeal(chain, header, false)
   520  }
   521  
   522  // verifySeal checks whether a block satisfies the PoW difficulty requirements,
   523  // either using the usual ethash cache for it, or alternatively using a full DAG
   524  // to make remote mining fast.
   525  func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Header, fulldag bool) error {
   526  	// If we're running a fake PoW, accept any seal as valid
   527  	if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
   528  		time.Sleep(ethash.fakeDelay)
   529  		if ethash.fakeFail == header.Number.Uint64() {
   530  			return errInvalidPoW
   531  		}
   532  		return nil
   533  	}
   534  	// If we're running a shared PoW, delegate verification to it
   535  	if ethash.shared != nil {
   536  		return ethash.shared.verifySeal(chain, header, fulldag)
   537  	}
   538  	// Ensure that we have a valid difficulty for the block
   539  	if header.Difficulty.Sign() <= 0 {
   540  		return errInvalidDifficulty
   541  	}
   542  	// Recompute the digest and PoW values
   543  	number := header.Number.Uint64()
   544  
   545  	var (
   546  		digest []byte
   547  		result []byte
   548  	)
   549  	// If fast-but-heavy PoW verification was requested, use an ethash dataset
   550  	if fulldag {
   551  		dataset := ethash.dataset(number, true)
   552  		if dataset.generated() {
   553  			digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   554  
   555  			// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
   556  			// until after the call to hashimotoFull so it's not unmapped while being used.
   557  			runtime.KeepAlive(dataset)
   558  		} else {
   559  			// Dataset not yet generated, don't hang, use a cache instead
   560  			fulldag = false
   561  		}
   562  	}
   563  	// If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
   564  	if !fulldag {
   565  		cache := ethash.cache(number)
   566  
   567  		size := datasetSize(number)
   568  		if ethash.config.PowMode == ModeTest {
   569  			size = 32 * 1024
   570  		}
   571  		digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
   572  
   573  		// Caches are unmapped in a finalizer. Ensure that the cache stays alive
   574  		// until after the call to hashimotoLight so it's not unmapped while being used.
   575  		runtime.KeepAlive(cache)
   576  	}
   577  	// Verify the calculated values against the ones provided in the header
   578  	if !bytes.Equal(header.MixDigest[:], digest) {
   579  		return errInvalidMixDigest
   580  	}
   581  	target := new(big.Int).Div(two256, header.Difficulty)
   582  	if new(big.Int).SetBytes(result).Cmp(target) > 0 {
   583  		return errInvalidPoW
   584  	}
   585  	return nil
   586  }
   587  
   588  // Prepare implements consensus.Engine, initializing the difficulty field of a
   589  // header to conform to the ethash protocol. The changes are done inline.
   590  func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
   591  	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   592  	if parent == nil {
   593  		return consensus.ErrUnknownAncestor
   594  	}
   595  	header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent)
   596  	return nil
   597  }
   598  
   599  // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
   600  // setting the final state and assembling the block.
   601  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) {
   602  	// Accumulate any block and uncle rewards and commit the final state root
   603  	accumulateRewards(chain.Config(), state, header, uncles)
   604  	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
   605  
   606  	// Header seems complete, assemble into a block and return
   607  	return types.NewBlock(header, txs, uncles, receipts), nil
   608  }
   609  
   610  // SealHash returns the hash of a block prior to it being sealed.
   611  func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
   612  	hasher := sha3.NewLegacyKeccak256()
   613  
   614  	rlp.Encode(hasher, []interface{}{
   615  		header.ParentHash,
   616  		header.UncleHash,
   617  		header.Coinbase,
   618  		header.Root,
   619  		header.TxHash,
   620  		header.ReceiptHash,
   621  		header.Bloom,
   622  		header.Difficulty,
   623  		header.Number,
   624  		header.GasLimit,
   625  		header.GasUsed,
   626  		header.Time,
   627  		header.Extra,
   628  	})
   629  	hasher.Sum(hash[:0])
   630  	return hash
   631  }
   632  
   633  // Some weird constants to avoid constant memory allocs for them.
   634  var (
   635  	big8  = big.NewInt(8)
   636  	big32 = big.NewInt(32)
   637  )
   638  
   639  // AccumulateRewards credits the coinbase of the given block with the mining
   640  // reward. The total reward consists of the static block reward and rewards for
   641  // included uncles. The coinbase of each uncle block is also rewarded.
   642  func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
   643  	//@Shyft Note: Use Shyft's block rewards
   644  	blockReward := ShyftMinerBlockReward_v1
   645  
   646  	// Accumulate the rewards for the miner and any included uncles
   647  	reward := new(big.Int).Set(blockReward)
   648  	r := new(big.Int)
   649  	for _, uncle := range uncles {
   650  		r.Add(uncle.Number, big8)
   651  		r.Sub(r, header.Number)
   652  		r.Mul(r, blockReward)
   653  		r.Div(r, big8)
   654  		state.AddBalance(uncle.Coinbase, r)
   655  
   656  		r.Div(blockReward, big32)
   657  		reward.Add(reward, r)
   658  	}
   659  	state.AddBalance(header.Coinbase, reward)
   660  
   661  	//@Shyft Note: allocate the shyft block reward for network "runtime".
   662  	state.AddBalance(ShyftNetworkConduitAddress_v1, ShyftNetworkBlockReward_v1)
   663  	//@Shyft Note: allocate the shyft block reward for the shyft bridge security fee.
   664  	state.AddBalance(ShyftNetworkBridgeSecurityAddress_v1, ShyftBridgeSecurityBlockReward_v1)
   665  
   666  }