block_validator.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. package core
  17. import (
  18. "fmt"
  19. "math/big"
  20. "github.com/ethereum/go-ethereum/common/math"
  21. "github.com/ethereum/go-ethereum/consensus"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/params"
  25. )
  26. // BlockValidator is responsible for validating block headers, uncles and
  27. // processed state.
  28. //
  29. // BlockValidator implements Validator.
  30. type BlockValidator struct {
  31. config *params.ChainConfig // Chain configuration options
  32. bc *BlockChain // Canonical block chain
  33. engine consensus.Engine // Consensus engine used for validating
  34. }
  35. // NewBlockValidator returns a new block validator which is safe for re-use
  36. func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator {
  37. validator := &BlockValidator{
  38. config: config,
  39. engine: engine,
  40. bc: blockchain,
  41. }
  42. return validator
  43. }
  44. // ValidateBody validates the given block's uncles and verifies the the block
  45. // header's transaction and uncle roots. The headers are assumed to be already
  46. // validated at this point.
  47. func (v *BlockValidator) ValidateBody(block *types.Block) error {
  48. // Check whether the block's known, and if not, that it's linkable
  49. if v.bc.HasBlockAndState(block.Hash()) {
  50. return ErrKnownBlock
  51. }
  52. if !v.bc.HasBlockAndState(block.ParentHash()) {
  53. return consensus.ErrUnknownAncestor
  54. }
  55. // Header validity is known at this point, check the uncles and transactions
  56. header := block.Header()
  57. if err := v.engine.VerifyUncles(v.bc, block); err != nil {
  58. return err
  59. }
  60. if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
  61. return fmt.Errorf("uncle root hash mismatch: have %x, want %x", hash, header.UncleHash)
  62. }
  63. if hash := types.DeriveSha(block.Transactions()); hash != header.TxHash {
  64. return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
  65. }
  66. return nil
  67. }
  68. // ValidateState validates the various changes that happen after a state
  69. // transition, such as amount of used gas, the receipt roots and the state root
  70. // itself. ValidateState returns a database batch if the validation was a success
  71. // otherwise nil and an error is returned.
  72. func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas *big.Int) error {
  73. header := block.Header()
  74. if block.GasUsed().Cmp(usedGas) != 0 {
  75. return fmt.Errorf("invalid gas used (remote: %v local: %v)", block.GasUsed(), usedGas)
  76. }
  77. // Validate the received block's bloom with the one derived from the generated receipts.
  78. // For valid blocks this should always validate to true.
  79. rbloom := types.CreateBloom(receipts)
  80. if rbloom != header.Bloom {
  81. return fmt.Errorf("invalid bloom (remote: %x local: %x)", header.Bloom, rbloom)
  82. }
  83. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  84. receiptSha := types.DeriveSha(receipts)
  85. if receiptSha != header.ReceiptHash {
  86. return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
  87. }
  88. // Validate the state root against the received state root and throw
  89. // an error if they don't match.
  90. if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
  91. return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
  92. }
  93. return nil
  94. }
  95. // CalcGasLimit computes the gas limit of the next block after parent.
  96. // The result may be modified by the caller.
  97. // This is miner strategy, not consensus protocol.
  98. func CalcGasLimit(parent *types.Block) *big.Int {
  99. // contrib = (parentGasUsed * 3 / 2) / 1024
  100. contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
  101. contrib = contrib.Div(contrib, big.NewInt(2))
  102. contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
  103. // decay = parentGasLimit / 1024 -1
  104. decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
  105. decay.Sub(decay, big.NewInt(1))
  106. /*
  107. strategy: gasLimit of block-to-mine is set based on parent's
  108. gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
  109. increase it, otherwise lower it (or leave it unchanged if it's right
  110. at that usage) the amount increased/decreased depends on how far away
  111. from parentGasLimit * (2/3) parentGasUsed is.
  112. */
  113. gl := new(big.Int).Sub(parent.GasLimit(), decay)
  114. gl = gl.Add(gl, contrib)
  115. gl.Set(math.BigMax(gl, params.MinGasLimit))
  116. // however, if we're now below the target (TargetGasLimit) we increase the
  117. // limit as much as we can (parentGasLimit / 1024 -1)
  118. if gl.Cmp(params.TargetGasLimit) < 0 {
  119. gl.Add(parent.GasLimit(), decay)
  120. gl.Set(math.BigMin(gl, params.TargetGasLimit))
  121. }
  122. return gl
  123. }