github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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  
    22  	"github.com/tacshi/go-ethereum/consensus"
    23  	"github.com/tacshi/go-ethereum/core/state"
    24  	"github.com/tacshi/go-ethereum/core/types"
    25  	"github.com/tacshi/go-ethereum/params"
    26  	"github.com/tacshi/go-ethereum/trie"
    27  )
    28  
    29  // BlockValidator is responsible for validating block headers, uncles and
    30  // processed state.
    31  //
    32  // BlockValidator implements Validator.
    33  type BlockValidator struct {
    34  	config *params.ChainConfig // Chain configuration options
    35  	bc     *BlockChain         // Canonical block chain
    36  	engine consensus.Engine    // Consensus engine used for validating
    37  }
    38  
    39  // NewBlockValidator returns a new block validator which is safe for re-use
    40  func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator {
    41  	validator := &BlockValidator{
    42  		config: config,
    43  		engine: engine,
    44  		bc:     blockchain,
    45  	}
    46  	return validator
    47  }
    48  
    49  // ValidateBody validates the given block's uncles and verifies the block
    50  // header's transaction and uncle roots. The headers are assumed to be already
    51  // validated at this point.
    52  func (v *BlockValidator) ValidateBody(block *types.Block) error {
    53  	// Check whether the block is already imported.
    54  	if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
    55  		return ErrKnownBlock
    56  	}
    57  
    58  	// Header validity is known at this point. Here we verify that uncles, transactions
    59  	// and withdrawals given in the block body match the header.
    60  	header := block.Header()
    61  	if err := v.engine.VerifyUncles(v.bc, block); err != nil {
    62  		return err
    63  	}
    64  	if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
    65  		return fmt.Errorf("uncle root hash mismatch (header value %x, calculated %x)", header.UncleHash, hash)
    66  	}
    67  	if hash := types.DeriveSha(block.Transactions(), trie.NewStackTrie(nil)); hash != header.TxHash {
    68  		return fmt.Errorf("transaction root hash mismatch (header value %x, calculated %x)", header.TxHash, hash)
    69  	}
    70  	// Withdrawals are present after the Shanghai fork.
    71  	if header.WithdrawalsHash != nil {
    72  		// Withdrawals list must be present in body after Shanghai.
    73  		if block.Withdrawals() == nil {
    74  			return fmt.Errorf("missing withdrawals in block body")
    75  		}
    76  		if hash := types.DeriveSha(block.Withdrawals(), trie.NewStackTrie(nil)); hash != *header.WithdrawalsHash {
    77  			return fmt.Errorf("withdrawals root hash mismatch (header value %x, calculated %x)", *header.WithdrawalsHash, hash)
    78  		}
    79  	} else if block.Withdrawals() != nil {
    80  		// Withdrawals are not allowed prior to shanghai fork
    81  		return fmt.Errorf("withdrawals present in block body")
    82  	}
    83  
    84  	if !v.bc.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
    85  		if !v.bc.HasBlock(block.ParentHash(), block.NumberU64()-1) {
    86  			return consensus.ErrUnknownAncestor
    87  		}
    88  		return consensus.ErrPrunedAncestor
    89  	}
    90  	return nil
    91  }
    92  
    93  // ValidateState validates the various changes that happen after a state
    94  // transition, such as amount of used gas, the receipt roots and the state root
    95  // itself. ValidateState returns a database batch if the validation was a success
    96  // otherwise nil and an error is returned.
    97  func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error {
    98  	header := block.Header()
    99  	if block.GasUsed() != usedGas {
   100  		return fmt.Errorf("invalid gas used (remote: %d local: %d)", block.GasUsed(), usedGas)
   101  	}
   102  	// Validate the received block's bloom with the one derived from the generated receipts.
   103  	// For valid blocks this should always validate to true.
   104  	rbloom := types.CreateBloom(receipts)
   105  	if rbloom != header.Bloom {
   106  		return fmt.Errorf("invalid bloom (remote: %x  local: %x)", header.Bloom, rbloom)
   107  	}
   108  	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, Rn]]))
   109  	receiptSha := types.DeriveSha(receipts, trie.NewStackTrie(nil))
   110  	if receiptSha != header.ReceiptHash {
   111  		return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
   112  	}
   113  	// Validate the state root against the received state root and throw
   114  	// an error if they don't match.
   115  	if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
   116  		return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
   117  	}
   118  	return nil
   119  }
   120  
   121  // CalcGasLimit computes the gas limit of the next block after parent. It aims
   122  // to keep the baseline gas close to the provided target, and increase it towards
   123  // the target if the baseline gas is lower.
   124  func CalcGasLimit(parentGasLimit, desiredLimit uint64) uint64 {
   125  	delta := parentGasLimit/params.GasLimitBoundDivisor - 1
   126  	limit := parentGasLimit
   127  	if desiredLimit < params.MinGasLimit {
   128  		desiredLimit = params.MinGasLimit
   129  	}
   130  	// If we're outside our allowed gas range, we try to hone towards them
   131  	if limit < desiredLimit {
   132  		limit = parentGasLimit + delta
   133  		if limit > desiredLimit {
   134  			limit = desiredLimit
   135  		}
   136  		return limit
   137  	}
   138  	if limit > desiredLimit {
   139  		limit = parentGasLimit - delta
   140  		if limit < desiredLimit {
   141  			limit = desiredLimit
   142  		}
   143  	}
   144  	return limit
   145  }