consensus.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 its 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. if len(block.Uncles()) == 0 {
  180. return nil
  181. }
  182. // Gather the set of past uncles and ancestors
  183. uncles, ancestors := mapset.NewSet(), make(map[common.Hash]*types.Header)
  184. number, parent := block.NumberU64()-1, block.ParentHash()
  185. for i := 0; i < 7; i++ {
  186. ancestor := chain.GetBlock(parent, number)
  187. if ancestor == nil {
  188. break
  189. }
  190. ancestors[ancestor.Hash()] = ancestor.Header()
  191. for _, uncle := range ancestor.Uncles() {
  192. uncles.Add(uncle.Hash())
  193. }
  194. parent, number = ancestor.ParentHash(), number-1
  195. }
  196. ancestors[block.Hash()] = block.Header()
  197. uncles.Add(block.Hash())
  198. // Verify each of the uncles that it's recent, but not an ancestor
  199. for _, uncle := range block.Uncles() {
  200. // Make sure every uncle is rewarded only once
  201. hash := uncle.Hash()
  202. if uncles.Contains(hash) {
  203. return errDuplicateUncle
  204. }
  205. uncles.Add(hash)
  206. // Make sure the uncle has a valid ancestry
  207. if ancestors[hash] != nil {
  208. return errUncleIsAncestor
  209. }
  210. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
  211. return errDanglingUncle
  212. }
  213. if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
  214. return err
  215. }
  216. }
  217. return nil
  218. }
  219. // verifyHeader checks whether a header conforms to the consensus rules of the
  220. // stock Ethereum ethash engine.
  221. // See YP section 4.3.4. "Block Header Validity"
  222. func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *types.Header, uncle bool, seal bool) error {
  223. // Ensure that the header's extra-data section is of a reasonable size
  224. if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
  225. return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
  226. }
  227. // Verify the header's timestamp
  228. if !uncle {
  229. if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
  230. return consensus.ErrFutureBlock
  231. }
  232. }
  233. if header.Time <= parent.Time {
  234. return errZeroBlockTime
  235. }
  236. // Verify the block's difficulty based in its timestamp and parent's difficulty
  237. expected := ethash.CalcDifficulty(chain, header.Time, parent)
  238. if expected.Cmp(header.Difficulty) != 0 {
  239. return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
  240. }
  241. // Verify that the gas limit is <= 2^63-1
  242. cap := uint64(0x7fffffffffffffff)
  243. if header.GasLimit > cap {
  244. return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
  245. }
  246. // Verify that the gasUsed is <= gasLimit
  247. if header.GasUsed > header.GasLimit {
  248. return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
  249. }
  250. // Verify that the gas limit remains within allowed bounds
  251. diff := int64(parent.GasLimit) - int64(header.GasLimit)
  252. if diff < 0 {
  253. diff *= -1
  254. }
  255. limit := parent.GasLimit / params.GasLimitBoundDivisor
  256. if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit {
  257. return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit)
  258. }
  259. // Verify that the block number is parent's +1
  260. if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
  261. return consensus.ErrInvalidNumber
  262. }
  263. // Verify the engine specific seal securing the block
  264. if seal {
  265. if err := ethash.VerifySeal(chain, header); err != nil {
  266. return err
  267. }
  268. }
  269. // If all checks passed, validate any special fields for hard forks
  270. if err := misc.VerifyDAOHeaderExtraData(chain.Config(), header); err != nil {
  271. return err
  272. }
  273. if err := misc.VerifyForkHashes(chain.Config(), header, uncle); err != nil {
  274. return err
  275. }
  276. return nil
  277. }
  278. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  279. // the difficulty that a new block should have when created at time
  280. // given the parent block's time and difficulty.
  281. func (ethash *Ethash) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
  282. return CalcDifficulty(chain.Config(), time, parent)
  283. }
  284. // CalcDifficulty is the difficulty adjustment algorithm. It returns
  285. // the difficulty that a new block should have when created at time
  286. // given the parent block's time and difficulty.
  287. func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
  288. next := new(big.Int).Add(parent.Number, big1)
  289. switch {
  290. case config.IsConstantinople(next):
  291. return calcDifficultyConstantinople(time, parent)
  292. case config.IsByzantium(next):
  293. return calcDifficultyByzantium(time, parent)
  294. case config.IsHomestead(next):
  295. return calcDifficultyHomestead(time, parent)
  296. default:
  297. return calcDifficultyFrontier(time, parent)
  298. }
  299. }
  300. // Some weird constants to avoid constant memory allocs for them.
  301. var (
  302. expDiffPeriod = big.NewInt(100000)
  303. big1 = big.NewInt(1)
  304. big2 = big.NewInt(2)
  305. big9 = big.NewInt(9)
  306. big10 = big.NewInt(10)
  307. bigMinus99 = big.NewInt(-99)
  308. )
  309. // makeDifficultyCalculator creates a difficultyCalculator with the given bomb-delay.
  310. // the difficulty is calculated with Byzantium rules, which differs from Homestead in
  311. // how uncles affect the calculation
  312. func makeDifficultyCalculator(bombDelay *big.Int) func(time uint64, parent *types.Header) *big.Int {
  313. // Note, the calculations below looks at the parent number, which is 1 below
  314. // the block number. Thus we remove one from the delay given
  315. bombDelayFromParent := new(big.Int).Sub(bombDelay, big1)
  316. return func(time uint64, parent *types.Header) *big.Int {
  317. // https://github.com/ethereum/EIPs/issues/100.
  318. // algorithm:
  319. // diff = (parent_diff +
  320. // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  321. // ) + 2^(periodCount - 2)
  322. bigTime := new(big.Int).SetUint64(time)
  323. bigParentTime := new(big.Int).SetUint64(parent.Time)
  324. // holds intermediate values to make the algo easier to read & audit
  325. x := new(big.Int)
  326. y := new(big.Int)
  327. // (2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9
  328. x.Sub(bigTime, bigParentTime)
  329. x.Div(x, big9)
  330. if parent.UncleHash == types.EmptyUncleHash {
  331. x.Sub(big1, x)
  332. } else {
  333. x.Sub(big2, x)
  334. }
  335. // max((2 if len(parent_uncles) else 1) - (block_timestamp - parent_timestamp) // 9, -99)
  336. if x.Cmp(bigMinus99) < 0 {
  337. x.Set(bigMinus99)
  338. }
  339. // parent_diff + (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99))
  340. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  341. x.Mul(y, x)
  342. x.Add(parent.Difficulty, x)
  343. // minimum difficulty can ever be (before exponential factor)
  344. if x.Cmp(params.MinimumDifficulty) < 0 {
  345. x.Set(params.MinimumDifficulty)
  346. }
  347. // calculate a fake block number for the ice-age delay
  348. // Specification: https://eips.ethereum.org/EIPS/eip-1234
  349. fakeBlockNumber := new(big.Int)
  350. if parent.Number.Cmp(bombDelayFromParent) >= 0 {
  351. fakeBlockNumber = fakeBlockNumber.Sub(parent.Number, bombDelayFromParent)
  352. }
  353. // for the exponential factor
  354. periodCount := fakeBlockNumber
  355. periodCount.Div(periodCount, expDiffPeriod)
  356. // the exponential factor, commonly referred to as "the bomb"
  357. // diff = diff + 2^(periodCount - 2)
  358. if periodCount.Cmp(big1) > 0 {
  359. y.Sub(periodCount, big2)
  360. y.Exp(big2, y, nil)
  361. x.Add(x, y)
  362. }
  363. return x
  364. }
  365. }
  366. // calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
  367. // the difficulty that a new block should have when created at time given the
  368. // parent block's time and difficulty. The calculation uses the Homestead rules.
  369. func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
  370. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
  371. // algorithm:
  372. // diff = (parent_diff +
  373. // (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  374. // ) + 2^(periodCount - 2)
  375. bigTime := new(big.Int).SetUint64(time)
  376. bigParentTime := new(big.Int).SetUint64(parent.Time)
  377. // holds intermediate values to make the algo easier to read & audit
  378. x := new(big.Int)
  379. y := new(big.Int)
  380. // 1 - (block_timestamp - parent_timestamp) // 10
  381. x.Sub(bigTime, bigParentTime)
  382. x.Div(x, big10)
  383. x.Sub(big1, x)
  384. // max(1 - (block_timestamp - parent_timestamp) // 10, -99)
  385. if x.Cmp(bigMinus99) < 0 {
  386. x.Set(bigMinus99)
  387. }
  388. // (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
  389. y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
  390. x.Mul(y, x)
  391. x.Add(parent.Difficulty, x)
  392. // minimum difficulty can ever be (before exponential factor)
  393. if x.Cmp(params.MinimumDifficulty) < 0 {
  394. x.Set(params.MinimumDifficulty)
  395. }
  396. // for the exponential factor
  397. periodCount := new(big.Int).Add(parent.Number, big1)
  398. periodCount.Div(periodCount, expDiffPeriod)
  399. // the exponential factor, commonly referred to as "the bomb"
  400. // diff = diff + 2^(periodCount - 2)
  401. if periodCount.Cmp(big1) > 0 {
  402. y.Sub(periodCount, big2)
  403. y.Exp(big2, y, nil)
  404. x.Add(x, y)
  405. }
  406. return x
  407. }
  408. // calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
  409. // difficulty that a new block should have when created at time given the parent
  410. // block's time and difficulty. The calculation uses the Frontier rules.
  411. func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
  412. diff := new(big.Int)
  413. adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
  414. bigTime := new(big.Int)
  415. bigParentTime := new(big.Int)
  416. bigTime.SetUint64(time)
  417. bigParentTime.SetUint64(parent.Time)
  418. if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
  419. diff.Add(parent.Difficulty, adjust)
  420. } else {
  421. diff.Sub(parent.Difficulty, adjust)
  422. }
  423. if diff.Cmp(params.MinimumDifficulty) < 0 {
  424. diff.Set(params.MinimumDifficulty)
  425. }
  426. periodCount := new(big.Int).Add(parent.Number, big1)
  427. periodCount.Div(periodCount, expDiffPeriod)
  428. if periodCount.Cmp(big1) > 0 {
  429. // diff = diff + 2^(periodCount - 2)
  430. expDiff := periodCount.Sub(periodCount, big2)
  431. expDiff.Exp(big2, expDiff, nil)
  432. diff.Add(diff, expDiff)
  433. diff = math.BigMax(diff, params.MinimumDifficulty)
  434. }
  435. return diff
  436. }
  437. // VerifySeal implements consensus.Engine, checking whether the given block satisfies
  438. // the PoW difficulty requirements.
  439. func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
  440. return ethash.verifySeal(chain, header, false)
  441. }
  442. // verifySeal checks whether a block satisfies the PoW difficulty requirements,
  443. // either using the usual ethash cache for it, or alternatively using a full DAG
  444. // to make remote mining fast.
  445. func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Header, fulldag bool) error {
  446. // If we're running a fake PoW, accept any seal as valid
  447. if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
  448. time.Sleep(ethash.fakeDelay)
  449. if ethash.fakeFail == header.Number.Uint64() {
  450. return errInvalidPoW
  451. }
  452. return nil
  453. }
  454. // If we're running a shared PoW, delegate verification to it
  455. if ethash.shared != nil {
  456. return ethash.shared.verifySeal(chain, header, fulldag)
  457. }
  458. // Ensure that we have a valid difficulty for the block
  459. if header.Difficulty.Sign() <= 0 {
  460. return errInvalidDifficulty
  461. }
  462. // Recompute the digest and PoW values
  463. number := header.Number.Uint64()
  464. var (
  465. digest []byte
  466. result []byte
  467. )
  468. // If fast-but-heavy PoW verification was requested, use an ethash dataset
  469. if fulldag {
  470. dataset := ethash.dataset(number, true)
  471. if dataset.generated() {
  472. digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  473. // Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
  474. // until after the call to hashimotoFull so it's not unmapped while being used.
  475. runtime.KeepAlive(dataset)
  476. } else {
  477. // Dataset not yet generated, don't hang, use a cache instead
  478. fulldag = false
  479. }
  480. }
  481. // If slow-but-light PoW verification was requested (or DAG not yet ready), use an ethash cache
  482. if !fulldag {
  483. cache := ethash.cache(number)
  484. size := datasetSize(number)
  485. if ethash.config.PowMode == ModeTest {
  486. size = 32 * 1024
  487. }
  488. digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
  489. // Caches are unmapped in a finalizer. Ensure that the cache stays alive
  490. // until after the call to hashimotoLight so it's not unmapped while being used.
  491. runtime.KeepAlive(cache)
  492. }
  493. // Verify the calculated values against the ones provided in the header
  494. if !bytes.Equal(header.MixDigest[:], digest) {
  495. return errInvalidMixDigest
  496. }
  497. target := new(big.Int).Div(two256, header.Difficulty)
  498. if new(big.Int).SetBytes(result).Cmp(target) > 0 {
  499. return errInvalidPoW
  500. }
  501. return nil
  502. }
  503. // Prepare implements consensus.Engine, initializing the difficulty field of a
  504. // header to conform to the ethash protocol. The changes are done inline.
  505. func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
  506. parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
  507. if parent == nil {
  508. return consensus.ErrUnknownAncestor
  509. }
  510. header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
  511. return nil
  512. }
  513. // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
  514. // setting the final state on the header
  515. func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header) {
  516. // Accumulate any block and uncle rewards and commit the final state root
  517. accumulateRewards(chain.Config(), state, header, uncles)
  518. header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  519. }
  520. // FinalizeAndAssemble implements consensus.Engine, accumulating the block and
  521. // uncle rewards, setting the final state and assembling the block.
  522. func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
  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. // Header seems complete, assemble into a block and return
  527. return types.NewBlock(header, txs, uncles, receipts), nil
  528. }
  529. // SealHash returns the hash of a block prior to it being sealed.
  530. func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
  531. hasher := sha3.NewLegacyKeccak256()
  532. rlp.Encode(hasher, []interface{}{
  533. header.ParentHash,
  534. header.UncleHash,
  535. header.Coinbase,
  536. header.Root,
  537. header.TxHash,
  538. header.ReceiptHash,
  539. header.Bloom,
  540. header.Difficulty,
  541. header.Number,
  542. header.GasLimit,
  543. header.GasUsed,
  544. header.Time,
  545. header.Extra,
  546. })
  547. hasher.Sum(hash[:0])
  548. return hash
  549. }
  550. // Some weird constants to avoid constant memory allocs for them.
  551. var (
  552. big8 = big.NewInt(8)
  553. big32 = big.NewInt(32)
  554. )
  555. // AccumulateRewards credits the coinbase of the given block with the mining
  556. // reward. The total reward consists of the static block reward and rewards for
  557. // included uncles. The coinbase of each uncle block is also rewarded.
  558. func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
  559. // Select the correct block reward based on chain progression
  560. blockReward := FrontierBlockReward
  561. if config.IsByzantium(header.Number) {
  562. blockReward = ByzantiumBlockReward
  563. }
  564. if config.IsConstantinople(header.Number) {
  565. blockReward = ConstantinopleBlockReward
  566. }
  567. // Accumulate the rewards for the miner and any included uncles
  568. reward := new(big.Int).Set(blockReward)
  569. r := new(big.Int)
  570. for _, uncle := range uncles {
  571. r.Add(uncle.Number, big8)
  572. r.Sub(r, header.Number)
  573. r.Mul(r, blockReward)
  574. r.Div(r, big8)
  575. state.AddBalance(uncle.Coinbase, r)
  576. r.Div(blockReward, big32)
  577. reward.Add(reward, r)
  578. }
  579. state.AddBalance(header.Coinbase, reward)
  580. }