block_validator.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. "github.com/ethereum/go-ethereum/trie"
  24. )
  25. // BlockValidator is responsible for validating block headers, uncles and
  26. // processed state.
  27. //
  28. // BlockValidator implements Validator.
  29. type BlockValidator struct {
  30. config *params.ChainConfig // Chain configuration options
  31. bc *BlockChain // Canonical block chain
  32. engine consensus.Engine // Consensus engine used for validating
  33. }
  34. // NewBlockValidator returns a new block validator which is safe for re-use
  35. func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator {
  36. validator := &BlockValidator{
  37. config: config,
  38. engine: engine,
  39. bc: blockchain,
  40. }
  41. return validator
  42. }
  43. // ValidateBody validates the given block's uncles and verifies the block
  44. // header's transaction and uncle roots. The headers are assumed to be already
  45. // validated at this point.
  46. func (v *BlockValidator) ValidateBody(block *types.Block) error {
  47. // Check whether the block's known, and if not, that it's linkable
  48. if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
  49. return ErrKnownBlock
  50. }
  51. // Header validity is known at this point, check the uncles and transactions
  52. header := block.Header()
  53. if err := v.engine.VerifyUncles(v.bc, block); err != nil {
  54. return err
  55. }
  56. if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
  57. return fmt.Errorf("uncle root hash mismatch: have %x, want %x", hash, header.UncleHash)
  58. }
  59. validateFuns := []func() error{
  60. func() error {
  61. if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
  62. return ErrKnownBlock
  63. }
  64. return nil
  65. },
  66. func() error {
  67. if hash := types.DeriveSha(block.Transactions(), trie.NewStackTrie(nil)); hash != header.TxHash {
  68. return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
  69. }
  70. return nil
  71. },
  72. func() error {
  73. if !v.bc.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
  74. if !v.bc.HasBlock(block.ParentHash(), block.NumberU64()-1) {
  75. return consensus.ErrUnknownAncestor
  76. }
  77. return consensus.ErrPrunedAncestor
  78. }
  79. return nil
  80. },
  81. }
  82. validateRes := make(chan error, len(validateFuns))
  83. for _, f := range validateFuns {
  84. tmpFunc := f
  85. go func() {
  86. validateRes <- tmpFunc()
  87. }()
  88. }
  89. for i := 0; i < len(validateFuns); i++ {
  90. r := <-validateRes
  91. if r != nil {
  92. return r
  93. }
  94. }
  95. return nil
  96. }
  97. // ValidateState validates the various changes that happen after a state
  98. // transition, such as amount of used gas, the receipt roots and the state root
  99. // itself. ValidateState returns a database batch if the validation was a success
  100. // otherwise nil and an error is returned.
  101. func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error {
  102. header := block.Header()
  103. if block.GasUsed() != usedGas {
  104. return fmt.Errorf("invalid gas used (remote: %d local: %d)", block.GasUsed(), usedGas)
  105. }
  106. // Validate the received block's bloom with the one derived from the generated receipts.
  107. // For valid blocks this should always validate to true.
  108. validateFuns := []func() error{
  109. func() error {
  110. rbloom := types.CreateBloom(receipts)
  111. if rbloom != header.Bloom {
  112. return fmt.Errorf("invalid bloom (remote: %x local: %x)", header.Bloom, rbloom)
  113. }
  114. return nil
  115. },
  116. func() error {
  117. receiptSha := types.DeriveSha(receipts, trie.NewStackTrie(nil))
  118. if receiptSha != header.ReceiptHash {
  119. return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", header.ReceiptHash, receiptSha)
  120. } else {
  121. return nil
  122. }
  123. },
  124. func() error {
  125. if root := statedb.IntermediateRoot(v.config.IsEIP158(header.Number)); header.Root != root {
  126. return fmt.Errorf("invalid merkle root (remote: %x local: %x)", header.Root, root)
  127. } else {
  128. return nil
  129. }
  130. },
  131. }
  132. validateRes := make(chan error, len(validateFuns))
  133. for _, f := range validateFuns {
  134. tmpFunc := f
  135. go func() {
  136. validateRes <- tmpFunc()
  137. }()
  138. }
  139. var err error
  140. for i := 0; i < len(validateFuns); i++ {
  141. r := <-validateRes
  142. if r != nil && err == nil {
  143. err = r
  144. }
  145. }
  146. return err
  147. }
  148. // CalcGasLimit computes the gas limit of the next block after parent. It aims
  149. // to keep the baseline gas above the provided floor, and increase it towards the
  150. // ceil if the blocks are full. If the ceil is exceeded, it will always decrease
  151. // the gas allowance.
  152. func CalcGasLimit(parent *types.Block, gasFloor, gasCeil uint64) uint64 {
  153. // contrib = (parentGasUsed * 3 / 2) / 256
  154. contrib := (parent.GasUsed() + parent.GasUsed()/2) / params.GasLimitBoundDivisor
  155. // decay = parentGasLimit / 256 -1
  156. decay := parent.GasLimit()/params.GasLimitBoundDivisor - 1
  157. /*
  158. strategy: gasLimit of block-to-mine is set based on parent's
  159. gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
  160. increase it, otherwise lower it (or leave it unchanged if it's right
  161. at that usage) the amount increased/decreased depends on how far away
  162. from parentGasLimit * (2/3) parentGasUsed is.
  163. */
  164. limit := parent.GasLimit() - decay + contrib
  165. if limit < params.MinGasLimit {
  166. limit = params.MinGasLimit
  167. }
  168. // If we're outside our allowed gas range, we try to hone towards them
  169. if limit < gasFloor {
  170. limit = parent.GasLimit() + decay
  171. if limit > gasFloor {
  172. limit = gasFloor
  173. }
  174. } else if limit > gasCeil {
  175. limit = parent.GasLimit() - decay
  176. if limit < gasCeil {
  177. limit = gasCeil
  178. }
  179. }
  180. return limit
  181. }