consensus.go 23 KB

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