github.com/gnc-project/gnc@v1.0.0/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  "log"
    22  	"github.com/gnc-project/gnc/consensus"
    23  	"github.com/gnc-project/gnc/core/state"
    24  	"github.com/gnc-project/gnc/core/types"
    25  	"github.com/gnc-project/gnc/params"
    26  )
    27  
    28  // BlockValidator is responsible for validating block headers, uncles and
    29  // processed state.
    30  //
    31  // BlockValidator implements Validator.
    32  type BlockValidator struct {
    33  	config *params.ChainConfig // Chain configuration options
    34  	bc     *BlockChain         // Canonical block chain
    35  	engine consensus.Engine    // Consensus engine used for validating
    36  }
    37  
    38  // NewBlockValidator returns a new block validator which is safe for re-use
    39  func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator {
    40  	validator := &BlockValidator{
    41  		config: config,
    42  		engine: engine,
    43  		bc:     blockchain,
    44  	}
    45  	return validator
    46  }
    47  
    48  // ValidateBody validates the given block's uncles and verifies the block
    49  // header's transaction and uncle roots. The headers are assumed to be already
    50  // validated at this point.
    51  func (v *BlockValidator) ValidateBody(block *types.Block) error {
    52  	// Check whether the block's known, and if not, that it's linkable
    53  	if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
    54  		return ErrKnownBlock
    55  	}
    56  	// Header validity is known at this point, check the uncles and transactions
    57  	header := block.Header()
    58  	if hash := types.DeriveSha(block.Transactions()); hash != header.TxHash {
    59  		return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
    60  	}
    61  	transactions:=block.Transactions()
    62  //linzhaojie blockValidate code
    63  	if len(transactions)>0{
    64  		for i:=0;i<len(transactions);i++{
    65  			msg, err := transactions[i].AsMessage(types.NewEIP155Signer(v.config.ChainID))
    66  						if err != nil {
    67  							log.Fatal("getFromErr",err)
    68  						}
    69               if msg.Type()==1||msg.Type()==2{
    70                 if msg.From()!=IsTheFates{
    71  				return fmt.Errorf("invalid txType‘s sender (remote: %d local: %d)", msg.From().Hex(), IsTheFates.Hex())
    72  			   }
    73  			}
    74  		}
    75  	}
    76  
    77  
    78  	if !v.bc.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
    79  		if !v.bc.HasBlock(block.ParentHash(), block.NumberU64()-1) {
    80  			return consensus.ErrUnknownAncestor
    81  		}
    82  		return consensus.ErrPrunedAncestor
    83  	}
    84  	return nil
    85  }
    86  
    87  // ValidateState validates the various changes that happen after a state
    88  // transition, such as amount of used gas, the receipt roots and the state root
    89  // itself. ValidateState returns a database batch if the validation was a success
    90  // otherwise nil and an error is returned.
    91  func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error {
    92  	header := block.Header()
    93  //verifyCoinbase
    94  	if !statedb.IsSuperNode(header.Coinbase)&&header.Coinbase!=header.TheFates{
    95  	  return fmt.Errorf("invalid Coinbase:%d is not a SuperNode", header.Coinbase.Hex())
    96  		
    97      }
    98  	
    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, R1]]))
   109  	receiptSha := types.DeriveSha(receipts)
   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  
   122  // CalcGasLimit computes the gas limit of the next block after parent. It aims
   123  // to keep the baseline gas above the provided floor, and increase it towards the
   124  // ceil if the blocks are full. If the ceil is exceeded, it will always decrease
   125  // the gas allowance.
   126  func CalcGasLimit(parent *types.Block, gasFloor, gasCeil uint64) uint64 {
   127  	// contrib = (parentGasUsed * 3 / 2) / 1024
   128  	contrib := (parent.GasUsed() + parent.GasUsed()/2) / params.GasLimitBoundDivisor
   129  
   130  	// decay = parentGasLimit / 1024 -1
   131  	decay := parent.GasLimit()/params.GasLimitBoundDivisor - 1
   132  
   133  	/*
   134  		strategy: gasLimit of block-to-mine is set based on parent's
   135  		gasUsed value.  if parentGasUsed > parentGasLimit * (2/3) then we
   136  		increase it, otherwise lower it (or leave it unchanged if it's right
   137  		at that usage) the amount increased/decreased depends on how far away
   138  		from parentGasLimit * (2/3) parentGasUsed is.
   139  	*/
   140  	limit := parent.GasLimit() - decay + contrib
   141  	if limit < params.MinGasLimit {
   142  		limit = params.MinGasLimit
   143  	}
   144  	// If we're outside our allowed gas range, we try to hone towards them
   145  	if limit < gasFloor {
   146  		limit = parent.GasLimit() + decay
   147  		if limit > gasFloor {
   148  			limit = gasFloor
   149  		}
   150  	} else if limit > gasCeil {
   151  		limit = parent.GasLimit() - decay
   152  		if limit < gasCeil {
   153  			limit = gasCeil
   154  		}
   155  	}
   156  	return limit
   157  }