github.com/fff-chain/go-fff@v0.0.0-20220726032732-1c84420b8a99/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  	"time"
    22  
    23  	"github.com/fff-chain/go-fff/consensus"
    24  	"github.com/fff-chain/go-fff/core/state"
    25  	"github.com/fff-chain/go-fff/core/types"
    26  	"github.com/fff-chain/go-fff/params"
    27  	"github.com/fff-chain/go-fff/trie"
    28  )
    29  
    30  const badBlockCacheExpire = 30 * time.Second
    31  
    32  // BlockValidator is responsible for validating block headers, uncles and
    33  // processed state.
    34  //
    35  // BlockValidator implements Validator.
    36  type BlockValidator struct {
    37  	config *params.ChainConfig // Chain configuration options
    38  	bc     *BlockChain         // Canonical block chain
    39  	engine consensus.Engine    // Consensus engine used for validating
    40  }
    41  
    42  // NewBlockValidator returns a new block validator which is safe for re-use
    43  func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator {
    44  	validator := &BlockValidator{
    45  		config: config,
    46  		engine: engine,
    47  		bc:     blockchain,
    48  	}
    49  	return validator
    50  }
    51  
    52  // ValidateBody validates the given block's uncles and verifies the block
    53  // header's transaction and uncle roots. The headers are assumed to be already
    54  // validated at this point.
    55  func (v *BlockValidator) ValidateBody(block *types.Block) error {
    56  	// Check whether the block's known, and if not, that it's linkable
    57  	if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
    58  		return ErrKnownBlock
    59  	}
    60  	if v.bc.isCachedBadBlock(block) {
    61  		return ErrKnownBadBlock
    62  	}
    63  	// Header validity is known at this point, check the uncles and transactions
    64  	header := block.Header()
    65  	if err := v.engine.VerifyUncles(v.bc, block); err != nil {
    66  		return err
    67  	}
    68  	if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
    69  		return fmt.Errorf("uncle root hash mismatch: have %x, want %x", hash, header.UncleHash)
    70  	}
    71  
    72  	validateFuns := []func() error{
    73  		func() error {
    74  			if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
    75  				return ErrKnownBlock
    76  			}
    77  			return nil
    78  		},
    79  		func() error {
    80  			if hash := types.DeriveSha(block.Transactions(), trie.NewStackTrie(nil)); hash != header.TxHash {
    81  				return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
    82  			}
    83  			return nil
    84  		},
    85  		func() error {
    86  			if !v.bc.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
    87  				if !v.bc.HasBlock(block.ParentHash(), block.NumberU64()-1) {
    88  					return consensus.ErrUnknownAncestor
    89  				}
    90  				return consensus.ErrPrunedAncestor
    91  			}
    92  			return nil
    93  		},
    94  	}
    95  	validateRes := make(chan error, len(validateFuns))
    96  	for _, f := range validateFuns {
    97  		tmpFunc := f
    98  		go func() {
    99  			validateRes <- tmpFunc()
   100  		}()
   101  	}
   102  	for i := 0; i < len(validateFuns); i++ {
   103  		r := <-validateRes
   104  		if r != nil {
   105  			return r
   106  		}
   107  	}
   108  	return nil
   109  }
   110  
   111  // ValidateState validates the various changes that happen after a state
   112  // transition, such as amount of used gas, the receipt roots and the state root
   113  // itself. ValidateState returns a database batch if the validation was a success
   114  // otherwise nil and an error is returned.
   115  func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64, skipHeavyVerify bool) error {
   116  	header := block.Header()
   117  	if block.GasUsed() != usedGas {
   118  		return fmt.Errorf("invalid gas used (remote: %d local: %d)", block.GasUsed(), usedGas)
   119  	}
   120  	// Validate the received block's bloom with the one derived from the generated receipts.
   121  	// For valid blocks this should always validate to true.
   122  	validateFuns := []func() error{
   123  		func() error {
   124  			rbloom := types.CreateBloom(receipts)
   125  			if rbloom != header.Bloom {
   126  				return fmt.Errorf("invalid bloom (remote: %x  local: %x)", header.Bloom, rbloom)
   127  			}
   128  			return nil
   129  		},
   130  		func() error {
   131  			receiptSha := types.DeriveSha(receipts, trie.NewStackTrie(nil))
   132  			if receiptSha != header.ReceiptHash {
   133  				return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
   134  			}
   135  			return nil
   136  		},
   137  	}
   138  	if skipHeavyVerify {
   139  		validateFuns = append(validateFuns, func() error {
   140  			if err := statedb.WaitPipeVerification(); err != nil {
   141  				return err
   142  			}
   143  			statedb.Finalise(v.config.IsEIP158(header.Number))
   144  			statedb.AccountsIntermediateRoot()
   145  			return nil
   146  		})
   147  	} else {
   148  		validateFuns = append(validateFuns, func() error {
   149  			if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
   150  				return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
   151  			}
   152  			return nil
   153  		})
   154  	}
   155  	validateRes := make(chan error, len(validateFuns))
   156  	for _, f := range validateFuns {
   157  		tmpFunc := f
   158  		go func() {
   159  			validateRes <- tmpFunc()
   160  		}()
   161  	}
   162  
   163  	var err error
   164  	for i := 0; i < len(validateFuns); i++ {
   165  		r := <-validateRes
   166  		if r != nil && err == nil {
   167  			err = r
   168  		}
   169  	}
   170  	return err
   171  }
   172  
   173  // CalcGasLimit computes the gas limit of the next block after parent. It aims
   174  // to keep the baseline gas above the provided floor, and increase it towards the
   175  // ceil if the blocks are full. If the ceil is exceeded, it will always decrease
   176  // the gas allowance.
   177  func CalcGasLimit(parent *types.Block, gasFloor, gasCeil uint64) uint64 {
   178  	// contrib = (parentGasUsed * 3 / 2) / 256
   179  	contrib := (parent.GasUsed() + parent.GasUsed()/2) / params.GasLimitBoundDivisor
   180  
   181  	// decay = parentGasLimit / 256 -1
   182  	decay := parent.GasLimit()/params.GasLimitBoundDivisor - 1
   183  
   184  	/*
   185  		strategy: gasLimit of block-to-mine is set based on parent's
   186  		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
   187  		increase it, otherwise lower it (or leave it unchanged if it's right
   188  		at that usage) the amount increased/decreased depends on how far away
   189  		from parentGasLimit * (2/3) parentGasUsed is.
   190  	*/
   191  	limit := parent.GasLimit() - decay + contrib
   192  	if limit < params.MinGasLimit {
   193  		limit = params.MinGasLimit
   194  	}
   195  	// If we're outside our allowed gas range, we try to hone towards them
   196  	if limit < gasFloor {
   197  		limit = parent.GasLimit() + decay
   198  		if limit > gasFloor {
   199  			limit = gasFloor
   200  		}
   201  	} else if limit > gasCeil {
   202  		limit = parent.GasLimit() - decay
   203  		if limit < gasCeil {
   204  			limit = gasCeil
   205  		}
   206  	}
   207  	return limit
   208  }