consensus.go 21 KB

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