block_validator.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/params"
  26. "github.com/ethereum/go-ethereum/pow"
  27. "gopkg.in/fatih/set.v0"
  28. )
  29. var (
  30. ExpDiffPeriod = big.NewInt(100000)
  31. big10 = big.NewInt(10)
  32. bigMinus99 = big.NewInt(-99)
  33. )
  34. // BlockValidator is responsible for validating block headers, uncles and
  35. // processed state.
  36. //
  37. // BlockValidator implements Validator.
  38. type BlockValidator struct {
  39. config *ChainConfig // Chain configuration options
  40. bc *BlockChain // Canonical block chain
  41. Pow pow.PoW // Proof of work used for validating
  42. }
  43. // NewBlockValidator returns a new block validator which is safe for re-use
  44. func NewBlockValidator(config *ChainConfig, blockchain *BlockChain, pow pow.PoW) *BlockValidator {
  45. validator := &BlockValidator{
  46. config: config,
  47. Pow: pow,
  48. bc: blockchain,
  49. }
  50. return validator
  51. }
  52. // ValidateBlock validates the given block's header and uncles and verifies the
  53. // the block header's transaction and uncle roots.
  54. //
  55. // ValidateBlock does not validate the header's pow. The pow work validated
  56. // separately so we can process them in parallel.
  57. //
  58. // ValidateBlock also validates and makes sure that any previous state (or present)
  59. // state that might or might not be present is checked to make sure that fast
  60. // sync has done it's job proper. This prevents the block validator form accepting
  61. // false positives where a header is present but the state is not.
  62. func (v *BlockValidator) ValidateBlock(block *types.Block) error {
  63. if v.bc.HasBlock(block.Hash()) {
  64. if _, err := state.New(block.Root(), v.bc.chainDb); err == nil {
  65. return &KnownBlockError{block.Number(), block.Hash()}
  66. }
  67. }
  68. parent := v.bc.GetBlock(block.ParentHash())
  69. if parent == nil {
  70. return ParentError(block.ParentHash())
  71. }
  72. if _, err := state.New(parent.Root(), v.bc.chainDb); err != nil {
  73. return ParentError(block.ParentHash())
  74. }
  75. header := block.Header()
  76. // validate the block header
  77. if err := ValidateHeader(v.config, v.Pow, header, parent.Header(), false, false); err != nil {
  78. return err
  79. }
  80. // verify the uncles are correctly rewarded
  81. if err := v.VerifyUncles(block, parent); err != nil {
  82. return err
  83. }
  84. // Verify UncleHash before running other uncle validations
  85. unclesSha := types.CalcUncleHash(block.Uncles())
  86. if unclesSha != header.UncleHash {
  87. return fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
  88. }
  89. // The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
  90. // can be used by light clients to make sure they've received the correct Txs
  91. txSha := types.DeriveSha(block.Transactions())
  92. if txSha != header.TxHash {
  93. return fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
  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, parent *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas *big.Int) (err error) {
  102. header := block.Header()
  103. if block.GasUsed().Cmp(usedGas) != 0 {
  104. return ValidationError(fmt.Sprintf("gas used error (%v / %v)", 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. rbloom := types.CreateBloom(receipts)
  109. if rbloom != header.Bloom {
  110. return fmt.Errorf("unable to replicate block's bloom=%x vs calculated bloom=%x", header.Bloom, rbloom)
  111. }
  112. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  113. receiptSha := types.DeriveSha(receipts)
  114. if receiptSha != header.ReceiptHash {
  115. return fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
  116. }
  117. // Validate the state root against the received state root and throw
  118. // an error if they don't match.
  119. if root := statedb.IntermediateRoot(); header.Root != root {
  120. return fmt.Errorf("invalid merkle root: header=%x computed=%x", header.Root, root)
  121. }
  122. return nil
  123. }
  124. // VerifyUncles verifies the given block's uncles and applies the Ethereum
  125. // consensus rules to the various block headers included; it will return an
  126. // error if any of the included uncle headers were invalid. It returns an error
  127. // if the validation failed.
  128. func (v *BlockValidator) VerifyUncles(block, parent *types.Block) error {
  129. // validate that there at most 2 uncles included in this block
  130. if len(block.Uncles()) > 2 {
  131. return ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(block.Uncles()))
  132. }
  133. uncles := set.New()
  134. ancestors := make(map[common.Hash]*types.Block)
  135. for _, ancestor := range v.bc.GetBlocksFromHash(block.ParentHash(), 7) {
  136. ancestors[ancestor.Hash()] = ancestor
  137. // Include ancestors uncles in the uncle set. Uncles must be unique.
  138. for _, uncle := range ancestor.Uncles() {
  139. uncles.Add(uncle.Hash())
  140. }
  141. }
  142. ancestors[block.Hash()] = block
  143. uncles.Add(block.Hash())
  144. for i, uncle := range block.Uncles() {
  145. hash := uncle.Hash()
  146. if uncles.Has(hash) {
  147. // Error not unique
  148. return UncleError("uncle[%d](%x) not unique", i, hash[:4])
  149. }
  150. uncles.Add(hash)
  151. if ancestors[hash] != nil {
  152. branch := fmt.Sprintf(" O - %x\n |\n", block.Hash())
  153. for h := range ancestors {
  154. branch += fmt.Sprintf(" O - %x\n |\n", h)
  155. }
  156. glog.Infoln(branch)
  157. return UncleError("uncle[%d](%x) is ancestor", i, hash[:4])
  158. }
  159. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == parent.Hash() {
  160. return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4])
  161. }
  162. if err := ValidateHeader(v.config, v.Pow, uncle, ancestors[uncle.ParentHash].Header(), true, true); err != nil {
  163. return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err))
  164. }
  165. }
  166. return nil
  167. }
  168. // ValidateHeader validates the given header and, depending on the pow arg,
  169. // checks the proof of work of the given header. Returns an error if the
  170. // validation failed.
  171. func (v *BlockValidator) ValidateHeader(header, parent *types.Header, checkPow bool) error {
  172. // Short circuit if the parent is missing.
  173. if parent == nil {
  174. return ParentError(header.ParentHash)
  175. }
  176. // Short circuit if the header's already known or its parent missing
  177. if v.bc.HasHeader(header.Hash()) {
  178. return nil
  179. }
  180. return ValidateHeader(v.config, v.Pow, header, parent, checkPow, false)
  181. }
  182. // Validates a header. Returns an error if the header is invalid.
  183. //
  184. // See YP section 4.3.4. "Block Header Validity"
  185. func ValidateHeader(config *ChainConfig, pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
  186. if big.NewInt(int64(len(header.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
  187. return fmt.Errorf("Header extra data too long (%d)", len(header.Extra))
  188. }
  189. if uncle {
  190. if header.Time.Cmp(common.MaxBig) == 1 {
  191. return BlockTSTooBigErr
  192. }
  193. } else {
  194. if header.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 {
  195. return BlockFutureErr
  196. }
  197. }
  198. if header.Time.Cmp(parent.Time) != 1 {
  199. return BlockEqualTSErr
  200. }
  201. expd := CalcDifficulty(config, header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
  202. if expd.Cmp(header.Difficulty) != 0 {
  203. return fmt.Errorf("Difficulty check failed for header %v, %v", header.Difficulty, expd)
  204. }
  205. a := new(big.Int).Set(parent.GasLimit)
  206. a = a.Sub(a, header.GasLimit)
  207. a.Abs(a)
  208. b := new(big.Int).Set(parent.GasLimit)
  209. b = b.Div(b, params.GasLimitBoundDivisor)
  210. if !(a.Cmp(b) < 0) || (header.GasLimit.Cmp(params.MinGasLimit) == -1) {
  211. return fmt.Errorf("GasLimit check failed for header %v (%v > %v)", header.GasLimit, a, b)
  212. }
  213. num := new(big.Int).Set(parent.Number)
  214. num.Sub(header.Number, num)
  215. if num.Cmp(big.NewInt(1)) != 0 {
  216. return BlockNumberErr
  217. }
  218. if checkPow {
  219. // Verify the nonce of the header. Return an error if it's not valid
  220. if !pow.Verify(types.NewBlockWithHeader(header)) {
  221. return &BlockNonceErr{header.Number, header.Hash(), header.Nonce.Uint64()}
  222. }
  223. }
  224. return nil
  225. }
  226. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  227. // the difficulty that a new block should have when created at time
  228. // given the parent block's time and difficulty.
  229. func CalcDifficulty(config *ChainConfig, time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  230. if config.IsHomestead(new(big.Int).Add(parentNumber, common.Big1)) {
  231. return calcDifficultyHomestead(time, parentTime, parentNumber, parentDiff)
  232. } else {
  233. return calcDifficultyFrontier(time, parentTime, parentNumber, parentDiff)
  234. }
  235. }
  236. func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  237. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki
  238. // algorithm:
  239. // diff = (parent_diff +
  240. // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  241. // ) + 2^(periodCount - 2)
  242. bigTime := new(big.Int).SetUint64(time)
  243. bigParentTime := new(big.Int).SetUint64(parentTime)
  244. // holds intermediate values to make the algo easier to read & audit
  245. x := new(big.Int)
  246. y := new(big.Int)
  247. // 1 - (block_timestamp -parent_timestamp) // 10
  248. x.Sub(bigTime, bigParentTime)
  249. x.Div(x, big10)
  250. x.Sub(common.Big1, x)
  251. // max(1 - (block_timestamp - parent_timestamp) // 10, -99)))
  252. if x.Cmp(bigMinus99) < 0 {
  253. x.Set(bigMinus99)
  254. }
  255. // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  256. y.Div(parentDiff, params.DifficultyBoundDivisor)
  257. x.Mul(y, x)
  258. x.Add(parentDiff, x)
  259. // minimum difficulty can ever be (before exponential factor)
  260. if x.Cmp(params.MinimumDifficulty) < 0 {
  261. x = params.MinimumDifficulty
  262. }
  263. // for the exponential factor
  264. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  265. periodCount.Div(periodCount, ExpDiffPeriod)
  266. // the exponential factor, commonly referred to as "the bomb"
  267. // diff = diff + 2^(periodCount - 2)
  268. if periodCount.Cmp(common.Big1) > 0 {
  269. y.Sub(periodCount, common.Big2)
  270. y.Exp(common.Big2, y, nil)
  271. x.Add(x, y)
  272. }
  273. return x
  274. }
  275. func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  276. diff := new(big.Int)
  277. adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
  278. bigTime := new(big.Int)
  279. bigParentTime := new(big.Int)
  280. bigTime.SetUint64(time)
  281. bigParentTime.SetUint64(parentTime)
  282. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  283. diff.Add(parentDiff, adjust)
  284. } else {
  285. diff.Sub(parentDiff, adjust)
  286. }
  287. if diff.Cmp(params.MinimumDifficulty) < 0 {
  288. diff = params.MinimumDifficulty
  289. }
  290. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  291. periodCount.Div(periodCount, ExpDiffPeriod)
  292. if periodCount.Cmp(common.Big1) > 0 {
  293. // diff = diff + 2^(periodCount - 2)
  294. expDiff := periodCount.Sub(periodCount, common.Big2)
  295. expDiff.Exp(common.Big2, expDiff, nil)
  296. diff.Add(diff, expDiff)
  297. diff = common.BigMax(diff, params.MinimumDifficulty)
  298. }
  299. return diff
  300. }
  301. // CalcGasLimit computes the gas limit of the next block after parent.
  302. // The result may be modified by the caller.
  303. // This is miner strategy, not consensus protocol.
  304. func CalcGasLimit(parent *types.Block) *big.Int {
  305. // contrib = (parentGasUsed * 3 / 2) / 1024
  306. contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
  307. contrib = contrib.Div(contrib, big.NewInt(2))
  308. contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
  309. // decay = parentGasLimit / 1024 -1
  310. decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
  311. decay.Sub(decay, big.NewInt(1))
  312. /*
  313. strategy: gasLimit of block-to-mine is set based on parent's
  314. gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
  315. increase it, otherwise lower it (or leave it unchanged if it's right
  316. at that usage) the amount increased/decreased depends on how far away
  317. from parentGasLimit * (2/3) parentGasUsed is.
  318. */
  319. gl := new(big.Int).Sub(parent.GasLimit(), decay)
  320. gl = gl.Add(gl, contrib)
  321. gl.Set(common.BigMax(gl, params.MinGasLimit))
  322. // however, if we're now below the target (TargetGasLimit) we increase the
  323. // limit as much as we can (parentGasLimit / 1024 -1)
  324. if gl.Cmp(params.TargetGasLimit) < 0 {
  325. gl.Add(parent.GasLimit(), decay)
  326. gl.Set(common.BigMin(gl, params.TargetGasLimit))
  327. }
  328. return gl
  329. }