block_validator.go 13 KB

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