github.com/theQRL/go-zond@v0.1.1/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  	"errors"
    21  	"fmt"
    22  
    23  	"github.com/theQRL/go-zond/consensus"
    24  	"github.com/theQRL/go-zond/core/state"
    25  	"github.com/theQRL/go-zond/core/types"
    26  	"github.com/theQRL/go-zond/params"
    27  	"github.com/theQRL/go-zond/trie"
    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 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 is already imported.
    55  	if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
    56  		return ErrKnownBlock
    57  	}
    58  
    59  	// Header validity is known at this point. Here we verify that uncles, transactions
    60  	// and withdrawals given in the block body match the header.
    61  	header := block.Header()
    62  	if err := v.engine.VerifyUncles(v.bc, block); err != nil {
    63  		return err
    64  	}
    65  	if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
    66  		return fmt.Errorf("uncle root hash mismatch (header value %x, calculated %x)", header.UncleHash, hash)
    67  	}
    68  	if hash := types.DeriveSha(block.Transactions(), trie.NewStackTrie(nil)); hash != header.TxHash {
    69  		return fmt.Errorf("transaction root hash mismatch (header value %x, calculated %x)", header.TxHash, hash)
    70  	}
    71  
    72  	// Withdrawals are present after the Shanghai fork.
    73  	if header.WithdrawalsHash != nil {
    74  		// Withdrawals list must be present in body after Shanghai.
    75  		if block.Withdrawals() == nil {
    76  			return errors.New("missing withdrawals in block body")
    77  		}
    78  		if hash := types.DeriveSha(block.Withdrawals(), trie.NewStackTrie(nil)); hash != *header.WithdrawalsHash {
    79  			return fmt.Errorf("withdrawals root hash mismatch (header value %x, calculated %x)", *header.WithdrawalsHash, hash)
    80  		}
    81  	} else if block.Withdrawals() != nil {
    82  		// Withdrawals are not allowed prior to Shanghai fork
    83  		return errors.New("withdrawals present in block body")
    84  	}
    85  
    86  	// Blob transactions may be present after the Cancun fork.
    87  	var blobs int
    88  	for i, tx := range block.Transactions() {
    89  		// Count the number of blobs to validate against the header's blobGasUsed
    90  		blobs += len(tx.BlobHashes())
    91  
    92  		// If the tx is a blob tx, it must NOT have a sidecar attached to be valid in a block.
    93  		if tx.BlobTxSidecar() != nil {
    94  			return fmt.Errorf("unexpected blob sidecar in transaction at index %d", i)
    95  		}
    96  
    97  		// The individual checks for blob validity (version-check + not empty)
    98  		// happens in StateTransition.
    99  	}
   100  
   101  	// Check blob gas usage.
   102  	if header.BlobGasUsed != nil {
   103  		if want := *header.BlobGasUsed / params.BlobTxBlobGasPerBlob; uint64(blobs) != want { // div because the header is surely good vs the body might be bloated
   104  			return fmt.Errorf("blob gas used mismatch (header %v, calculated %v)", *header.BlobGasUsed, blobs*params.BlobTxBlobGasPerBlob)
   105  		}
   106  	} else {
   107  		if blobs > 0 {
   108  			return errors.New("data blobs present in block body")
   109  		}
   110  	}
   111  
   112  	// Ancestor block must be known.
   113  	if !v.bc.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
   114  		if !v.bc.HasBlock(block.ParentHash(), block.NumberU64()-1) {
   115  			return consensus.ErrUnknownAncestor
   116  		}
   117  		return consensus.ErrPrunedAncestor
   118  	}
   119  	return nil
   120  }
   121  
   122  // ValidateState validates the various changes that happen after a state transition,
   123  // such as amount of used gas, the receipt roots and the state root itself.
   124  func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error {
   125  	header := block.Header()
   126  	if block.GasUsed() != usedGas {
   127  		return fmt.Errorf("invalid gas used (remote: %d local: %d)", block.GasUsed(), usedGas)
   128  	}
   129  	// Validate the received block's bloom with the one derived from the generated receipts.
   130  	// For valid blocks this should always validate to true.
   131  	rbloom := types.CreateBloom(receipts)
   132  	if rbloom != header.Bloom {
   133  		return fmt.Errorf("invalid bloom (remote: %x  local: %x)", header.Bloom, rbloom)
   134  	}
   135  	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, Rn]]))
   136  	receiptSha := types.DeriveSha(receipts, trie.NewStackTrie(nil))
   137  	if receiptSha != header.ReceiptHash {
   138  		return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
   139  	}
   140  	// Validate the state root against the received state root and throw
   141  	// an error if they don't match.
   142  	if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
   143  		return fmt.Errorf("invalid merkle root (remote: %x local: %x) dberr: %w", header.Root, root, statedb.Error())
   144  	}
   145  	return nil
   146  }
   147  
   148  // CalcGasLimit computes the gas limit of the next block after parent. It aims
   149  // to keep the baseline gas close to the provided target, and increase it towards
   150  // the target if the baseline gas is lower.
   151  func CalcGasLimit(parentGasLimit, desiredLimit uint64) uint64 {
   152  	delta := parentGasLimit/params.GasLimitBoundDivisor - 1
   153  	limit := parentGasLimit
   154  	if desiredLimit < params.MinGasLimit {
   155  		desiredLimit = params.MinGasLimit
   156  	}
   157  	// If we're outside our allowed gas range, we try to hone towards them
   158  	if limit < desiredLimit {
   159  		limit = parentGasLimit + delta
   160  		if limit > desiredLimit {
   161  			limit = desiredLimit
   162  		}
   163  		return limit
   164  	}
   165  	if limit > desiredLimit {
   166  		limit = parentGasLimit - delta
   167  		if limit < desiredLimit {
   168  			limit = desiredLimit
   169  		}
   170  	}
   171  	return limit
   172  }