consensus.go 23 KB

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