github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/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/ethereum/go-ethereum/consensus"
    24  	"github.com/ethereum/go-ethereum/core/state"
    25  	"github.com/ethereum/go-ethereum/core/types"
    26  	"github.com/ethereum/go-ethereum/params"
    27  	"github.com/ethereum/go-ethereum/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) 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 statedb.IsPipeCommit() {
   139  		validateFuns = append(validateFuns, func() error {
   140  			if err := statedb.WaitPipeVerification(); err != nil {
   141  				return err
   142  			}
   143  			statedb.CorrectAccountsRoot()
   144  			statedb.Finalise(v.config.IsEIP158(header.Number))
   145  			// State verification pipeline - accounts root are not calculated here, just populate needed fields for process
   146  			statedb.PopulateSnapAccountAndStorage()
   147  			return nil
   148  		})
   149  	} else {
   150  		validateFuns = append(validateFuns, func() error {
   151  			if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
   152  				return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
   153  			}
   154  			return nil
   155  		})
   156  	}
   157  	validateRes := make(chan error, len(validateFuns))
   158  	for _, f := range validateFuns {
   159  		tmpFunc := f
   160  		go func() {
   161  			validateRes <- tmpFunc()
   162  		}()
   163  	}
   164  
   165  	var err error
   166  	for i := 0; i < len(validateFuns); i++ {
   167  		r := <-validateRes
   168  		if r != nil && err == nil {
   169  			err = r
   170  		}
   171  	}
   172  	return err
   173  }
   174  
   175  // CalcGasLimit computes the gas limit of the next block after parent. It aims
   176  // to keep the baseline gas above the provided floor, and increase it towards the
   177  // ceil if the blocks are full. If the ceil is exceeded, it will always decrease
   178  // the gas allowance.
   179  func CalcGasLimit(parent *types.Block, gasFloor, gasCeil uint64) uint64 {
   180  	// contrib = (parentGasUsed * 3 / 2) / 256
   181  	contrib := (parent.GasUsed() + parent.GasUsed()/2) / params.GasLimitBoundDivisor
   182  
   183  	// decay = parentGasLimit / 256 -1
   184  	decay := parent.GasLimit()/params.GasLimitBoundDivisor - 1
   185  
   186  	/*
   187  		strategy: gasLimit of block-to-mine is set based on parent's
   188  		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
   189  		increase it, otherwise lower it (or leave it unchanged if it's right
   190  		at that usage) the amount increased/decreased depends on how far away
   191  		from parentGasLimit * (2/3) parentGasUsed is.
   192  	*/
   193  	limit := parent.GasLimit() - decay + contrib
   194  	if limit < params.MinGasLimit {
   195  		limit = params.MinGasLimit
   196  	}
   197  	// If we're outside our allowed gas range, we try to hone towards them
   198  	if limit < gasFloor {
   199  		limit = parent.GasLimit() + decay
   200  		if limit > gasFloor {
   201  			limit = gasFloor
   202  		}
   203  	} else if limit > gasCeil {
   204  		limit = parent.GasLimit() - decay
   205  		if limit < gasCeil {
   206  			limit = gasCeil
   207  		}
   208  	}
   209  	return limit
   210  }