consensus.go 22 KB

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