consensus.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. allowedFutureBlockTime = 15 * time.Second // Max time 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)
  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. )
  121. for i := 0; i < workers; i++ {
  122. go func() {
  123. for index := range inputs {
  124. errors[index] = ethash.verifyHeaderWorker(chain, headers, seals, index)
  125. done <- index
  126. }
  127. }()
  128. }
  129. errorsOut := make(chan error, len(headers))
  130. go func() {
  131. defer close(inputs)
  132. var (
  133. in, out = 0, 0
  134. checked = make([]bool, len(headers))
  135. inputs = inputs
  136. )
  137. for {
  138. select {
  139. case inputs <- in:
  140. if in++; in == len(headers) {
  141. // Reached end of headers. Stop sending to workers.
  142. inputs = nil
  143. }
  144. case index := <-done:
  145. for checked[index] = true; checked[out]; out++ {
  146. errorsOut <- errors[out]
  147. if out == len(headers)-1 {
  148. return
  149. }
  150. }
  151. case <-abort:
  152. return
  153. }
  154. }
  155. }()
  156. return abort, errorsOut
  157. }
  158. func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool, index int) error {
  159. var parent *types.Header
  160. if index == 0 {
  161. parent = chain.GetHeader(headers[0].ParentHash, headers[0].Number.Uint64()-1)
  162. } else if headers[index-1].Hash() == headers[index].ParentHash {
  163. parent = headers[index-1]
  164. }
  165. if parent == nil {
  166. return consensus.ErrUnknownAncestor
  167. }
  168. if chain.GetHeader(headers[index].Hash(), headers[index].Number.Uint64()) != nil {
  169. return nil // known block
  170. }
  171. return ethash.verifyHeader(chain, headers[index], parent, false, seals[index])
  172. }
  173. // VerifyUncles verifies that the given block's uncles conform to the consensus
  174. // rules of the stock Ethereum ethash engine.
  175. func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
  176. // If we're running a full engine faking, accept any input as valid
  177. if ethash.config.PowMode == ModeFullFake {
  178. return nil
  179. }
  180. // Verify that there are at most 2 uncles included in this block
  181. if len(block.Uncles()) > maxUncles {
  182. return errTooManyUncles
  183. }
  184. if len(block.Uncles()) == 0 {
  185. return nil
  186. }
  187. // Gather the set of past uncles and ancestors
  188. uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
  189. number, parent := block.NumberU64()-1, block.ParentHash()
  190. for i := 0; i < 7; i++ {
  191. ancestor := chain.GetBlock(parent, number)
  192. if ancestor == nil {
  193. break
  194. }
  195. ancestors[ancestor.Hash()] = ancestor.Header()
  196. for _, uncle := range ancestor.Uncles() {
  197. uncles.Add(uncle.Hash())
  198. }
  199. parent, number = ancestor.ParentHash(), number-1
  200. }
  201. ancestors[block.Hash()] = block.Header()
  202. uncles.Add(block.Hash())
  203. // Verify each of the uncles that it's recent, but not an ancestor
  204. for _, uncle := range block.Uncles() {
  205. // Make sure every uncle is rewarded only once
  206. hash := uncle.Hash()
  207. if uncles.Contains(hash) {
  208. return errDuplicateUncle
  209. }
  210. uncles.Add(hash)
  211. // Make sure the uncle has a valid ancestry
  212. if ancestors[hash] != nil {
  213. return errUncleIsAncestor
  214. }
  215. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
  216. return errDanglingUncle
  217. }
  218. if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
  219. return err
  220. }
  221. }
  222. return nil
  223. }
  224. // verifyHeader checks whether a header conforms to the consensus rules of the
  225. // stock Ethereum ethash engine.
  226. // See YP section 4.3.4. "Block Header Validity"
  227. func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header, uncle bool, seal bool) error {
  228. // Ensure that the header's extra-data section is of a reasonable size
  229. if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
  230. return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
  231. }
  232. // Verify the header's timestamp
  233. if !uncle {
  234. if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
  235. return consensus.ErrFutureBlock
  236. }
  237. }
  238. if header.Time <= parent.Time {
  239. return errOlderBlockTime
  240. }
  241. // Verify the block's difficulty based on its timestamp and parent's difficulty
  242. expected := ethash.CalcDifficulty(chain, header.Time, parent)
  243. if expected.Cmp(header.Difficulty) != 0 {
  244. return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
  245. }
  246. // Verify that the gas limit is <= 2^63-1
  247. cap := uint64(0x7fffffffffffffff)
  248. if header.GasLimit > cap {
  249. return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
  250. }
  251. // Verify that the gasUsed is <= gasLimit
  252. if header.GasUsed > header.GasLimit {
  253. return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
  254. }
  255. // Verify that the gas limit remains within allowed bounds
  256. diff := int64(parent.GasLimit) - int64(header.GasLimit)
  257. if diff < 0 {
  258. diff *= -1
  259. }
  260. limit := parent.GasLimit / params.GasLimitBoundDivisor
  261. if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
  262. return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
  263. }
  264. // Verify that the block number is parent's +1
  265. if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
  266. return consensus.ErrInvalidNumber
  267. }
  268. // Verify the engine specific seal securing the block
  269. if seal {
  270. if err := ethash.VerifySeal(chain, header); err != nil {
  271. return err
  272. }
  273. }
  274. // If all checks passed, validate any special fields for hard forks
  275. if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
  276. return err
  277. }
  278. if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
  279. return err
  280. }
  281. return nil
  282. }
  283. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  284. // the difficulty that a new block should have when created at time
  285. // given the parent block's time and difficulty.
  286. func (ethash *Ethash) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
  287. return CalcDifficulty(chain.Config(), time, parent)
  288. }
  289. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  290. // the difficulty that a new block should have when created at time
  291. // given the parent block's time and difficulty.
  292. func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
  293. next := new(big.Int).Add(parent.Number, big1)
  294. switch {
  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. // VerifySeal implements consensus.Engine, checking whether the given block satisfies
  445. // the PoW difficulty requirements.
  446. func (ethash *Ethash) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error {
  447. return ethash.verifySeal(chain, header, false)
  448. }
  449. // verifySeal checks whether a block satisfies the PoW difficulty requirements,
  450. // either using the usual ethash cache for it, or alternatively using a full DAG
  451. // to make remote mining fast.
  452. func (ethash *Ethash) verifySeal(chain consensus.ChainHeaderReader, header *types.Header, fulldag bool) error {
  453. // If we're running a fake PoW, accept any seal as valid
  454. if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
  455. time.Sleep(ethash.fakeDelay)
  456. if ethash.fakeFail == header.Number.Uint64() {
  457. return errInvalidPoW
  458. }
  459. return nil
  460. }
  461. // If we're running a shared PoW, delegate verification to it
  462. if ethash.shared != nil {
  463. return ethash.shared.verifySeal(chain, header, fulldag)
  464. }
  465. // Ensure that we have a valid difficulty for the block
  466. if header.Difficulty.Sign() <= 0 {
  467. return errInvalidDifficulty
  468. }
  469. // Recompute the digest and PoW values
  470. number := header.Number.Uint64()
  471. var (
  472. digest []byte
  473. result []byte
  474. )
  475. // If fast-but-heavy PoW verification was requested, use an ethash dataset
  476. if fulldag {
  477. dataset := ethash.dataset(number, true)
  478. if dataset.generated() {
  479. digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  480. // Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
  481. // until after the call to hashimotoFull so it's not unmapped while being used.
  482. runtime.KeepAlive(dataset)
  483. } else {
  484. // Dataset not yet generated, don't hang, use a cache instead
  485. fulldag = false
  486. }
  487. }
  488. // If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
  489. if !fulldag {
  490. cache := ethash.cache(number)
  491. size := datasetSize(number)
  492. if ethash.config.PowMode == ModeTest {
  493. size = 32 * 1024
  494. }
  495. digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  496. // Caches are unmapped in a finalizer. Ensure that the cache stays alive
  497. // until after the call to hashimotoLight so it's not unmapped while being used.
  498. runtime.KeepAlive(cache)
  499. }
  500. // Verify the calculated values against the ones provided in the header
  501. if !bytes.Equal(header.MixDigest[:], digest) {
  502. return errInvalidMixDigest
  503. }
  504. target := new(big.Int).Div(two256, header.Difficulty)
  505. if new(big.Int).SetBytes(result).Cmp(target) > 0 {
  506. return errInvalidPoW
  507. }
  508. return nil
  509. }
  510. // Prepare implements consensus.Engine, initializing the difficulty field of a
  511. // header to conform to the ethash protocol. The changes are done inline.
  512. func (ethash *Ethash) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
  513. parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
  514. if parent == nil {
  515. return consensus.ErrUnknownAncestor
  516. }
  517. header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
  518. return nil
  519. }
  520. // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
  521. // setting the final state on the header
  522. func (ethash *Ethash) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
  523. // Accumulate any block and uncle rewards and commit the final state root
  524. accumulateRewards(chain.Config(), state, header, uncles)
  525. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  526. }
  527. // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
  528. // uncle rewards, setting the final state and assembling the block.
  529. 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) {
  530. // Accumulate any block and uncle rewards and commit the final state root
  531. accumulateRewards(chain.Config(), state, header, uncles)
  532. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  533. // Header seems complete, assemble into a block and return
  534. return types.NewBlock(header, txs, uncles, receipts, new(trie.Trie)), nil
  535. }
  536. // SealHash returns the hash of a block prior to it being sealed.
  537. func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
  538. hasher := sha3.NewLegacyKeccak256()
  539. rlp.Encode(hasher, []interface{}{
  540. header.ParentHash,
  541. header.UncleHash,
  542. header.Coinbase,
  543. header.Root,
  544. header.TxHash,
  545. header.ReceiptHash,
  546. header.Bloom,
  547. header.Difficulty,
  548. header.Number,
  549. header.GasLimit,
  550. header.GasUsed,
  551. header.Time,
  552. header.Extra,
  553. })
  554. hasher.Sum(hash[:0])
  555. return hash
  556. }
  557. // Some weird constants to avoid constant memory allocs for them.
  558. var (
  559. big8 = big.NewInt(8)
  560. big32 = big.NewInt(32)
  561. )
  562. // AccumulateRewards credits the coinbase of the given block with the mining
  563. // reward. The total reward consists of the static block reward and rewards for
  564. // included uncles. The coinbase of each uncle block is also rewarded.
  565. func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
  566. // Select the correct block reward based on chain progression
  567. blockReward := FrontierBlockReward
  568. if config.IsByzantium(header.Number) {
  569. blockReward = ByzantiumBlockReward
  570. }
  571. if config.IsConstantinople(header.Number) {
  572. blockReward = ConstantinopleBlockReward
  573. }
  574. // Accumulate the rewards for the miner and any included uncles
  575. reward := new(big.Int).Set(blockReward)
  576. r := new(big.Int)
  577. for _, uncle := range uncles {
  578. r.Add(uncle.Number, big8)
  579. r.Sub(r, header.Number)
  580. r.Mul(r, blockReward)
  581. r.Div(r, big8)
  582. state.AddBalance(uncle.Coinbase, r)
  583. r.Div(blockReward, big32)
  584. reward.Add(reward, r)
  585. }
  586. state.AddBalance(header.Coinbase, reward)
  587. }