consensus.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. mapset "github.com/deckarep/golang-set"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/gopool"
  27. "github.com/ethereum/go-ethereum/common/math"
  28. "github.com/ethereum/go-ethereum/consensus"
  29. "github.com/ethereum/go-ethereum/consensus/misc"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. "github.com/ethereum/go-ethereum/trie"
  35. "golang.org/x/crypto/sha3"
  36. )
  37. // Ethash proof-of-work protocol constants.
  38. var (
  39. FrontierBlockReward = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
  40. ByzantiumBlockReward = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
  41. ConstantinopleBlockReward = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
  42. maxUncles = 2 // Maximum number of uncles allowed in a single block
  43. allowedFutureBlockTimeSeconds = int64(15) // Max seconds from current time allowed for blocks, before they're considered future blocks
  44. // calcDifficultyEip2384 is the difficulty adjustment algorithm as specified by EIP 2384.
  45. // It offsets the bomb 4M blocks from Constantinople, so in total 9M blocks.
  46. // Specification EIP-2384: https://eips.ethereum.org/EIPS/eip-2384
  47. calcDifficultyEip2384 = makeDifficultyCalculator(big.NewInt(9000000))
  48. // calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
  49. // It returns the difficulty that a new block should have when created at time given the
  50. // parent block's time and difficulty. The calculation uses the Byzantium rules, but with
  51. // bomb offset 5M.
  52. // Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
  53. calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
  54. // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
  55. // the difficulty that a new block should have when created at time given the
  56. // parent block's time and difficulty. The calculation uses the Byzantium rules.
  57. // Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
  58. calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
  59. )
  60. // Various error messages to mark blocks invalid. These should be private to
  61. // prevent engine specific errors from being referenced in the remainder of the
  62. // codebase, inherently breaking if the engine is swapped out. Please put common
  63. // error types into the consensus package.
  64. var (
  65. errOlderBlockTime = errors.New("timestamp older than parent")
  66. errTooManyUncles = errors.New("too many uncles")
  67. errDuplicateUncle = errors.New("duplicate uncle")
  68. errUncleIsAncestor = errors.New("uncle is ancestor")
  69. errDanglingUncle = errors.New("uncle's parent is not ancestor")
  70. errInvalidDifficulty = errors.New("non-positive difficulty")
  71. errInvalidMixDigest = errors.New("invalid mix digest")
  72. errInvalidPoW = errors.New("invalid proof-of-work")
  73. )
  74. // Author implements consensus.Engine, returning the header's coinbase as the
  75. // proof-of-work verified author of the block.
  76. func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
  77. return header.Coinbase, nil
  78. }
  79. // VerifyHeader checks whether a header conforms to the consensus rules of the
  80. // stock Ethereum ethash engine.
  81. func (ethash *Ethash) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
  82. // If we're running a full engine faking, accept any input as valid
  83. if ethash.config.PowMode == ModeFullFake {
  84. return nil
  85. }
  86. // Short circuit if the header is known, or its parent not
  87. number := header.Number.Uint64()
  88. if chain.GetHeader(header.Hash(), number) != nil {
  89. return nil
  90. }
  91. parent := chain.GetHeader(header.ParentHash, number-1)
  92. if parent == nil {
  93. return consensus.ErrUnknownAncestor
  94. }
  95. // Sanity checks passed, do a proper verification
  96. return ethash.verifyHeader(chain, header, parent, false, seal, time.Now().Unix())
  97. }
  98. // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
  99. // concurrently. The method returns a quit channel to abort the operations and
  100. // a results channel to retrieve the async verifications.
  101. func (ethash *Ethash) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  102. // If we're running a full engine faking, accept any input as valid
  103. if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
  104. abort, results := make(chan struct{}), make(chan error, len(headers))
  105. for i := 0; i < len(headers); i++ {
  106. results <- nil
  107. }
  108. return abort, results
  109. }
  110. // Spawn as many workers as allowed threads
  111. workers := runtime.GOMAXPROCS(0)
  112. if len(headers) < workers {
  113. workers = len(headers)
  114. }
  115. // Create a task channel and spawn the verifiers
  116. var (
  117. inputs = make(chan int)
  118. done = make(chan int, workers)
  119. errors = make([]error, len(headers))
  120. abort = make(chan struct{})
  121. unixNow = time.Now().Unix()
  122. )
  123. for i := 0; i < workers; i++ {
  124. gopool.Submit(func() {
  125. for index := range inputs {
  126. errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index, unixNow)
  127. done <- index
  128. }
  129. })
  130. }
  131. errorsOut := make(chan error, len(headers))
  132. gopool.Submit(func() {
  133. defer close(inputs)
  134. var (
  135. in, out = 0, 0
  136. checked = make([]bool, len(headers))
  137. inputs = inputs
  138. )
  139. for {
  140. select {
  141. case inputs <- in:
  142. if in++; in == len(headers) {
  143. // Reached end of headers. Stop sending to workers.
  144. inputs = nil
  145. }
  146. case index := <-done:
  147. for checked[index] = true; checked[out]; out++ {
  148. errorsOut <- errors[out]
  149. if out == len(headers)-1 {
  150. return
  151. }
  152. }
  153. case <-abort:
  154. return
  155. }
  156. }
  157. })
  158. return abort, errorsOut
  159. }
  160. func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int, unixNow int64) error {
  161. var parent *types.Header
  162. if index == 0 {
  163. parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
  164. } else if headers[index-1].Hash() == headers[index].ParentHash {
  165. parent = headers[index-1]
  166. }
  167. if parent == nil {
  168. return consensus.ErrUnknownAncestor
  169. }
  170. return ethash.verifyHeader(chain, headers[index], parent, false, seals[index], unixNow)
  171. }
  172. // VerifyUncles verifies that the given block's uncles conform to the consensus
  173. // rules of the stock Ethereum ethash engine.
  174. func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
  175. // If we're running a full engine faking, accept any input as valid
  176. if ethash.config.PowMode == ModeFullFake {
  177. return nil
  178. }
  179. // Verify that there are at most 2 uncles included in this block
  180. if len(block.Uncles()) > maxUncles {
  181. return errTooManyUncles
  182. }
  183. if len(block.Uncles()) == 0 {
  184. return nil
  185. }
  186. // Gather the set of past uncles and ancestors
  187. uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
  188. number, parent := block.NumberU64()-1, block.ParentHash()
  189. for i := 0; i < 7; i++ {
  190. ancestorHeader := chain.GetHeader(parent, number)
  191. if ancestorHeader == nil {
  192. break
  193. }
  194. ancestors[parent] = ancestorHeader
  195. // If the ancestor doesn't have any uncles, we don't have to iterate them
  196. if ancestorHeader.UncleHash != types.EmptyUncleHash {
  197. // Need to add those uncles to the blacklist too
  198. ancestor := chain.GetBlock(parent, number)
  199. if ancestor == nil {
  200. break
  201. }
  202. for _, uncle := range ancestor.Uncles() {
  203. uncles.Add(uncle.Hash())
  204. }
  205. }
  206. parent, number = ancestorHeader.ParentHash, number-1
  207. }
  208. ancestors[block.Hash()] = block.Header()
  209. uncles.Add(block.Hash())
  210. // Verify each of the uncles that it's recent, but not an ancestor
  211. for _, uncle := range block.Uncles() {
  212. // Make sure every uncle is rewarded only once
  213. hash := uncle.Hash()
  214. if uncles.Contains(hash) {
  215. return errDuplicateUncle
  216. }
  217. uncles.Add(hash)
  218. // Make sure the uncle has a valid ancestry
  219. if ancestors[hash] != nil {
  220. return errUncleIsAncestor
  221. }
  222. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
  223. return errDanglingUncle
  224. }
  225. if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true, time.Now().Unix()); err != nil {
  226. return err
  227. }
  228. }
  229. return nil
  230. }
  231. // verifyHeader checks whether a header conforms to the consensus rules of the
  232. // stock Ethereum ethash engine.
  233. // See YP section 4.3.4. "Block Header Validity"
  234. func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool, unixNow int64) error {
  235. // Ensure that the header's extra-data section is of a reasonable size
  236. if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
  237. return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
  238. }
  239. // Verify the header's timestamp
  240. if !uncle {
  241. if header.Time > uint64(unixNow+allowedFutureBlockTimeSeconds) {
  242. return consensus.ErrFutureBlock
  243. }
  244. }
  245. if header.Time <= parent.Time {
  246. return errOlderBlockTime
  247. }
  248. // Verify the block's difficulty based on its timestamp and parent's difficulty
  249. expected := ethash.CalcDifficulty(chain, header.Time, parent)
  250. if expected.Cmp(header.Difficulty) != 0 {
  251. return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
  252. }
  253. // Verify that the gas limit is <= 2^63-1
  254. cap := uint64(0x7fffffffffffffff)
  255. if header.GasLimit > cap {
  256. return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
  257. }
  258. // Verify that the gasUsed is <= gasLimit
  259. if header.GasUsed > header.GasLimit {
  260. return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
  261. }
  262. // Verify that the gas limit remains within allowed bounds
  263. diff := int64(parent.GasLimit) - int64(header.GasLimit)
  264. if diff < 0 {
  265. diff *= -1
  266. }
  267. limit := parent.GasLimit / params.GasLimitBoundDivisor
  268. if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
  269. return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
  270. }
  271. // Verify that the block number is parent's +1
  272. if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
  273. return consensus.ErrInvalidNumber
  274. }
  275. // Verify the engine specific seal securing the block
  276. if seal {
  277. if err := ethash.verifySeal(chain, header, false); err != nil {
  278. return err
  279. }
  280. }
  281. // If all checks passed, validate any special fields for hard forks
  282. if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
  283. return err
  284. }
  285. if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
  286. return err
  287. }
  288. return nil
  289. }
  290. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  291. // the difficulty that a new block should have when created at time
  292. // given the parent block's time and difficulty.
  293. func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  294. return CalcDifficulty(chain.Config(), time, parent)
  295. }
  296. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  297. // the difficulty that a new block should have when created at time
  298. // given the parent block's time and difficulty.
  299. func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
  300. next := new(big.Int).Add(parent.Number, big1)
  301. switch {
  302. case config.IsCatalyst(next):
  303. return big.NewInt(1)
  304. case config.IsMuirGlacier(next):
  305. return calcDifficultyEip2384(time, parent)
  306. case config.IsConstantinople(next):
  307. return calcDifficultyConstantinople(time, parent)
  308. case config.IsByzantium(next):
  309. return calcDifficultyByzantium(time, parent)
  310. case config.IsHomestead(next):
  311. return calcDifficultyHomestead(time, parent)
  312. default:
  313. return calcDifficultyFrontier(time, parent)
  314. }
  315. }
  316. // Some weird constants to avoid constant memory allocs for them.
  317. var (
  318. expDiffPeriod = big.NewInt(100000)
  319. big1 = big.NewInt(1)
  320. big2 = big.NewInt(2)
  321. big9 = big.NewInt(9)
  322. big10 = big.NewInt(10)
  323. bigMinus99 = big.NewInt(-99)
  324. )
  325. // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
  326. // the difficulty is calculated with Byzantium rules, which differs from Homestead in
  327. // how uncles affect the calculation
  328. func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
  329. // Note, the calculations below looks at the parent number, which is 1 below
  330. // the block number. Thus we remove one from the delay given
  331. bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
  332. return func(time uint64, parent *types.Header) *big.Int {
  333. // https://github.com/ethereum/EIPs/issues/100.
  334. // algorithm:
  335. // diff = (parent_diff +
  336. // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  337. // ) + 2^(periodCount - 2)
  338. bigTime := new(big.Int).SetUint64(time)
  339. bigParentTime := new(big.Int).SetUint64(parent.Time)
  340. // holds intermediate values to make the algo easier to read & audit
  341. x := new(big.Int)
  342. y := new(big.Int)
  343. // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
  344. x.Sub(bigTime, bigParentTime)
  345. x.Div(x, big9)
  346. if parent.UncleHash == types.EmptyUncleHash {
  347. x.Sub(big1, x)
  348. } else {
  349. x.Sub(big2, x)
  350. }
  351. // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
  352. if x.Cmp(bigMinus99) < 0 {
  353. x.Set(bigMinus99)
  354. }
  355. // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  356. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  357. x.Mul(y, x)
  358. x.Add(parent.Difficulty, x)
  359. // minimum difficulty can ever be (before exponential factor)
  360. if x.Cmp(params.MinimumDifficulty) < 0 {
  361. x.Set(params.MinimumDifficulty)
  362. }
  363. // calculate a fake block number for the ice-age delay
  364. // Specification: https://eips.ethereum.org/EIPS/eip-1234
  365. fakeBlockNumber := new(big.Int)
  366. if parent.Number.Cmp(bombDelayFromParent) >= 0 {
  367. fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
  368. }
  369. // for the exponential factor
  370. periodCount := fakeBlockNumber
  371. periodCount.Div(periodCount, expDiffPeriod)
  372. // the exponential factor, commonly referred to as "the bomb"
  373. // diff = diff + 2^(periodCount - 2)
  374. if periodCount.Cmp(big1) > 0 {
  375. y.Sub(periodCount, big2)
  376. y.Exp(big2, y, nil)
  377. x.Add(x, y)
  378. }
  379. return x
  380. }
  381. }
  382. // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
  383. // the difficulty that a new block should have when created at time given the
  384. // parent block's time and difficulty. The calculation uses the Homestead rules.
  385. func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
  386. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
  387. // algorithm:
  388. // diff = (parent_diff +
  389. // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  390. // ) + 2^(periodCount - 2)
  391. bigTime := new(big.Int).SetUint64(time)
  392. bigParentTime := new(big.Int).SetUint64(parent.Time)
  393. // holds intermediate values to make the algo easier to read & audit
  394. x := new(big.Int)
  395. y := new(big.Int)
  396. // 1 - (block_timestamp - parent_timestamp) // 10
  397. x.Sub(bigTime, bigParentTime)
  398. x.Div(x, big10)
  399. x.Sub(big1, x)
  400. // max(1 - (block_timestamp - parent_timestamp) // 10, -99)
  401. if x.Cmp(bigMinus99) < 0 {
  402. x.Set(bigMinus99)
  403. }
  404. // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  405. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  406. x.Mul(y, x)
  407. x.Add(parent.Difficulty, x)
  408. // minimum difficulty can ever be (before exponential factor)
  409. if x.Cmp(params.MinimumDifficulty) < 0 {
  410. x.Set(params.MinimumDifficulty)
  411. }
  412. // for the exponential factor
  413. periodCount := new(big.Int).Add(parent.Number, big1)
  414. periodCount.Div(periodCount, expDiffPeriod)
  415. // the exponential factor, commonly referred to as "the bomb"
  416. // diff = diff + 2^(periodCount - 2)
  417. if periodCount.Cmp(big1) > 0 {
  418. y.Sub(periodCount, big2)
  419. y.Exp(big2, y, nil)
  420. x.Add(x, y)
  421. }
  422. return x
  423. }
  424. // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
  425. // difficulty that a new block should have when created at time given the parent
  426. // block's time and difficulty. The calculation uses the Frontier rules.
  427. func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
  428. diff := new(big.Int)
  429. adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
  430. bigTime := new(big.Int)
  431. bigParentTime := new(big.Int)
  432. bigTime.SetUint64(time)
  433. bigParentTime.SetUint64(parent.Time)
  434. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  435. diff.Add(parent.Difficulty, adjust)
  436. } else {
  437. diff.Sub(parent.Difficulty, adjust)
  438. }
  439. if diff.Cmp(params.MinimumDifficulty) < 0 {
  440. diff.Set(params.MinimumDifficulty)
  441. }
  442. periodCount := new(big.Int).Add(parent.Number, big1)
  443. periodCount.Div(periodCount, expDiffPeriod)
  444. if periodCount.Cmp(big1) > 0 {
  445. // diff = diff + 2^(periodCount - 2)
  446. expDiff := periodCount.Sub(periodCount, big2)
  447. expDiff.Exp(big2, expDiff, nil)
  448. diff.Add(diff, expDiff)
  449. diff = math.BigMax(diff, params.MinimumDifficulty)
  450. }
  451. return diff
  452. }
  453. // Exported for fuzzing
  454. var FrontierDifficultyCalulator = calcDifficultyFrontier
  455. var HomesteadDifficultyCalulator = calcDifficultyHomestead
  456. var DynamicDifficultyCalculator = makeDifficultyCalculator
  457. // verifySeal checks whether a block satisfies the PoW difficulty requirements,
  458. // either using the usual ethash cache for it, or alternatively using a full DAG
  459. // to make remote mining fast.
  460. func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
  461. // If we're running a fake PoW, accept any seal as valid
  462. if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
  463. time.Sleep(ethash.fakeDelay)
  464. if ethash.fakeFail == header.Number.Uint64() {
  465. return errInvalidPoW
  466. }
  467. return nil
  468. }
  469. // If we're running a shared PoW, delegate verification to it
  470. if ethash.shared != nil {
  471. return ethash.shared.verifySeal(chain, header, fulldag)
  472. }
  473. // Ensure that we have a valid difficulty for the block
  474. if header.Difficulty.Sign() <= 0 {
  475. return errInvalidDifficulty
  476. }
  477. // Recompute the digest and PoW values
  478. number := header.Number.Uint64()
  479. var (
  480. digest []byte
  481. result []byte
  482. )
  483. // If fast-but-heavy PoW verification was requested, use an ethash dataset
  484. if fulldag {
  485. dataset := ethash.dataset(number, true)
  486. if dataset.generated() {
  487. digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  488. // Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
  489. // until after the call to hashimotoFull so it's not unmapped while being used.
  490. runtime.KeepAlive(dataset)
  491. } else {
  492. // Dataset not yet generated, don't hang, use a cache instead
  493. fulldag = false
  494. }
  495. }
  496. // If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
  497. if !fulldag {
  498. cache := ethash.cache(number)
  499. size := datasetSize(number)
  500. if ethash.config.PowMode == ModeTest {
  501. size = 32 * 1024
  502. }
  503. digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  504. // Caches are unmapped in a finalizer. Ensure that the cache stays alive
  505. // until after the call to hashimotoLight so it's not unmapped while being used.
  506. runtime.KeepAlive(cache)
  507. }
  508. // Verify the calculated values against the ones provided in the header
  509. if !bytes.Equal(header.MixDigest[:], digest) {
  510. return errInvalidMixDigest
  511. }
  512. target := new(big.Int).Div(two256, header.Difficulty)
  513. if new(big.Int).SetBytes(result).Cmp(target) > 0 {
  514. return errInvalidPoW
  515. }
  516. return nil
  517. }
  518. // Prepare implements consensus.Engine, initializing the difficulty field of a
  519. // header to conform to the ethash protocol. The changes are done inline.
  520. func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
  521. parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
  522. if parent == nil {
  523. return consensus.ErrUnknownAncestor
  524. }
  525. header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
  526. return nil
  527. }
  528. func (ethash *Ethash) BeforeValidateTx(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs *[]*types.Transaction, uncles []*types.Header,
  529. receipts *[]*types.Receipt, _ *[]*types.Transaction, _ *uint64) (err error) {
  530. return
  531. }
  532. func (ethash *Ethash) BeforePackTx(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB,
  533. txs *[]*types.Transaction, uncles []*types.Header, receipts *[]*types.Receipt) (err error) {
  534. return
  535. }
  536. // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
  537. // setting the final state on the header
  538. func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs *[]*types.Transaction, uncles []*types.Header,
  539. receipts *[]*types.Receipt, _ *[]*types.Transaction, _ *uint64) (err error) {
  540. // Accumulate any block and uncle rewards and commit the final state root
  541. accumulateRewards(chain.Config(), state, header, uncles)
  542. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  543. return
  544. }
  545. // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
  546. // uncle rewards, setting the final state and assembling the block.
  547. func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB,
  548. txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, []*types.Receipt, error) {
  549. ethash.Finalize(chain, header, state, &txs, uncles, nil, nil, nil)
  550. // Header seems complete, assemble into a block and return
  551. return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), receipts, nil
  552. }
  553. func (ethash *Ethash) Delay(_ consensus.ChainReader, _ *types.Header) *time.Duration {
  554. return nil
  555. }
  556. // SealHash returns the hash of a block prior to it being sealed.
  557. func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
  558. hasher := sha3.NewLegacyKeccak256()
  559. rlp.Encode(hasher, []interface{}{
  560. header.ParentHash,
  561. header.UncleHash,
  562. header.Coinbase,
  563. header.Root,
  564. header.TxHash,
  565. header.ReceiptHash,
  566. header.Bloom,
  567. header.Difficulty,
  568. header.Number,
  569. header.GasLimit,
  570. header.GasUsed,
  571. header.Time,
  572. header.Extra,
  573. })
  574. hasher.Sum(hash[:0])
  575. return hash
  576. }
  577. // Some weird constants to avoid constant memory allocs for them.
  578. var (
  579. big8 = big.NewInt(8)
  580. big32 = big.NewInt(32)
  581. )
  582. // AccumulateRewards credits the coinbase of the given block with the mining
  583. // reward. The total reward consists of the static block reward and rewards for
  584. // included uncles. The coinbase of each uncle block is also rewarded.
  585. func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
  586. // Skip block reward in catalyst mode
  587. if config.IsCatalyst(header.Number) {
  588. return
  589. }
  590. // Select the correct block reward based on chain progression
  591. blockReward := FrontierBlockReward
  592. if config.IsByzantium(header.Number) {
  593. blockReward = ByzantiumBlockReward
  594. }
  595. if config.IsConstantinople(header.Number) {
  596. blockReward = ConstantinopleBlockReward
  597. }
  598. // Accumulate the rewards for the miner and any included uncles
  599. reward := new(big.Int).Set(blockReward)
  600. r := new(big.Int)
  601. for _, uncle := range uncles {
  602. r.Add(uncle.Number, big8)
  603. r.Sub(r, header.Number)
  604. r.Mul(r, blockReward)
  605. r.Div(r, big8)
  606. state.AddBalance(uncle.Coinbase, r)
  607. r.Div(blockReward, big32)
  608. reward.Add(reward, r)
  609. }
  610. state.AddBalance(header.Coinbase, reward)
  611. }