consensus.go 22 KB

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