block_validator.go 6.7 KB

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