github.com/ylsgit/go-ethereum@v1.6.5/core/block_validator.go (about)

     1  // Copyright 2015 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 core
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  
    23  	"github.com/ethereum/go-ethereum/common/math"
    24  	"github.com/ethereum/go-ethereum/consensus"
    25  	"github.com/ethereum/go-ethereum/core/state"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/params"
    28  )
    29  
    30  // BlockValidator is responsible for validating block headers, uncles and
    31  // processed state.
    32  //
    33  // BlockValidator implements Validator.
    34  type BlockValidator struct {
    35  	config *params.ChainConfig // Chain configuration options
    36  	bc     *BlockChain         // Canonical block chain
    37  	engine consensus.Engine    // Consensus engine used for validating
    38  }
    39  
    40  // NewBlockValidator returns a new block validator which is safe for re-use
    41  func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator {
    42  	validator := &BlockValidator{
    43  		config: config,
    44  		engine: engine,
    45  		bc:     blockchain,
    46  	}
    47  	return validator
    48  }
    49  
    50  // ValidateBody validates the given block's uncles and verifies the the block
    51  // header's transaction and uncle roots. The headers are assumed to be already
    52  // validated at this point.
    53  func (v *BlockValidator) ValidateBody(block *types.Block) error {
    54  	// Check whether the block's known, and if not, that it's linkable
    55  	if v.bc.HasBlock(block.Hash()) {
    56  		if _, err := state.New(block.Root(), v.bc.chainDb); err == nil {
    57  			return ErrKnownBlock
    58  		}
    59  	}
    60  	parent := v.bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
    61  	if parent == nil {
    62  		return consensus.ErrUnknownAncestor
    63  	}
    64  	if _, err := state.New(parent.Root(), v.bc.chainDb); err != nil {
    65  		return consensus.ErrUnknownAncestor
    66  	}
    67  	// Header validity is known at this point, check the uncles and transactions
    68  	header := block.Header()
    69  	if err := v.engine.VerifyUncles(v.bc, block); err != nil {
    70  		return err
    71  	}
    72  	if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
    73  		return fmt.Errorf("uncle root hash mismatch: have %x, want %x", hash, header.UncleHash)
    74  	}
    75  	if hash := types.DeriveSha(block.Transactions()); hash != header.TxHash {
    76  		return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
    77  	}
    78  	return nil
    79  }
    80  
    81  // ValidateState validates the various changes that happen after a state
    82  // transition, such as amount of used gas, the receipt roots and the state root
    83  // itself. ValidateState returns a database batch if the validation was a success
    84  // otherwise nil and an error is returned.
    85  func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas *big.Int) error {
    86  	header := block.Header()
    87  	if block.GasUsed().Cmp(usedGas) != 0 {
    88  		return fmt.Errorf("invalid gas used (remote: %v local: %v)", block.GasUsed(), usedGas)
    89  	}
    90  	// Validate the received block's bloom with the one derived from the generated receipts.
    91  	// For valid blocks this should always validate to true.
    92  	rbloom := types.CreateBloom(receipts)
    93  	if rbloom != header.Bloom {
    94  		return fmt.Errorf("invalid bloom (remote: %x  local: %x)", header.Bloom, rbloom)
    95  	}
    96  	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
    97  	receiptSha := types.DeriveSha(receipts)
    98  	if receiptSha != header.ReceiptHash {
    99  		return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
   100  	}
   101  	// Validate the state root against the received state root and throw
   102  	// an error if they don't match.
   103  	if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
   104  		return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
   105  	}
   106  	return nil
   107  }
   108  
   109  // CalcGasLimit computes the gas limit of the next block after parent.
   110  // The result may be modified by the caller.
   111  // This is miner strategy, not consensus protocol.
   112  func CalcGasLimit(parent *types.Block) *big.Int {
   113  	// contrib = (parentGasUsed * 3 / 2) / 1024
   114  	contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
   115  	contrib = contrib.Div(contrib, big.NewInt(2))
   116  	contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
   117  
   118  	// decay = parentGasLimit / 1024 -1
   119  	decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
   120  	decay.Sub(decay, big.NewInt(1))
   121  
   122  	/*
   123  		strategy: gasLimit of block-to-mine is set based on parent's
   124  		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
   125  		increase it, otherwise lower it (or leave it unchanged if it's right
   126  		at that usage) the amount increased/decreased depends on how far away
   127  		from parentGasLimit * (2/3) parentGasUsed is.
   128  	*/
   129  	gl := new(big.Int).Sub(parent.GasLimit(), decay)
   130  	gl = gl.Add(gl, contrib)
   131  	gl.Set(math.BigMax(gl, params.MinGasLimit))
   132  
   133  	// however, if we're now below the target (TargetGasLimit) we increase the
   134  	// limit as much as we can (parentGasLimit / 1024 -1)
   135  	if gl.Cmp(params.TargetGasLimit) < 0 {
   136  		gl.Add(parent.GasLimit(), decay)
   137  		gl.Set(math.BigMin(gl, params.TargetGasLimit))
   138  	}
   139  	return gl
   140  }