consensus.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. // Copyright 2017 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 ethash
  17. import (
  18. "bytes"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "runtime"
  23. "sync/atomic"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/math"
  27. "github.com/ethereum/go-ethereum/consensus"
  28. "github.com/ethereum/go-ethereum/consensus/misc"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/params"
  32. set "gopkg.in/fatih/set.v0"
  33. )
  34. // Ethash proof-of-work protocol constants.
  35. var (
  36. blockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
  37. maxUncles = 2 // Maximum number of uncles allowed in a single block
  38. )
  39. // Various error messages to mark blocks invalid. These should be private to
  40. // prevent engine specific errors from being referenced in the remainder of the
  41. // codebase, inherently breaking if the engine is swapped out. Please put common
  42. // error types into the consensus package.
  43. var (
  44. errInvalidChain = errors.New("invalid header chain")
  45. errLargeBlockTime = errors.New("timestamp too big")
  46. errZeroBlockTime = errors.New("timestamp equals parent's")
  47. errTooManyUncles = errors.New("too many uncles")
  48. errDuplicateUncle = errors.New("duplicate uncle")
  49. errUncleIsAncestor = errors.New("uncle is ancestor")
  50. errDanglingUncle = errors.New("uncle's parent is not ancestor")
  51. errNonceOutOfRange = errors.New("nonce out of range")
  52. errInvalidDifficulty = errors.New("non-positive difficulty")
  53. errInvalidMixDigest = errors.New("invalid mix digest")
  54. errInvalidPoW = errors.New("invalid proof-of-work")
  55. )
  56. // Author implements consensus.Engine, returning the header's coinbase as the
  57. // proof-of-work verified author of the block.
  58. func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
  59. return header.Coinbase, nil
  60. }
  61. // VerifyHeader checks whether a header conforms to the consensus rules of the
  62. // stock Ethereum ethash engine.
  63. func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
  64. // If we're running a full engine faking, accept any input as valid
  65. if ethash.fakeFull {
  66. return nil
  67. }
  68. // Short circuit if the header is known, or it's parent not
  69. number := header.Number.Uint64()
  70. if chain.GetHeader(header.Hash(), number) != nil {
  71. return nil
  72. }
  73. parent := chain.GetHeader(header.ParentHash, number-1)
  74. if parent == nil {
  75. return consensus.ErrUnknownAncestor
  76. }
  77. // Sanity checks passed, do a proper verification
  78. return ethash.verifyHeader(chain, header, parent, false, seal)
  79. }
  80. // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
  81. // concurrently. The method returns a quit channel to abort the operations and
  82. // a results channel to retrieve the async verifications.
  83. func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  84. // If we're running a full engine faking, accept any input as valid
  85. if ethash.fakeFull {
  86. abort, results := make(chan struct{}), make(chan error, len(headers))
  87. for i := 0; i < len(headers); i++ {
  88. results <- nil
  89. }
  90. return abort, results
  91. }
  92. // Spawn as many workers as allowed threads
  93. workers := runtime.GOMAXPROCS(0)
  94. if len(headers) < workers {
  95. workers = len(headers)
  96. }
  97. // Create a task channel and spawn the verifiers
  98. type result struct {
  99. index int
  100. err error
  101. }
  102. inputs := make(chan int, workers)
  103. outputs := make(chan result, len(headers))
  104. var badblock uint64
  105. for i := 0; i < workers; i++ {
  106. go func() {
  107. for index := range inputs {
  108. // If we've found a bad block already before this, stop validating
  109. if bad := atomic.LoadUint64(&badblock); bad != 0 && bad <= headers[index].Number.Uint64() {
  110. outputs <- result{index: index, err: errInvalidChain}
  111. continue
  112. }
  113. // We need to look up the first parent
  114. var parent *types.Header
  115. if index == 0 {
  116. parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
  117. } else if headers[index-1].Hash() == headers[index].ParentHash {
  118. parent = headers[index-1]
  119. }
  120. // Ensure the validation is useful and execute it
  121. var failure error
  122. switch {
  123. case chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()-1) != nil:
  124. outputs <- result{index: index, err: nil}
  125. case parent == nil:
  126. failure = consensus.ErrUnknownAncestor
  127. outputs <- result{index: index, err: failure}
  128. default:
  129. failure = ethash.verifyHeader(chain, headers[index], parent, false, seals[index])
  130. outputs <- result{index: index, err: failure}
  131. }
  132. // If a validation failure occurred, mark subsequent blocks invalid
  133. if failure != nil {
  134. number := headers[index].Number.Uint64()
  135. if prev := atomic.LoadUint64(&badblock); prev == 0 || prev > number {
  136. // This two step atomic op isn't thread-safe in that `badblock` might end
  137. // up slightly higher than the block number of the first failure (if many
  138. // workers try to write at the same time), but it's fine as we're mostly
  139. // interested to avoid large useless work, we don't care about 1-2 extra
  140. // runs. Doing "full thread safety" would involve mutexes, which would be
  141. // a noticeable sync overhead on the fast spinning worker routines.
  142. atomic.StoreUint64(&badblock, number)
  143. }
  144. }
  145. }
  146. }()
  147. }
  148. // Feed item indices to the workers until done, sorting and feeding the results to the caller
  149. dones := make([]bool, len(headers))
  150. errors := make([]error, len(headers))
  151. abort := make(chan struct{})
  152. returns := make(chan error, len(headers))
  153. go func() {
  154. defer close(inputs)
  155. input, output := 0, 0
  156. for i := 0; i < len(headers)*2; i++ {
  157. var res result
  158. // If there are tasks left, push to workers
  159. if input < len(headers) {
  160. select {
  161. case inputs <- input:
  162. input++
  163. continue
  164. case <-abort:
  165. return
  166. case res = <-outputs:
  167. }
  168. } else {
  169. // Otherwise keep waiting for results
  170. select {
  171. case <-abort:
  172. return
  173. case res = <-outputs:
  174. }
  175. }
  176. // A result arrived, save and propagate if next
  177. dones[res.index], errors[res.index] = true, res.err
  178. for output < len(headers) && dones[output] {
  179. returns <- errors[output]
  180. output++
  181. }
  182. }
  183. }()
  184. return abort, returns
  185. }
  186. // VerifyUncles verifies that the given block's uncles conform to the consensus
  187. // rules of the stock Ethereum ethash engine.
  188. func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
  189. // If we're running a full engine faking, accept any input as valid
  190. if ethash.fakeFull {
  191. return nil
  192. }
  193. // Verify that there are at most 2 uncles included in this block
  194. if len(block.Uncles()) > maxUncles {
  195. return errTooManyUncles
  196. }
  197. // Gather the set of past uncles and ancestors
  198. uncles, ancestors := set.New(), make(map[common.Hash]*types.Header)
  199. number, parent := block.NumberU64()-1, block.ParentHash()
  200. for i := 0; i < 7; i++ {
  201. ancestor := chain.GetBlock(parent, number)
  202. if ancestor == nil {
  203. break
  204. }
  205. ancestors[ancestor.Hash()] = ancestor.Header()
  206. for _, uncle := range ancestor.Uncles() {
  207. uncles.Add(uncle.Hash())
  208. }
  209. parent, number = ancestor.ParentHash(), number-1
  210. }
  211. ancestors[block.Hash()] = block.Header()
  212. uncles.Add(block.Hash())
  213. // Verify each of the uncles that it's recent, but not an ancestor
  214. for _, uncle := range block.Uncles() {
  215. // Make sure every uncle is rewarded only once
  216. hash := uncle.Hash()
  217. if uncles.Has(hash) {
  218. return errDuplicateUncle
  219. }
  220. uncles.Add(hash)
  221. // Make sure the uncle has a valid ancestry
  222. if ancestors[hash] != nil {
  223. return errUncleIsAncestor
  224. }
  225. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
  226. return errDanglingUncle
  227. }
  228. if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
  229. return err
  230. }
  231. }
  232. return nil
  233. }
  234. // verifyHeader checks whether a header conforms to the consensus rules of the
  235. // stock Ethereum ethash engine.
  236. //
  237. // See YP section 4.3.4. "Block Header Validity"
  238. func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error {
  239. // Ensure that the header's extra-data section is of a reasonable size
  240. if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
  241. return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
  242. }
  243. // Verify the header's timestamp
  244. if uncle {
  245. if header.Time.Cmp(math.MaxBig256) > 0 {
  246. return errLargeBlockTime
  247. }
  248. } else {
  249. if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
  250. return consensus.ErrFutureBlock
  251. }
  252. }
  253. if header.Time.Cmp(parent.Time) <= 0 {
  254. return errZeroBlockTime
  255. }
  256. // Verify the block's difficulty based in it's timestamp and parent's difficulty
  257. expected := CalcDifficulty(chain.Config(), header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
  258. if expected.Cmp(header.Difficulty) != 0 {
  259. return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
  260. }
  261. // Verify that the gas limit remains within allowed bounds
  262. diff := new(big.Int).Set(parent.GasLimit)
  263. diff = diff.Sub(diff, header.GasLimit)
  264. diff.Abs(diff)
  265. limit := new(big.Int).Set(parent.GasLimit)
  266. limit = limit.Div(limit, params.GasLimitBoundDivisor)
  267. if diff.Cmp(limit) >= 0 || header.GasLimit.Cmp(params.MinGasLimit) < 0 {
  268. return fmt.Errorf("invalid gas limit: have %v, want %v += %v", header.GasLimit, parent.GasLimit, limit)
  269. }
  270. // Verify that the block number is parent's +1
  271. if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
  272. return consensus.ErrInvalidNumber
  273. }
  274. // Verify the engine specific seal securing the block
  275. if seal {
  276. if err := ethash.VerifySeal(chain, header); err != nil {
  277. return err
  278. }
  279. }
  280. // If all checks passed, validate any special fields for hard forks
  281. if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
  282. return err
  283. }
  284. if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
  285. return err
  286. }
  287. return nil
  288. }
  289. // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
  290. // that a new block should have when created at time given the parent block's time
  291. // and difficulty.
  292. //
  293. // TODO (karalabe): Move the chain maker into this package and make this private!
  294. func CalcDifficulty(config *params.ChainConfig, time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  295. if config.IsHomestead(new(big.Int).Add(parentNumber, common.Big1)) {
  296. return calcDifficultyHomestead(time, parentTime, parentNumber, parentDiff)
  297. }
  298. return calcDifficultyFrontier(time, parentTime, parentNumber, parentDiff)
  299. }
  300. // Some weird constants to avoid constant memory allocs for them.
  301. var (
  302. expDiffPeriod = big.NewInt(100000)
  303. big10 = big.NewInt(10)
  304. bigMinus99 = big.NewInt(-99)
  305. )
  306. // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
  307. // the difficulty that a new block should have when created at time given the
  308. // parent block's time and difficulty. The calculation uses the Homestead rules.
  309. func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  310. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki
  311. // algorithm:
  312. // diff = (parent_diff +
  313. // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  314. // ) + 2^(periodCount - 2)
  315. bigTime := new(big.Int).SetUint64(time)
  316. bigParentTime := new(big.Int).SetUint64(parentTime)
  317. // holds intermediate values to make the algo easier to read & audit
  318. x := new(big.Int)
  319. y := new(big.Int)
  320. // 1 - (block_timestamp -parent_timestamp) // 10
  321. x.Sub(bigTime, bigParentTime)
  322. x.Div(x, big10)
  323. x.Sub(common.Big1, x)
  324. // max(1 - (block_timestamp - parent_timestamp) // 10, -99)))
  325. if x.Cmp(bigMinus99) < 0 {
  326. x.Set(bigMinus99)
  327. }
  328. // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  329. y.Div(parentDiff, params.DifficultyBoundDivisor)
  330. x.Mul(y, x)
  331. x.Add(parentDiff, x)
  332. // minimum difficulty can ever be (before exponential factor)
  333. if x.Cmp(params.MinimumDifficulty) < 0 {
  334. x.Set(params.MinimumDifficulty)
  335. }
  336. // for the exponential factor
  337. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  338. periodCount.Div(periodCount, expDiffPeriod)
  339. // the exponential factor, commonly referred to as "the bomb"
  340. // diff = diff + 2^(periodCount - 2)
  341. if periodCount.Cmp(common.Big1) > 0 {
  342. y.Sub(periodCount, common.Big2)
  343. y.Exp(common.Big2, y, nil)
  344. x.Add(x, y)
  345. }
  346. return x
  347. }
  348. // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
  349. // difficulty that a new block should have when created at time given the parent
  350. // block's time and difficulty. The calculation uses the Frontier rules.
  351. func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
  352. diff := new(big.Int)
  353. adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
  354. bigTime := new(big.Int)
  355. bigParentTime := new(big.Int)
  356. bigTime.SetUint64(time)
  357. bigParentTime.SetUint64(parentTime)
  358. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  359. diff.Add(parentDiff, adjust)
  360. } else {
  361. diff.Sub(parentDiff, adjust)
  362. }
  363. if diff.Cmp(params.MinimumDifficulty) < 0 {
  364. diff.Set(params.MinimumDifficulty)
  365. }
  366. periodCount := new(big.Int).Add(parentNumber, common.Big1)
  367. periodCount.Div(periodCount, expDiffPeriod)
  368. if periodCount.Cmp(common.Big1) > 0 {
  369. // diff = diff + 2^(periodCount - 2)
  370. expDiff := periodCount.Sub(periodCount, common.Big2)
  371. expDiff.Exp(common.Big2, expDiff, nil)
  372. diff.Add(diff, expDiff)
  373. diff = math.BigMax(diff, params.MinimumDifficulty)
  374. }
  375. return diff
  376. }
  377. // VerifySeal implements consensus.Engine, checking whether the given block satisfies
  378. // the PoW difficulty requirements.
  379. func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
  380. // If we're running a fake PoW, accept any seal as valid
  381. if ethash.fakeMode {
  382. time.Sleep(ethash.fakeDelay)
  383. if ethash.fakeFail == header.Number.Uint64() {
  384. return errInvalidPoW
  385. }
  386. return nil
  387. }
  388. // If we're running a shared PoW, delegate verification to it
  389. if ethash.shared != nil {
  390. return ethash.shared.VerifySeal(chain, header)
  391. }
  392. // Sanity check that the block number is below the lookup table size (60M blocks)
  393. number := header.Number.Uint64()
  394. if number/epochLength >= uint64(len(cacheSizes)) {
  395. // Go < 1.7 cannot calculate new cache/dataset sizes (no fast prime check)
  396. return errNonceOutOfRange
  397. }
  398. // Ensure that we have a valid difficulty for the block
  399. if header.Difficulty.Sign() <= 0 {
  400. return errInvalidDifficulty
  401. }
  402. // Recompute the digest and PoW value and verify against the header
  403. cache := ethash.cache(number)
  404. size := datasetSize(number)
  405. if ethash.tester {
  406. size = 32 * 1024
  407. }
  408. digest, result := hashimotoLight(size, cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64())
  409. if !bytes.Equal(header.MixDigest[:], digest) {
  410. return errInvalidMixDigest
  411. }
  412. target := new(big.Int).Div(maxUint256, header.Difficulty)
  413. if new(big.Int).SetBytes(result).Cmp(target) > 0 {
  414. return errInvalidPoW
  415. }
  416. return nil
  417. }
  418. // Prepare implements consensus.Engine, initializing the difficulty field of a
  419. // header to conform to the ethash protocol. The changes are done inline.
  420. func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
  421. parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
  422. if parent == nil {
  423. return consensus.ErrUnknownAncestor
  424. }
  425. header.Difficulty = CalcDifficulty(chain.Config(), header.Time.Uint64(),
  426. parent.Time.Uint64(), parent.Number, parent.Difficulty)
  427. return nil
  428. }
  429. // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
  430. // setting the final state and assembling the block.
  431. func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
  432. // Accumulate any block and uncle rewards and commit the final state root
  433. AccumulateRewards(state, header, uncles)
  434. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  435. // Header seems complete, assemble into a block and return
  436. return types.NewBlock(header, txs, uncles, receipts), nil
  437. }
  438. // Some weird constants to avoid constant memory allocs for them.
  439. var (
  440. big8 = big.NewInt(8)
  441. big32 = big.NewInt(32)
  442. )
  443. // AccumulateRewards credits the coinbase of the given block with the mining
  444. // reward. The total reward consists of the static block reward and rewards for
  445. // included uncles. The coinbase of each uncle block is also rewarded.
  446. //
  447. // TODO (karalabe): Move the chain maker into this package and make this private!
  448. func AccumulateRewards(state *state.StateDB, header *types.Header, uncles []*types.Header) {
  449. reward := new(big.Int).Set(blockReward)
  450. r := new(big.Int)
  451. for _, uncle := range uncles {
  452. r.Add(uncle.Number, big8)
  453. r.Sub(r, header.Number)
  454. r.Mul(r, blockReward)
  455. r.Div(r, big8)
  456. state.AddBalance(uncle.Coinbase, r)
  457. r.Div(blockReward, big32)
  458. reward.Add(reward, r)
  459. }
  460. state.AddBalance(header.Coinbase, reward)
  461. }