consensus.go 16 KB

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