block_validator.go 5.4 KB

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