github.com/core-coin/go-core/v2@v2.1.9/core/block_validator.go (about)

     1  // Copyright 2015 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/core-coin/go-core/v2/common"
    23  	"github.com/core-coin/go-core/v2/consensus"
    24  	"github.com/core-coin/go-core/v2/core/state"
    25  	"github.com/core-coin/go-core/v2/core/types"
    26  	"github.com/core-coin/go-core/v2/params"
    27  	"github.com/core-coin/go-core/v2/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's known, and if not, that it's linkable
    55  	if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
    56  		return ErrKnownBlock
    57  	}
    58  	// Header validity is known at this point, check the uncles and transactions
    59  	header := block.Header()
    60  	if err := v.engine.VerifyUncles(v.bc, block); err != nil {
    61  		return err
    62  	}
    63  	if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
    64  		return fmt.Errorf("uncle root hash mismatch: have %x, want %x", hash, header.UncleHash)
    65  	}
    66  	if hash := types.DeriveSha(block.Transactions(), trie.NewStackTrie(nil)); hash != header.TxHash {
    67  		return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
    68  	}
    69  
    70  	// Validate transactions network IDs and addresses
    71  	for _, tx := range block.Transactions() {
    72  		if tx.Hash().Hex() != params.ZeroNetworkIDTxHash.Hex() && tx.NetworkID() != uint(v.config.NetworkID.Uint64()) {
    73  			return types.ErrInvalidNetworkId
    74  		}
    75  		if tx.To() != nil && common.VerifyAddress(*tx.To()) != nil {
    76  			return ErrInvalidRecipientOrSig
    77  		}
    78  	}
    79  
    80  	if !v.bc.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
    81  		if !v.bc.HasBlock(block.ParentHash(), block.NumberU64()-1) {
    82  			return consensus.ErrUnknownAncestor
    83  		}
    84  		return consensus.ErrPrunedAncestor
    85  	}
    86  	return nil
    87  }
    88  
    89  // ValidateState validates the various changes that happen after a state
    90  // transition, such as amount of used energy, the receipt roots and the state root
    91  // itself. ValidateState returns a database batch if the validation was a success
    92  // otherwise nil and an error is returned.
    93  func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedEnergy uint64) error {
    94  	header := block.Header()
    95  	if block.EnergyUsed() != usedEnergy {
    96  		return fmt.Errorf("invalid energy used (remote: %d local: %d)", block.EnergyUsed(), usedEnergy)
    97  	}
    98  	// Validate the received block's bloom with the one derived from the generated receipts.
    99  	// For valid blocks this should always validate to true.
   100  	rbloom := types.CreateBloom(receipts)
   101  	if rbloom != header.Bloom {
   102  		return fmt.Errorf("invalid bloom (remote: %x  local: %x)", header.Bloom, rbloom)
   103  	}
   104  	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, Rn]]))
   105  	receiptSha := types.DeriveSha(receipts, trie.NewStackTrie(nil))
   106  	if receiptSha != header.ReceiptHash {
   107  		return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
   108  	}
   109  	// Validate the state root against the received state root and throw
   110  	// an error if they don't match.
   111  	if root := statedb.IntermediateRoot(true); header.Root != root {
   112  		return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
   113  	}
   114  	return nil
   115  }
   116  
   117  // CalcEnergyLimit computes the energy limit of the next block after parent. It aims
   118  // to keep the baseline energy above the provided floor, and increase it towards the
   119  // ceil if the blocks are full. If the ceil is exceeded, it will always decrease
   120  // the energy allowance.
   121  func CalcEnergyLimit(parent *types.Block, energyFloor, energyCeil uint64) uint64 {
   122  	// contrib = (parentEnergyUsed * 3 / 2) / 1024
   123  	contrib := (parent.EnergyUsed() + parent.EnergyUsed()/2) / params.EnergyLimitBoundDivisor
   124  
   125  	// decay = parentEnergyLimit / 1024 -1
   126  	decay := parent.EnergyLimit()/params.EnergyLimitBoundDivisor - 1
   127  
   128  	/*
   129  		strategy: energyLimit of block-to-mine is set based on parent's
   130  		energyUsed value.  if parentEnergyUsed > parentEnergyLimit * (2/3) then we
   131  		increase it, otherwise lower it (or leave it unchanged if it's right
   132  		at that usage) the amount increased/decreased depends on how far away
   133  		from parentEnergyLimit * (2/3) parentEnergyUsed is.
   134  	*/
   135  	limit := parent.EnergyLimit() - decay + contrib
   136  	if limit < params.MinEnergyLimit {
   137  		limit = params.MinEnergyLimit
   138  	}
   139  	// If we're outside our allowed energy range, we try to hone towards them
   140  	if limit < energyFloor {
   141  		limit = parent.EnergyLimit() + decay
   142  		if limit > energyFloor {
   143  			limit = energyFloor
   144  		}
   145  	} else if limit > energyCeil {
   146  		limit = parent.EnergyLimit() - decay
   147  		if limit < energyCeil {
   148  			limit = energyCeil
   149  		}
   150  	}
   151  	return limit
   152  }