consensus.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. // calcDifficultyEip2384 is the difficulty adjustment algorithm as specified by EIP 2384.
  43. // It offsets the bomb 4M blocks from Constantinople, so in total 9M blocks.
  44. // Specification EIP-2384: https://eips.ethereum.org/EIPS/eip-2384
  45. calcDifficultyEip2384 = makeDifficultyCalculator(big.NewInt(9000000))
  46. // calcDifficultyConstantinople is the difficulty adjustment algorithm for Constantinople.
  47. // It returns the difficulty that a new block should have when created at time given the
  48. // parent block's time and difficulty. The calculation uses the Byzantium rules, but with
  49. // bomb offset 5M.
  50. // Specification EIP-1234: https://eips.ethereum.org/EIPS/eip-1234
  51. calcDifficultyConstantinople = makeDifficultyCalculator(big.NewInt(5000000))
  52. // calcDifficultyByzantium is the difficulty adjustment algorithm. It returns
  53. // the difficulty that a new block should have when created at time given the
  54. // parent block's time and difficulty. The calculation uses the Byzantium rules.
  55. // Specification EIP-649: https://eips.ethereum.org/EIPS/eip-649
  56. calcDifficultyByzantium = makeDifficultyCalculator(big.NewInt(3000000))
  57. )
  58. // Various error messages to mark blocks invalid. These should be private to
  59. // prevent engine specific errors from being referenced in the remainder of the
  60. // codebase, inherently breaking if the engine is swapped out. Please put common
  61. // error types into the consensus package.
  62. var (
  63. errOlderBlockTime = errors.New("timestamp older than parent")
  64. errTooManyUncles = errors.New("too many uncles")
  65. errDuplicateUncle = errors.New("duplicate uncle")
  66. errUncleIsAncestor = errors.New("uncle is ancestor")
  67. errDanglingUncle = errors.New("uncle's parent is not ancestor")
  68. errInvalidDifficulty = errors.New("non-positive difficulty")
  69. errInvalidMixDigest = errors.New("invalid mix digest")
  70. errInvalidPoW = errors.New("invalid proof-of-work")
  71. )
  72. // Author implements consensus.Engine, returning the header's coinbase as the
  73. // proof-of-work verified author of the block.
  74. func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
  75. return header.Coinbase, nil
  76. }
  77. // VerifyHeader checks whether a header conforms to the consensus rules of the
  78. // stock Ethereum ethash engine.
  79. func (ethash *Ethash) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
  80. // If we're running a full engine faking, accept any input as valid
  81. if ethash.config.PowMode == ModeFullFake {
  82. return nil
  83. }
  84. // Short circuit if the header is known, or its parent not
  85. number := header.Number.Uint64()
  86. if chain.GetHeader(header.Hash(), number) != nil {
  87. return nil
  88. }
  89. parent := chain.GetHeader(header.ParentHash, number-1)
  90. if parent == nil {
  91. return consensus.ErrUnknownAncestor
  92. }
  93. // Sanity checks passed, do a proper verification
  94. return ethash.verifyHeader(chain, header, parent, false, seal)
  95. }
  96. // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
  97. // concurrently. The method returns a quit channel to abort the operations and
  98. // a results channel to retrieve the async verifications.
  99. func (ethash *Ethash) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  100. // If we're running a full engine faking, accept any input as valid
  101. if ethash.config.PowMode == ModeFullFake || len(headers) == 0 {
  102. abort, results := make(chan struct{}), make(chan error, len(headers))
  103. for i := 0; i < len(headers); i++ {
  104. results <- nil
  105. }
  106. return abort, results
  107. }
  108. // Spawn as many workers as allowed threads
  109. workers := runtime.GOMAXPROCS(0)
  110. if len(headers) < workers {
  111. workers = len(headers)
  112. }
  113. // Create a task channel and spawn the verifiers
  114. var (
  115. inputs = make(chan int)
  116. done = make(chan int, workers)
  117. errors = make([]error, len(headers))
  118. abort = make(chan struct{})
  119. )
  120. for i := 0; i < workers; i++ {
  121. go func() {
  122. for index := range inputs {
  123. errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index)
  124. done <- index
  125. }
  126. }()
  127. }
  128. errorsOut := make(chan error, len(headers))
  129. go func() {
  130. defer close(inputs)
  131. var (
  132. in, out = 0, 0
  133. checked = make([]bool, len(headers))
  134. inputs = inputs
  135. )
  136. for {
  137. select {
  138. case inputs <- in:
  139. if in++; in == len(headers) {
  140. // Reached end of headers. Stop sending to workers.
  141. inputs = nil
  142. }
  143. case index := <-done:
  144. for checked[index] = true; checked[out]; out++ {
  145. errorsOut <- errors[out]
  146. if out == len(headers)-1 {
  147. return
  148. }
  149. }
  150. case <-abort:
  151. return
  152. }
  153. }
  154. }()
  155. return abort, errorsOut
  156. }
  157. func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int) error {
  158. var parent *types.Header
  159. if index == 0 {
  160. parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
  161. } else if headers[index-1].Hash() == headers[index].ParentHash {
  162. parent = headers[index-1]
  163. }
  164. if parent == nil {
  165. return consensus.ErrUnknownAncestor
  166. }
  167. if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil {
  168. return nil // known block
  169. }
  170. return ethash.verifyHeader(chain, headers[index], parent, false, seals[index])
  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. ancestor := chain.GetBlock(parent, number)
  191. if ancestor == nil {
  192. break
  193. }
  194. ancestors[ancestor.Hash()] = ancestor.Header()
  195. for _, uncle := range ancestor.Uncles() {
  196. uncles.Add(uncle.Hash())
  197. }
  198. parent, number = ancestor.ParentHash(), number-1
  199. }
  200. ancestors[block.Hash()] = block.Header()
  201. uncles.Add(block.Hash())
  202. // Verify each of the uncles that it's recent, but not an ancestor
  203. for _, uncle := range block.Uncles() {
  204. // Make sure every uncle is rewarded only once
  205. hash := uncle.Hash()
  206. if uncles.Contains(hash) {
  207. return errDuplicateUncle
  208. }
  209. uncles.Add(hash)
  210. // Make sure the uncle has a valid ancestry
  211. if ancestors[hash] != nil {
  212. return errUncleIsAncestor
  213. }
  214. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
  215. return errDanglingUncle
  216. }
  217. if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
  218. return err
  219. }
  220. }
  221. return nil
  222. }
  223. // verifyHeader checks whether a header conforms to the consensus rules of the
  224. // stock Ethereum ethash engine.
  225. // See YP section 4.3.4. "Block Header Validity"
  226. func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool) error {
  227. // Ensure that the header's extra-data section is of a reasonable size
  228. if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
  229. return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
  230. }
  231. // Verify the header's timestamp
  232. if !uncle {
  233. if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
  234. return consensus.ErrFutureBlock
  235. }
  236. }
  237. if header.Time <= parent.Time {
  238. return errOlderBlockTime
  239. }
  240. // Verify the block's difficulty based on its timestamp and parent's difficulty
  241. expected := ethash.CalcDifficulty(chain, header.Time, parent)
  242. if expected.Cmp(header.Difficulty) != 0 {
  243. return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
  244. }
  245. // Verify that the gas limit is <= 2^63-1
  246. cap := uint64(0x7fffffffffffffff)
  247. if header.GasLimit > cap {
  248. return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
  249. }
  250. // Verify that the gasUsed is <= gasLimit
  251. if header.GasUsed > header.GasLimit {
  252. return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
  253. }
  254. // Verify that the gas limit remains within allowed bounds
  255. diff := int64(parent.GasLimit) - int64(header.GasLimit)
  256. if diff < 0 {
  257. diff *= -1
  258. }
  259. limit := parent.GasLimit / params.GasLimitBoundDivisor
  260. if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
  261. return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
  262. }
  263. // Verify that the block number is parent's +1
  264. if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
  265. return consensus.ErrInvalidNumber
  266. }
  267. // Verify the engine specific seal securing the block
  268. if seal {
  269. if err := ethash.VerifySeal(chain, header); err != nil {
  270. return err
  271. }
  272. }
  273. // If all checks passed, validate any special fields for hard forks
  274. if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
  275. return err
  276. }
  277. if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
  278. return err
  279. }
  280. return nil
  281. }
  282. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  283. // the difficulty that a new block should have when created at time
  284. // given the parent block's time and difficulty.
  285. func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  286. return CalcDifficulty(chain.Config(), time, parent)
  287. }
  288. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  289. // the difficulty that a new block should have when created at time
  290. // given the parent block's time and difficulty.
  291. func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
  292. next := new(big.Int).Add(parent.Number, big1)
  293. switch {
  294. case config.IsMuirGlacier(next):
  295. return calcDifficultyEip2384(time, parent)
  296. case config.IsConstantinople(next):
  297. return calcDifficultyConstantinople(time, parent)
  298. case config.IsByzantium(next):
  299. return calcDifficultyByzantium(time, parent)
  300. case config.IsHomestead(next):
  301. return calcDifficultyHomestead(time, parent)
  302. default:
  303. return calcDifficultyFrontier(time, parent)
  304. }
  305. }
  306. // Some weird constants to avoid constant memory allocs for them.
  307. var (
  308. expDiffPeriod = big.NewInt(100000)
  309. big1 = big.NewInt(1)
  310. big2 = big.NewInt(2)
  311. big9 = big.NewInt(9)
  312. big10 = big.NewInt(10)
  313. bigMinus99 = big.NewInt(-99)
  314. )
  315. // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
  316. // the difficulty is calculated with Byzantium rules, which differs from Homestead in
  317. // how uncles affect the calculation
  318. func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
  319. // Note, the calculations below looks at the parent number, which is 1 below
  320. // the block number. Thus we remove one from the delay given
  321. bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
  322. return func(time uint64, parent *types.Header) *big.Int {
  323. // https://github.com/ethereum/EIPs/issues/100.
  324. // algorithm:
  325. // diff = (parent_diff +
  326. // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  327. // ) + 2^(periodCount - 2)
  328. bigTime := new(big.Int).SetUint64(time)
  329. bigParentTime := new(big.Int).SetUint64(parent.Time)
  330. // holds intermediate values to make the algo easier to read & audit
  331. x := new(big.Int)
  332. y := new(big.Int)
  333. // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
  334. x.Sub(bigTime, bigParentTime)
  335. x.Div(x, big9)
  336. if parent.UncleHash == types.EmptyUncleHash {
  337. x.Sub(big1, x)
  338. } else {
  339. x.Sub(big2, x)
  340. }
  341. // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
  342. if x.Cmp(bigMinus99) < 0 {
  343. x.Set(bigMinus99)
  344. }
  345. // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  346. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  347. x.Mul(y, x)
  348. x.Add(parent.Difficulty, x)
  349. // minimum difficulty can ever be (before exponential factor)
  350. if x.Cmp(params.MinimumDifficulty) < 0 {
  351. x.Set(params.MinimumDifficulty)
  352. }
  353. // calculate a fake block number for the ice-age delay
  354. // Specification: https://eips.ethereum.org/EIPS/eip-1234
  355. fakeBlockNumber := new(big.Int)
  356. if parent.Number.Cmp(bombDelayFromParent) >= 0 {
  357. fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
  358. }
  359. // for the exponential factor
  360. periodCount := fakeBlockNumber
  361. periodCount.Div(periodCount, expDiffPeriod)
  362. // the exponential factor, commonly referred to as "the bomb"
  363. // diff = diff + 2^(periodCount - 2)
  364. if periodCount.Cmp(big1) > 0 {
  365. y.Sub(periodCount, big2)
  366. y.Exp(big2, y, nil)
  367. x.Add(x, y)
  368. }
  369. return x
  370. }
  371. }
  372. // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
  373. // the difficulty that a new block should have when created at time given the
  374. // parent block's time and difficulty. The calculation uses the Homestead rules.
  375. func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
  376. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
  377. // algorithm:
  378. // diff = (parent_diff +
  379. // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  380. // ) + 2^(periodCount - 2)
  381. bigTime := new(big.Int).SetUint64(time)
  382. bigParentTime := new(big.Int).SetUint64(parent.Time)
  383. // holds intermediate values to make the algo easier to read & audit
  384. x := new(big.Int)
  385. y := new(big.Int)
  386. // 1 - (block_timestamp - parent_timestamp) // 10
  387. x.Sub(bigTime, bigParentTime)
  388. x.Div(x, big10)
  389. x.Sub(big1, x)
  390. // max(1 - (block_timestamp - parent_timestamp) // 10, -99)
  391. if x.Cmp(bigMinus99) < 0 {
  392. x.Set(bigMinus99)
  393. }
  394. // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  395. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  396. x.Mul(y, x)
  397. x.Add(parent.Difficulty, x)
  398. // minimum difficulty can ever be (before exponential factor)
  399. if x.Cmp(params.MinimumDifficulty) < 0 {
  400. x.Set(params.MinimumDifficulty)
  401. }
  402. // for the exponential factor
  403. periodCount := new(big.Int).Add(parent.Number, big1)
  404. periodCount.Div(periodCount, expDiffPeriod)
  405. // the exponential factor, commonly referred to as "the bomb"
  406. // diff = diff + 2^(periodCount - 2)
  407. if periodCount.Cmp(big1) > 0 {
  408. y.Sub(periodCount, big2)
  409. y.Exp(big2, y, nil)
  410. x.Add(x, y)
  411. }
  412. return x
  413. }
  414. // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
  415. // difficulty that a new block should have when created at time given the parent
  416. // block's time and difficulty. The calculation uses the Frontier rules.
  417. func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
  418. diff := new(big.Int)
  419. adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
  420. bigTime := new(big.Int)
  421. bigParentTime := new(big.Int)
  422. bigTime.SetUint64(time)
  423. bigParentTime.SetUint64(parent.Time)
  424. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  425. diff.Add(parent.Difficulty, adjust)
  426. } else {
  427. diff.Sub(parent.Difficulty, adjust)
  428. }
  429. if diff.Cmp(params.MinimumDifficulty) < 0 {
  430. diff.Set(params.MinimumDifficulty)
  431. }
  432. periodCount := new(big.Int).Add(parent.Number, big1)
  433. periodCount.Div(periodCount, expDiffPeriod)
  434. if periodCount.Cmp(big1) > 0 {
  435. // diff = diff + 2^(periodCount - 2)
  436. expDiff := periodCount.Sub(periodCount, big2)
  437. expDiff.Exp(big2, expDiff, nil)
  438. diff.Add(diff, expDiff)
  439. diff = math.BigMax(diff, params.MinimumDifficulty)
  440. }
  441. return diff
  442. }
  443. // VerifySeal implements consensus.Engine, checking whether the given block satisfies
  444. // the PoW difficulty requirements.
  445. func (ethash *Ethash) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error {
  446. return ethash.verifySeal(chain, header, false)
  447. }
  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. // Accumulate any block and uncle rewards and commit the final state root
  530. accumulateRewards(chain.Config(), state, header, uncles)
  531. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  532. // Header seems complete, assemble into a block and return
  533. return types.NewBlock(header, txs, uncles, receipts), nil
  534. }
  535. // SealHash returns the hash of a block prior to it being sealed.
  536. func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
  537. hasher := sha3.NewLegacyKeccak256()
  538. rlp.Encode(hasher, []interface{}{
  539. header.ParentHash,
  540. header.UncleHash,
  541. header.Coinbase,
  542. header.Root,
  543. header.TxHash,
  544. header.ReceiptHash,
  545. header.Bloom,
  546. header.Difficulty,
  547. header.Number,
  548. header.GasLimit,
  549. header.GasUsed,
  550. header.Time,
  551. header.Extra,
  552. })
  553. hasher.Sum(hash[:0])
  554. return hash
  555. }
  556. // Some weird constants to avoid constant memory allocs for them.
  557. var (
  558. big8 = big.NewInt(8)
  559. big32 = big.NewInt(32)
  560. )
  561. // AccumulateRewards credits the coinbase of the given block with the mining
  562. // reward. The total reward consists of the static block reward and rewards for
  563. // included uncles. The coinbase of each uncle block is also rewarded.
  564. func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
  565. // Select the correct block reward based on chain progression
  566. blockReward := FrontierBlockReward
  567. if config.IsByzantium(header.Number) {
  568. blockReward = ByzantiumBlockReward
  569. }
  570. if config.IsConstantinople(header.Number) {
  571. blockReward = ConstantinopleBlockReward
  572. }
  573. // Accumulate the rewards for the miner and any included uncles
  574. reward := new(big.Int).Set(blockReward)
  575. r := new(big.Int)
  576. for _, uncle := range uncles {
  577. r.Add(uncle.Number, big8)
  578. r.Sub(r, header.Number)
  579. r.Mul(r, blockReward)
  580. r.Div(r, big8)
  581. state.AddBalance(uncle.Coinbase, r)
  582. r.Div(blockReward, big32)
  583. reward.Add(reward, r)
  584. }
  585. state.AddBalance(header.Coinbase, reward)
  586. }