consensus.go 19 KB

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