block_validator.go 14 KB

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